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 let text = include_text(server.as_ref()).then(|| buffer.read(cx).text());
2277
2278 server
2279 .notify::<lsp::notification::DidSaveTextDocument>(
2280 lsp::DidSaveTextDocumentParams {
2281 text_document: text_document.clone(),
2282 text,
2283 },
2284 )
2285 .log_err();
2286 }
2287
2288 let language_server_ids = self.language_server_ids_for_buffer(buffer.read(cx), cx);
2289 for language_server_id in language_server_ids {
2290 if let Some(LanguageServerState::Running {
2291 adapter,
2292 simulate_disk_based_diagnostics_completion,
2293 ..
2294 }) = self.language_servers.get_mut(&language_server_id)
2295 {
2296 // After saving a buffer using a language server that doesn't provide
2297 // a disk-based progress token, kick off a timer that will reset every
2298 // time the buffer is saved. If the timer eventually fires, simulate
2299 // disk-based diagnostics being finished so that other pieces of UI
2300 // (e.g., project diagnostics view, diagnostic status bar) can update.
2301 // We don't emit an event right away because the language server might take
2302 // some time to publish diagnostics.
2303 if adapter.disk_based_diagnostics_progress_token.is_none() {
2304 const DISK_BASED_DIAGNOSTICS_DEBOUNCE: Duration =
2305 Duration::from_secs(1);
2306
2307 let task = cx.spawn_weak(|this, mut cx| async move {
2308 cx.background().timer(DISK_BASED_DIAGNOSTICS_DEBOUNCE).await;
2309 if let Some(this) = this.upgrade(&cx) {
2310 this.update(&mut cx, |this, cx| {
2311 this.disk_based_diagnostics_finished(
2312 language_server_id,
2313 cx,
2314 );
2315 this.buffer_ordered_messages_tx
2316 .unbounded_send(
2317 BufferOrderedMessage::LanguageServerUpdate {
2318 language_server_id,
2319 message:proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(Default::default())
2320 },
2321 )
2322 .ok();
2323 });
2324 }
2325 });
2326 *simulate_disk_based_diagnostics_completion = Some(task);
2327 }
2328 }
2329 }
2330 }
2331
2332 _ => {}
2333 }
2334
2335 None
2336 }
2337
2338 fn request_buffer_diff_recalculation(
2339 &mut self,
2340 buffer: &ModelHandle<Buffer>,
2341 cx: &mut ModelContext<Self>,
2342 ) {
2343 self.buffers_needing_diff.insert(buffer.downgrade());
2344 let first_insertion = self.buffers_needing_diff.len() == 1;
2345
2346 let settings = settings::get::<ProjectSettings>(cx);
2347 let delay = if let Some(delay) = settings.git.gutter_debounce {
2348 delay
2349 } else {
2350 if first_insertion {
2351 let this = cx.weak_handle();
2352 cx.defer(move |cx| {
2353 if let Some(this) = this.upgrade(cx) {
2354 this.update(cx, |this, cx| {
2355 this.recalculate_buffer_diffs(cx).detach();
2356 });
2357 }
2358 });
2359 }
2360 return;
2361 };
2362
2363 const MIN_DELAY: u64 = 50;
2364 let delay = delay.max(MIN_DELAY);
2365 let duration = Duration::from_millis(delay);
2366
2367 self.git_diff_debouncer
2368 .fire_new(duration, cx, move |this, cx| {
2369 this.recalculate_buffer_diffs(cx)
2370 });
2371 }
2372
2373 fn recalculate_buffer_diffs(&mut self, cx: &mut ModelContext<Self>) -> Task<()> {
2374 cx.spawn(|this, mut cx| async move {
2375 let buffers: Vec<_> = this.update(&mut cx, |this, _| {
2376 this.buffers_needing_diff.drain().collect()
2377 });
2378
2379 let tasks: Vec<_> = this.update(&mut cx, |_, cx| {
2380 buffers
2381 .iter()
2382 .filter_map(|buffer| {
2383 let buffer = buffer.upgrade(cx)?;
2384 buffer.update(cx, |buffer, cx| buffer.git_diff_recalc(cx))
2385 })
2386 .collect()
2387 });
2388
2389 futures::future::join_all(tasks).await;
2390
2391 this.update(&mut cx, |this, cx| {
2392 if !this.buffers_needing_diff.is_empty() {
2393 this.recalculate_buffer_diffs(cx).detach();
2394 } else {
2395 // TODO: Would a `ModelContext<Project>.notify()` suffice here?
2396 for buffer in buffers {
2397 if let Some(buffer) = buffer.upgrade(cx) {
2398 buffer.update(cx, |_, cx| cx.notify());
2399 }
2400 }
2401 }
2402 });
2403 })
2404 }
2405
2406 fn language_servers_for_worktree(
2407 &self,
2408 worktree_id: WorktreeId,
2409 ) -> impl Iterator<Item = (&Arc<CachedLspAdapter>, &Arc<Language>, &Arc<LanguageServer>)> {
2410 self.language_server_ids
2411 .iter()
2412 .filter_map(move |((language_server_worktree_id, _), id)| {
2413 if *language_server_worktree_id == worktree_id {
2414 if let Some(LanguageServerState::Running {
2415 adapter,
2416 language,
2417 server,
2418 ..
2419 }) = self.language_servers.get(id)
2420 {
2421 return Some((adapter, language, server));
2422 }
2423 }
2424 None
2425 })
2426 }
2427
2428 fn maintain_buffer_languages(
2429 languages: Arc<LanguageRegistry>,
2430 cx: &mut ModelContext<Project>,
2431 ) -> Task<()> {
2432 let mut subscription = languages.subscribe();
2433 let mut prev_reload_count = languages.reload_count();
2434 cx.spawn_weak(|project, mut cx| async move {
2435 while let Some(()) = subscription.next().await {
2436 if let Some(project) = project.upgrade(&cx) {
2437 // If the language registry has been reloaded, then remove and
2438 // re-assign the languages on all open buffers.
2439 let reload_count = languages.reload_count();
2440 if reload_count > prev_reload_count {
2441 prev_reload_count = reload_count;
2442 project.update(&mut cx, |this, cx| {
2443 let buffers = this
2444 .opened_buffers
2445 .values()
2446 .filter_map(|b| b.upgrade(cx))
2447 .collect::<Vec<_>>();
2448 for buffer in buffers {
2449 if let Some(f) = File::from_dyn(buffer.read(cx).file()).cloned() {
2450 this.unregister_buffer_from_language_servers(&buffer, &f, cx);
2451 buffer.update(cx, |buffer, cx| buffer.set_language(None, cx));
2452 }
2453 }
2454 });
2455 }
2456
2457 project.update(&mut cx, |project, cx| {
2458 let mut plain_text_buffers = Vec::new();
2459 let mut buffers_with_unknown_injections = Vec::new();
2460 for buffer in project.opened_buffers.values() {
2461 if let Some(handle) = buffer.upgrade(cx) {
2462 let buffer = &handle.read(cx);
2463 if buffer.language().is_none()
2464 || buffer.language() == Some(&*language::PLAIN_TEXT)
2465 {
2466 plain_text_buffers.push(handle);
2467 } else if buffer.contains_unknown_injections() {
2468 buffers_with_unknown_injections.push(handle);
2469 }
2470 }
2471 }
2472
2473 for buffer in plain_text_buffers {
2474 project.detect_language_for_buffer(&buffer, cx);
2475 project.register_buffer_with_language_servers(&buffer, cx);
2476 }
2477
2478 for buffer in buffers_with_unknown_injections {
2479 buffer.update(cx, |buffer, cx| buffer.reparse(cx));
2480 }
2481 });
2482 }
2483 }
2484 })
2485 }
2486
2487 fn maintain_workspace_config(cx: &mut ModelContext<Project>) -> Task<()> {
2488 let (mut settings_changed_tx, mut settings_changed_rx) = watch::channel();
2489 let _ = postage::stream::Stream::try_recv(&mut settings_changed_rx);
2490
2491 let settings_observation = cx.observe_global::<SettingsStore, _>(move |_, _| {
2492 *settings_changed_tx.borrow_mut() = ();
2493 });
2494
2495 cx.spawn_weak(|this, mut cx| async move {
2496 while let Some(_) = settings_changed_rx.next().await {
2497 let Some(this) = this.upgrade(&cx) else {
2498 break;
2499 };
2500
2501 let servers: Vec<_> = this.read_with(&cx, |this, _| {
2502 this.language_servers
2503 .values()
2504 .filter_map(|state| match state {
2505 LanguageServerState::Starting(_) => None,
2506 LanguageServerState::Running {
2507 adapter, server, ..
2508 } => Some((adapter.clone(), server.clone())),
2509 })
2510 .collect()
2511 });
2512
2513 for (adapter, server) in servers {
2514 let workspace_config =
2515 cx.update(|cx| adapter.workspace_configuration(cx)).await;
2516 server
2517 .notify::<lsp::notification::DidChangeConfiguration>(
2518 lsp::DidChangeConfigurationParams {
2519 settings: workspace_config.clone(),
2520 },
2521 )
2522 .ok();
2523 }
2524 }
2525
2526 drop(settings_observation);
2527 })
2528 }
2529
2530 fn detect_language_for_buffer(
2531 &mut self,
2532 buffer_handle: &ModelHandle<Buffer>,
2533 cx: &mut ModelContext<Self>,
2534 ) -> Option<()> {
2535 // If the buffer has a language, set it and start the language server if we haven't already.
2536 let buffer = buffer_handle.read(cx);
2537 let full_path = buffer.file()?.full_path(cx);
2538 let content = buffer.as_rope();
2539 let new_language = self
2540 .languages
2541 .language_for_file(&full_path, Some(content))
2542 .now_or_never()?
2543 .ok()?;
2544 self.set_language_for_buffer(buffer_handle, new_language, cx);
2545 None
2546 }
2547
2548 pub fn set_language_for_buffer(
2549 &mut self,
2550 buffer: &ModelHandle<Buffer>,
2551 new_language: Arc<Language>,
2552 cx: &mut ModelContext<Self>,
2553 ) {
2554 buffer.update(cx, |buffer, cx| {
2555 if buffer.language().map_or(true, |old_language| {
2556 !Arc::ptr_eq(old_language, &new_language)
2557 }) {
2558 buffer.set_language(Some(new_language.clone()), cx);
2559 }
2560 });
2561
2562 if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
2563 let worktree = file.worktree.clone();
2564 if let Some(tree) = worktree.read(cx).as_local() {
2565 self.start_language_servers(&worktree, tree.abs_path().clone(), new_language, cx);
2566 }
2567 }
2568 }
2569
2570 fn start_language_servers(
2571 &mut self,
2572 worktree: &ModelHandle<Worktree>,
2573 worktree_path: Arc<Path>,
2574 language: Arc<Language>,
2575 cx: &mut ModelContext<Self>,
2576 ) {
2577 let root_file = worktree.update(cx, |tree, cx| tree.root_file(cx));
2578 let settings = language_settings(Some(&language), root_file.map(|f| f as _).as_ref(), cx);
2579 if !settings.enable_language_server {
2580 return;
2581 }
2582
2583 let worktree_id = worktree.read(cx).id();
2584 for adapter in language.lsp_adapters() {
2585 self.start_language_server(
2586 worktree_id,
2587 worktree_path.clone(),
2588 adapter.clone(),
2589 language.clone(),
2590 cx,
2591 );
2592 }
2593 }
2594
2595 fn start_language_server(
2596 &mut self,
2597 worktree_id: WorktreeId,
2598 worktree_path: Arc<Path>,
2599 adapter: Arc<CachedLspAdapter>,
2600 language: Arc<Language>,
2601 cx: &mut ModelContext<Self>,
2602 ) {
2603 let key = (worktree_id, adapter.name.clone());
2604 if self.language_server_ids.contains_key(&key) {
2605 return;
2606 }
2607
2608 let pending_server = match self.languages.create_pending_language_server(
2609 language.clone(),
2610 adapter.clone(),
2611 worktree_path,
2612 ProjectLspAdapterDelegate::new(self, cx),
2613 cx,
2614 ) {
2615 Some(pending_server) => pending_server,
2616 None => return,
2617 };
2618
2619 let project_settings = settings::get::<ProjectSettings>(cx);
2620 let lsp = project_settings.lsp.get(&adapter.name.0);
2621 let override_options = lsp.map(|s| s.initialization_options.clone()).flatten();
2622
2623 let mut initialization_options = adapter.initialization_options.clone();
2624 match (&mut initialization_options, override_options) {
2625 (Some(initialization_options), Some(override_options)) => {
2626 merge_json_value_into(override_options, initialization_options);
2627 }
2628 (None, override_options) => initialization_options = override_options,
2629 _ => {}
2630 }
2631
2632 let server_id = pending_server.server_id;
2633 let container_dir = pending_server.container_dir.clone();
2634 let state = LanguageServerState::Starting({
2635 let adapter = adapter.clone();
2636 let server_name = adapter.name.0.clone();
2637 let language = language.clone();
2638 let key = key.clone();
2639
2640 cx.spawn_weak(|this, mut cx| async move {
2641 let result = Self::setup_and_insert_language_server(
2642 this,
2643 initialization_options,
2644 pending_server,
2645 adapter.clone(),
2646 language.clone(),
2647 server_id,
2648 key,
2649 &mut cx,
2650 )
2651 .await;
2652
2653 match result {
2654 Ok(server) => server,
2655
2656 Err(err) => {
2657 log::error!("failed to start language server {:?}: {}", server_name, err);
2658
2659 if let Some(this) = this.upgrade(&cx) {
2660 if let Some(container_dir) = container_dir {
2661 let installation_test_binary = adapter
2662 .installation_test_binary(container_dir.to_path_buf())
2663 .await;
2664
2665 this.update(&mut cx, |_, cx| {
2666 Self::check_errored_server(
2667 language,
2668 adapter,
2669 server_id,
2670 installation_test_binary,
2671 cx,
2672 )
2673 });
2674 }
2675 }
2676
2677 None
2678 }
2679 }
2680 })
2681 });
2682
2683 self.language_servers.insert(server_id, state);
2684 self.language_server_ids.insert(key, server_id);
2685 }
2686
2687 fn reinstall_language_server(
2688 &mut self,
2689 language: Arc<Language>,
2690 adapter: Arc<CachedLspAdapter>,
2691 server_id: LanguageServerId,
2692 cx: &mut ModelContext<Self>,
2693 ) -> Option<Task<()>> {
2694 log::info!("beginning to reinstall server");
2695
2696 let existing_server = match self.language_servers.remove(&server_id) {
2697 Some(LanguageServerState::Running { server, .. }) => Some(server),
2698 _ => None,
2699 };
2700
2701 for worktree in &self.worktrees {
2702 if let Some(worktree) = worktree.upgrade(cx) {
2703 let key = (worktree.read(cx).id(), adapter.name.clone());
2704 self.language_server_ids.remove(&key);
2705 }
2706 }
2707
2708 Some(cx.spawn(move |this, mut cx| async move {
2709 if let Some(task) = existing_server.and_then(|server| server.shutdown()) {
2710 log::info!("shutting down existing server");
2711 task.await;
2712 }
2713
2714 // TODO: This is race-safe with regards to preventing new instances from
2715 // starting while deleting, but existing instances in other projects are going
2716 // to be very confused and messed up
2717 this.update(&mut cx, |this, cx| {
2718 this.languages.delete_server_container(adapter.clone(), cx)
2719 })
2720 .await;
2721
2722 this.update(&mut cx, |this, mut cx| {
2723 let worktrees = this.worktrees.clone();
2724 for worktree in worktrees {
2725 let worktree = match worktree.upgrade(cx) {
2726 Some(worktree) => worktree.read(cx),
2727 None => continue,
2728 };
2729 let worktree_id = worktree.id();
2730 let root_path = worktree.abs_path();
2731
2732 this.start_language_server(
2733 worktree_id,
2734 root_path,
2735 adapter.clone(),
2736 language.clone(),
2737 &mut cx,
2738 );
2739 }
2740 })
2741 }))
2742 }
2743
2744 async fn setup_and_insert_language_server(
2745 this: WeakModelHandle<Self>,
2746 initialization_options: Option<serde_json::Value>,
2747 pending_server: PendingLanguageServer,
2748 adapter: Arc<CachedLspAdapter>,
2749 language: Arc<Language>,
2750 server_id: LanguageServerId,
2751 key: (WorktreeId, LanguageServerName),
2752 cx: &mut AsyncAppContext,
2753 ) -> Result<Option<Arc<LanguageServer>>> {
2754 let setup = Self::setup_pending_language_server(
2755 this,
2756 initialization_options,
2757 pending_server,
2758 adapter.clone(),
2759 server_id,
2760 cx,
2761 );
2762
2763 let language_server = match setup.await? {
2764 Some(language_server) => language_server,
2765 None => return Ok(None),
2766 };
2767 let this = match this.upgrade(cx) {
2768 Some(this) => this,
2769 None => return Err(anyhow!("failed to upgrade project handle")),
2770 };
2771
2772 this.update(cx, |this, cx| {
2773 this.insert_newly_running_language_server(
2774 language,
2775 adapter,
2776 language_server.clone(),
2777 server_id,
2778 key,
2779 cx,
2780 )
2781 })?;
2782
2783 Ok(Some(language_server))
2784 }
2785
2786 async fn setup_pending_language_server(
2787 this: WeakModelHandle<Self>,
2788 initialization_options: Option<serde_json::Value>,
2789 pending_server: PendingLanguageServer,
2790 adapter: Arc<CachedLspAdapter>,
2791 server_id: LanguageServerId,
2792 cx: &mut AsyncAppContext,
2793 ) -> Result<Option<Arc<LanguageServer>>> {
2794 let workspace_config = cx.update(|cx| adapter.workspace_configuration(cx)).await;
2795 let language_server = match pending_server.task.await? {
2796 Some(server) => server,
2797 None => return Ok(None),
2798 };
2799
2800 language_server
2801 .on_notification::<lsp::notification::PublishDiagnostics, _>({
2802 let adapter = adapter.clone();
2803 move |mut params, mut cx| {
2804 let this = this;
2805 let adapter = adapter.clone();
2806 adapter.process_diagnostics(&mut params);
2807 if let Some(this) = this.upgrade(&cx) {
2808 this.update(&mut cx, |this, cx| {
2809 this.update_diagnostics(
2810 server_id,
2811 params,
2812 &adapter.disk_based_diagnostic_sources,
2813 cx,
2814 )
2815 .log_err();
2816 });
2817 }
2818 }
2819 })
2820 .detach();
2821
2822 language_server
2823 .on_request::<lsp::request::WorkspaceConfiguration, _, _>({
2824 let adapter = adapter.clone();
2825 move |params, mut cx| {
2826 let adapter = adapter.clone();
2827 async move {
2828 let workspace_config =
2829 cx.update(|cx| adapter.workspace_configuration(cx)).await;
2830 Ok(params
2831 .items
2832 .into_iter()
2833 .map(|item| {
2834 if let Some(section) = &item.section {
2835 workspace_config
2836 .get(section)
2837 .cloned()
2838 .unwrap_or(serde_json::Value::Null)
2839 } else {
2840 workspace_config.clone()
2841 }
2842 })
2843 .collect())
2844 }
2845 }
2846 })
2847 .detach();
2848
2849 // Even though we don't have handling for these requests, respond to them to
2850 // avoid stalling any language server like `gopls` which waits for a response
2851 // to these requests when initializing.
2852 language_server
2853 .on_request::<lsp::request::WorkDoneProgressCreate, _, _>(
2854 move |params, mut cx| async move {
2855 if let Some(this) = this.upgrade(&cx) {
2856 this.update(&mut cx, |this, _| {
2857 if let Some(status) = this.language_server_statuses.get_mut(&server_id)
2858 {
2859 if let lsp::NumberOrString::String(token) = params.token {
2860 status.progress_tokens.insert(token);
2861 }
2862 }
2863 });
2864 }
2865 Ok(())
2866 },
2867 )
2868 .detach();
2869 language_server
2870 .on_request::<lsp::request::RegisterCapability, _, _>({
2871 move |params, mut cx| async move {
2872 let this = this
2873 .upgrade(&cx)
2874 .ok_or_else(|| anyhow!("project dropped"))?;
2875 for reg in params.registrations {
2876 if reg.method == "workspace/didChangeWatchedFiles" {
2877 if let Some(options) = reg.register_options {
2878 let options = serde_json::from_value(options)?;
2879 this.update(&mut cx, |this, cx| {
2880 this.on_lsp_did_change_watched_files(server_id, options, cx);
2881 });
2882 }
2883 }
2884 }
2885 Ok(())
2886 }
2887 })
2888 .detach();
2889
2890 language_server
2891 .on_request::<lsp::request::ApplyWorkspaceEdit, _, _>({
2892 let adapter = adapter.clone();
2893 move |params, cx| {
2894 Self::on_lsp_workspace_edit(this, params, server_id, adapter.clone(), cx)
2895 }
2896 })
2897 .detach();
2898
2899 language_server
2900 .on_request::<lsp::request::InlayHintRefreshRequest, _, _>({
2901 move |(), mut cx| async move {
2902 let this = this
2903 .upgrade(&cx)
2904 .ok_or_else(|| anyhow!("project dropped"))?;
2905 this.update(&mut cx, |project, cx| {
2906 cx.emit(Event::RefreshInlayHints);
2907 project.remote_id().map(|project_id| {
2908 project.client.send(proto::RefreshInlayHints { project_id })
2909 })
2910 })
2911 .transpose()?;
2912 Ok(())
2913 }
2914 })
2915 .detach();
2916
2917 let disk_based_diagnostics_progress_token =
2918 adapter.disk_based_diagnostics_progress_token.clone();
2919
2920 language_server
2921 .on_notification::<lsp::notification::Progress, _>(move |params, mut cx| {
2922 if let Some(this) = this.upgrade(&cx) {
2923 this.update(&mut cx, |this, cx| {
2924 this.on_lsp_progress(
2925 params,
2926 server_id,
2927 disk_based_diagnostics_progress_token.clone(),
2928 cx,
2929 );
2930 });
2931 }
2932 })
2933 .detach();
2934
2935 let language_server = language_server.initialize(initialization_options).await?;
2936
2937 language_server
2938 .notify::<lsp::notification::DidChangeConfiguration>(
2939 lsp::DidChangeConfigurationParams {
2940 settings: workspace_config,
2941 },
2942 )
2943 .ok();
2944
2945 Ok(Some(language_server))
2946 }
2947
2948 fn insert_newly_running_language_server(
2949 &mut self,
2950 language: Arc<Language>,
2951 adapter: Arc<CachedLspAdapter>,
2952 language_server: Arc<LanguageServer>,
2953 server_id: LanguageServerId,
2954 key: (WorktreeId, LanguageServerName),
2955 cx: &mut ModelContext<Self>,
2956 ) -> Result<()> {
2957 // If the language server for this key doesn't match the server id, don't store the
2958 // server. Which will cause it to be dropped, killing the process
2959 if self
2960 .language_server_ids
2961 .get(&key)
2962 .map(|id| id != &server_id)
2963 .unwrap_or(false)
2964 {
2965 return Ok(());
2966 }
2967
2968 // Update language_servers collection with Running variant of LanguageServerState
2969 // indicating that the server is up and running and ready
2970 self.language_servers.insert(
2971 server_id,
2972 LanguageServerState::Running {
2973 adapter: adapter.clone(),
2974 language: language.clone(),
2975 watched_paths: Default::default(),
2976 server: language_server.clone(),
2977 simulate_disk_based_diagnostics_completion: None,
2978 },
2979 );
2980
2981 self.language_server_statuses.insert(
2982 server_id,
2983 LanguageServerStatus {
2984 name: language_server.name().to_string(),
2985 pending_work: Default::default(),
2986 has_pending_diagnostic_updates: false,
2987 progress_tokens: Default::default(),
2988 },
2989 );
2990
2991 cx.emit(Event::LanguageServerAdded(server_id));
2992
2993 if let Some(project_id) = self.remote_id() {
2994 self.client.send(proto::StartLanguageServer {
2995 project_id,
2996 server: Some(proto::LanguageServer {
2997 id: server_id.0 as u64,
2998 name: language_server.name().to_string(),
2999 }),
3000 })?;
3001 }
3002
3003 // Tell the language server about every open buffer in the worktree that matches the language.
3004 for buffer in self.opened_buffers.values() {
3005 if let Some(buffer_handle) = buffer.upgrade(cx) {
3006 let buffer = buffer_handle.read(cx);
3007 let file = match File::from_dyn(buffer.file()) {
3008 Some(file) => file,
3009 None => continue,
3010 };
3011 let language = match buffer.language() {
3012 Some(language) => language,
3013 None => continue,
3014 };
3015
3016 if file.worktree.read(cx).id() != key.0
3017 || !language.lsp_adapters().iter().any(|a| a.name == key.1)
3018 {
3019 continue;
3020 }
3021
3022 let file = match file.as_local() {
3023 Some(file) => file,
3024 None => continue,
3025 };
3026
3027 let versions = self
3028 .buffer_snapshots
3029 .entry(buffer.remote_id())
3030 .or_default()
3031 .entry(server_id)
3032 .or_insert_with(|| {
3033 vec![LspBufferSnapshot {
3034 version: 0,
3035 snapshot: buffer.text_snapshot(),
3036 }]
3037 });
3038
3039 let snapshot = versions.last().unwrap();
3040 let version = snapshot.version;
3041 let initial_snapshot = &snapshot.snapshot;
3042 let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
3043 language_server.notify::<lsp::notification::DidOpenTextDocument>(
3044 lsp::DidOpenTextDocumentParams {
3045 text_document: lsp::TextDocumentItem::new(
3046 uri,
3047 adapter
3048 .language_ids
3049 .get(language.name().as_ref())
3050 .cloned()
3051 .unwrap_or_default(),
3052 version,
3053 initial_snapshot.text(),
3054 ),
3055 },
3056 )?;
3057
3058 buffer_handle.update(cx, |buffer, cx| {
3059 buffer.set_completion_triggers(
3060 language_server
3061 .capabilities()
3062 .completion_provider
3063 .as_ref()
3064 .and_then(|provider| provider.trigger_characters.clone())
3065 .unwrap_or_default(),
3066 cx,
3067 )
3068 });
3069 }
3070 }
3071
3072 cx.notify();
3073 Ok(())
3074 }
3075
3076 // Returns a list of all of the worktrees which no longer have a language server and the root path
3077 // for the stopped server
3078 fn stop_language_server(
3079 &mut self,
3080 worktree_id: WorktreeId,
3081 adapter_name: LanguageServerName,
3082 cx: &mut ModelContext<Self>,
3083 ) -> Task<(Option<PathBuf>, Vec<WorktreeId>)> {
3084 let key = (worktree_id, adapter_name);
3085 if let Some(server_id) = self.language_server_ids.remove(&key) {
3086 log::info!("stopping language server {}", key.1 .0);
3087
3088 // Remove other entries for this language server as well
3089 let mut orphaned_worktrees = vec![worktree_id];
3090 let other_keys = self.language_server_ids.keys().cloned().collect::<Vec<_>>();
3091 for other_key in other_keys {
3092 if self.language_server_ids.get(&other_key) == Some(&server_id) {
3093 self.language_server_ids.remove(&other_key);
3094 orphaned_worktrees.push(other_key.0);
3095 }
3096 }
3097
3098 for buffer in self.opened_buffers.values() {
3099 if let Some(buffer) = buffer.upgrade(cx) {
3100 buffer.update(cx, |buffer, cx| {
3101 buffer.update_diagnostics(server_id, Default::default(), cx);
3102 });
3103 }
3104 }
3105 for worktree in &self.worktrees {
3106 if let Some(worktree) = worktree.upgrade(cx) {
3107 worktree.update(cx, |worktree, cx| {
3108 if let Some(worktree) = worktree.as_local_mut() {
3109 worktree.clear_diagnostics_for_language_server(server_id, cx);
3110 }
3111 });
3112 }
3113 }
3114
3115 self.language_server_statuses.remove(&server_id);
3116 cx.notify();
3117
3118 let server_state = self.language_servers.remove(&server_id);
3119 cx.emit(Event::LanguageServerRemoved(server_id));
3120 cx.spawn_weak(|this, mut cx| async move {
3121 let mut root_path = None;
3122
3123 let server = match server_state {
3124 Some(LanguageServerState::Starting(task)) => task.await,
3125 Some(LanguageServerState::Running { server, .. }) => Some(server),
3126 None => None,
3127 };
3128
3129 if let Some(server) = server {
3130 root_path = Some(server.root_path().clone());
3131 if let Some(shutdown) = server.shutdown() {
3132 shutdown.await;
3133 }
3134 }
3135
3136 if let Some(this) = this.upgrade(&cx) {
3137 this.update(&mut cx, |this, cx| {
3138 this.language_server_statuses.remove(&server_id);
3139 cx.notify();
3140 });
3141 }
3142
3143 (root_path, orphaned_worktrees)
3144 })
3145 } else {
3146 Task::ready((None, Vec::new()))
3147 }
3148 }
3149
3150 pub fn restart_language_servers_for_buffers(
3151 &mut self,
3152 buffers: impl IntoIterator<Item = ModelHandle<Buffer>>,
3153 cx: &mut ModelContext<Self>,
3154 ) -> Option<()> {
3155 let language_server_lookup_info: HashSet<(ModelHandle<Worktree>, Arc<Language>)> = buffers
3156 .into_iter()
3157 .filter_map(|buffer| {
3158 let buffer = buffer.read(cx);
3159 let file = File::from_dyn(buffer.file())?;
3160 let full_path = file.full_path(cx);
3161 let language = self
3162 .languages
3163 .language_for_file(&full_path, Some(buffer.as_rope()))
3164 .now_or_never()?
3165 .ok()?;
3166 Some((file.worktree.clone(), language))
3167 })
3168 .collect();
3169 for (worktree, language) in language_server_lookup_info {
3170 self.restart_language_servers(worktree, language, cx);
3171 }
3172
3173 None
3174 }
3175
3176 // TODO This will break in the case where the adapter's root paths and worktrees are not equal
3177 fn restart_language_servers(
3178 &mut self,
3179 worktree: ModelHandle<Worktree>,
3180 language: Arc<Language>,
3181 cx: &mut ModelContext<Self>,
3182 ) {
3183 let worktree_id = worktree.read(cx).id();
3184 let fallback_path = worktree.read(cx).abs_path();
3185
3186 let mut stops = Vec::new();
3187 for adapter in language.lsp_adapters() {
3188 stops.push(self.stop_language_server(worktree_id, adapter.name.clone(), cx));
3189 }
3190
3191 if stops.is_empty() {
3192 return;
3193 }
3194 let mut stops = stops.into_iter();
3195
3196 cx.spawn_weak(|this, mut cx| async move {
3197 let (original_root_path, mut orphaned_worktrees) = stops.next().unwrap().await;
3198 for stop in stops {
3199 let (_, worktrees) = stop.await;
3200 orphaned_worktrees.extend_from_slice(&worktrees);
3201 }
3202
3203 let this = match this.upgrade(&cx) {
3204 Some(this) => this,
3205 None => return,
3206 };
3207
3208 this.update(&mut cx, |this, cx| {
3209 // Attempt to restart using original server path. Fallback to passed in
3210 // path if we could not retrieve the root path
3211 let root_path = original_root_path
3212 .map(|path_buf| Arc::from(path_buf.as_path()))
3213 .unwrap_or(fallback_path);
3214
3215 this.start_language_servers(&worktree, root_path, language.clone(), cx);
3216
3217 // Lookup new server ids and set them for each of the orphaned worktrees
3218 for adapter in language.lsp_adapters() {
3219 if let Some(new_server_id) = this
3220 .language_server_ids
3221 .get(&(worktree_id, adapter.name.clone()))
3222 .cloned()
3223 {
3224 for &orphaned_worktree in &orphaned_worktrees {
3225 this.language_server_ids
3226 .insert((orphaned_worktree, adapter.name.clone()), new_server_id);
3227 }
3228 }
3229 }
3230 });
3231 })
3232 .detach();
3233 }
3234
3235 fn check_errored_server(
3236 language: Arc<Language>,
3237 adapter: Arc<CachedLspAdapter>,
3238 server_id: LanguageServerId,
3239 installation_test_binary: Option<LanguageServerBinary>,
3240 cx: &mut ModelContext<Self>,
3241 ) {
3242 if !adapter.can_be_reinstalled() {
3243 log::info!(
3244 "Validation check requested for {:?} but it cannot be reinstalled",
3245 adapter.name.0
3246 );
3247 return;
3248 }
3249
3250 cx.spawn(|this, mut cx| async move {
3251 log::info!("About to spawn test binary");
3252
3253 // A lack of test binary counts as a failure
3254 let process = installation_test_binary.and_then(|binary| {
3255 smol::process::Command::new(&binary.path)
3256 .current_dir(&binary.path)
3257 .args(binary.arguments)
3258 .stdin(Stdio::piped())
3259 .stdout(Stdio::piped())
3260 .stderr(Stdio::inherit())
3261 .kill_on_drop(true)
3262 .spawn()
3263 .ok()
3264 });
3265
3266 const PROCESS_TIMEOUT: Duration = Duration::from_secs(5);
3267 let mut timeout = cx.background().timer(PROCESS_TIMEOUT).fuse();
3268
3269 let mut errored = false;
3270 if let Some(mut process) = process {
3271 futures::select! {
3272 status = process.status().fuse() => match status {
3273 Ok(status) => errored = !status.success(),
3274 Err(_) => errored = true,
3275 },
3276
3277 _ = timeout => {
3278 log::info!("test binary time-ed out, this counts as a success");
3279 _ = process.kill();
3280 }
3281 }
3282 } else {
3283 log::warn!("test binary failed to launch");
3284 errored = true;
3285 }
3286
3287 if errored {
3288 log::warn!("test binary check failed");
3289 let task = this.update(&mut cx, move |this, mut cx| {
3290 this.reinstall_language_server(language, adapter, server_id, &mut cx)
3291 });
3292
3293 if let Some(task) = task {
3294 task.await;
3295 }
3296 }
3297 })
3298 .detach();
3299 }
3300
3301 fn on_lsp_progress(
3302 &mut self,
3303 progress: lsp::ProgressParams,
3304 language_server_id: LanguageServerId,
3305 disk_based_diagnostics_progress_token: Option<String>,
3306 cx: &mut ModelContext<Self>,
3307 ) {
3308 let token = match progress.token {
3309 lsp::NumberOrString::String(token) => token,
3310 lsp::NumberOrString::Number(token) => {
3311 log::info!("skipping numeric progress token {}", token);
3312 return;
3313 }
3314 };
3315 let lsp::ProgressParamsValue::WorkDone(progress) = progress.value;
3316 let language_server_status =
3317 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
3318 status
3319 } else {
3320 return;
3321 };
3322
3323 if !language_server_status.progress_tokens.contains(&token) {
3324 return;
3325 }
3326
3327 let is_disk_based_diagnostics_progress = disk_based_diagnostics_progress_token
3328 .as_ref()
3329 .map_or(false, |disk_based_token| {
3330 token.starts_with(disk_based_token)
3331 });
3332
3333 match progress {
3334 lsp::WorkDoneProgress::Begin(report) => {
3335 if is_disk_based_diagnostics_progress {
3336 language_server_status.has_pending_diagnostic_updates = true;
3337 self.disk_based_diagnostics_started(language_server_id, cx);
3338 self.buffer_ordered_messages_tx
3339 .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
3340 language_server_id,
3341 message: proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(Default::default())
3342 })
3343 .ok();
3344 } else {
3345 self.on_lsp_work_start(
3346 language_server_id,
3347 token.clone(),
3348 LanguageServerProgress {
3349 message: report.message.clone(),
3350 percentage: report.percentage.map(|p| p as usize),
3351 last_update_at: Instant::now(),
3352 },
3353 cx,
3354 );
3355 self.buffer_ordered_messages_tx
3356 .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
3357 language_server_id,
3358 message: proto::update_language_server::Variant::WorkStart(
3359 proto::LspWorkStart {
3360 token,
3361 message: report.message,
3362 percentage: report.percentage.map(|p| p as u32),
3363 },
3364 ),
3365 })
3366 .ok();
3367 }
3368 }
3369 lsp::WorkDoneProgress::Report(report) => {
3370 if !is_disk_based_diagnostics_progress {
3371 self.on_lsp_work_progress(
3372 language_server_id,
3373 token.clone(),
3374 LanguageServerProgress {
3375 message: report.message.clone(),
3376 percentage: report.percentage.map(|p| p as usize),
3377 last_update_at: Instant::now(),
3378 },
3379 cx,
3380 );
3381 self.buffer_ordered_messages_tx
3382 .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
3383 language_server_id,
3384 message: proto::update_language_server::Variant::WorkProgress(
3385 proto::LspWorkProgress {
3386 token,
3387 message: report.message,
3388 percentage: report.percentage.map(|p| p as u32),
3389 },
3390 ),
3391 })
3392 .ok();
3393 }
3394 }
3395 lsp::WorkDoneProgress::End(_) => {
3396 language_server_status.progress_tokens.remove(&token);
3397
3398 if is_disk_based_diagnostics_progress {
3399 language_server_status.has_pending_diagnostic_updates = false;
3400 self.disk_based_diagnostics_finished(language_server_id, cx);
3401 self.buffer_ordered_messages_tx
3402 .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
3403 language_server_id,
3404 message:
3405 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
3406 Default::default(),
3407 ),
3408 })
3409 .ok();
3410 } else {
3411 self.on_lsp_work_end(language_server_id, token.clone(), cx);
3412 self.buffer_ordered_messages_tx
3413 .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
3414 language_server_id,
3415 message: proto::update_language_server::Variant::WorkEnd(
3416 proto::LspWorkEnd { token },
3417 ),
3418 })
3419 .ok();
3420 }
3421 }
3422 }
3423 }
3424
3425 fn on_lsp_work_start(
3426 &mut self,
3427 language_server_id: LanguageServerId,
3428 token: String,
3429 progress: LanguageServerProgress,
3430 cx: &mut ModelContext<Self>,
3431 ) {
3432 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
3433 status.pending_work.insert(token, progress);
3434 cx.notify();
3435 }
3436 }
3437
3438 fn on_lsp_work_progress(
3439 &mut self,
3440 language_server_id: LanguageServerId,
3441 token: String,
3442 progress: LanguageServerProgress,
3443 cx: &mut ModelContext<Self>,
3444 ) {
3445 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
3446 let entry = status
3447 .pending_work
3448 .entry(token)
3449 .or_insert(LanguageServerProgress {
3450 message: Default::default(),
3451 percentage: Default::default(),
3452 last_update_at: progress.last_update_at,
3453 });
3454 if progress.message.is_some() {
3455 entry.message = progress.message;
3456 }
3457 if progress.percentage.is_some() {
3458 entry.percentage = progress.percentage;
3459 }
3460 entry.last_update_at = progress.last_update_at;
3461 cx.notify();
3462 }
3463 }
3464
3465 fn on_lsp_work_end(
3466 &mut self,
3467 language_server_id: LanguageServerId,
3468 token: String,
3469 cx: &mut ModelContext<Self>,
3470 ) {
3471 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
3472 cx.emit(Event::RefreshInlayHints);
3473 status.pending_work.remove(&token);
3474 cx.notify();
3475 }
3476 }
3477
3478 fn on_lsp_did_change_watched_files(
3479 &mut self,
3480 language_server_id: LanguageServerId,
3481 params: DidChangeWatchedFilesRegistrationOptions,
3482 cx: &mut ModelContext<Self>,
3483 ) {
3484 if let Some(LanguageServerState::Running { watched_paths, .. }) =
3485 self.language_servers.get_mut(&language_server_id)
3486 {
3487 let mut builders = HashMap::default();
3488 for watcher in params.watchers {
3489 for worktree in &self.worktrees {
3490 if let Some(worktree) = worktree.upgrade(cx) {
3491 let glob_is_inside_worktree = worktree.update(cx, |tree, _| {
3492 if let Some(abs_path) = tree.abs_path().to_str() {
3493 let relative_glob_pattern = match &watcher.glob_pattern {
3494 lsp::GlobPattern::String(s) => s
3495 .strip_prefix(abs_path)
3496 .and_then(|s| s.strip_prefix(std::path::MAIN_SEPARATOR)),
3497 lsp::GlobPattern::Relative(rp) => {
3498 let base_uri = match &rp.base_uri {
3499 lsp::OneOf::Left(workspace_folder) => {
3500 &workspace_folder.uri
3501 }
3502 lsp::OneOf::Right(base_uri) => base_uri,
3503 };
3504 base_uri.to_file_path().ok().and_then(|file_path| {
3505 (file_path.to_str() == Some(abs_path))
3506 .then_some(rp.pattern.as_str())
3507 })
3508 }
3509 };
3510 if let Some(relative_glob_pattern) = relative_glob_pattern {
3511 let literal_prefix =
3512 glob_literal_prefix(&relative_glob_pattern);
3513 tree.as_local_mut()
3514 .unwrap()
3515 .add_path_prefix_to_scan(Path::new(literal_prefix).into());
3516 if let Some(glob) = Glob::new(relative_glob_pattern).log_err() {
3517 builders
3518 .entry(tree.id())
3519 .or_insert_with(|| GlobSetBuilder::new())
3520 .add(glob);
3521 }
3522 return true;
3523 }
3524 }
3525 false
3526 });
3527 if glob_is_inside_worktree {
3528 break;
3529 }
3530 }
3531 }
3532 }
3533
3534 watched_paths.clear();
3535 for (worktree_id, builder) in builders {
3536 if let Ok(globset) = builder.build() {
3537 watched_paths.insert(worktree_id, globset);
3538 }
3539 }
3540
3541 cx.notify();
3542 }
3543 }
3544
3545 async fn on_lsp_workspace_edit(
3546 this: WeakModelHandle<Self>,
3547 params: lsp::ApplyWorkspaceEditParams,
3548 server_id: LanguageServerId,
3549 adapter: Arc<CachedLspAdapter>,
3550 mut cx: AsyncAppContext,
3551 ) -> Result<lsp::ApplyWorkspaceEditResponse> {
3552 let this = this
3553 .upgrade(&cx)
3554 .ok_or_else(|| anyhow!("project project closed"))?;
3555 let language_server = this
3556 .read_with(&cx, |this, _| this.language_server_for_id(server_id))
3557 .ok_or_else(|| anyhow!("language server not found"))?;
3558 let transaction = Self::deserialize_workspace_edit(
3559 this.clone(),
3560 params.edit,
3561 true,
3562 adapter.clone(),
3563 language_server.clone(),
3564 &mut cx,
3565 )
3566 .await
3567 .log_err();
3568 this.update(&mut cx, |this, _| {
3569 if let Some(transaction) = transaction {
3570 this.last_workspace_edits_by_language_server
3571 .insert(server_id, transaction);
3572 }
3573 });
3574 Ok(lsp::ApplyWorkspaceEditResponse {
3575 applied: true,
3576 failed_change: None,
3577 failure_reason: None,
3578 })
3579 }
3580
3581 pub fn language_server_statuses(
3582 &self,
3583 ) -> impl DoubleEndedIterator<Item = &LanguageServerStatus> {
3584 self.language_server_statuses.values()
3585 }
3586
3587 pub fn update_diagnostics(
3588 &mut self,
3589 language_server_id: LanguageServerId,
3590 mut params: lsp::PublishDiagnosticsParams,
3591 disk_based_sources: &[String],
3592 cx: &mut ModelContext<Self>,
3593 ) -> Result<()> {
3594 let abs_path = params
3595 .uri
3596 .to_file_path()
3597 .map_err(|_| anyhow!("URI is not a file"))?;
3598 let mut diagnostics = Vec::default();
3599 let mut primary_diagnostic_group_ids = HashMap::default();
3600 let mut sources_by_group_id = HashMap::default();
3601 let mut supporting_diagnostics = HashMap::default();
3602
3603 // Ensure that primary diagnostics are always the most severe
3604 params.diagnostics.sort_by_key(|item| item.severity);
3605
3606 for diagnostic in ¶ms.diagnostics {
3607 let source = diagnostic.source.as_ref();
3608 let code = diagnostic.code.as_ref().map(|code| match code {
3609 lsp::NumberOrString::Number(code) => code.to_string(),
3610 lsp::NumberOrString::String(code) => code.clone(),
3611 });
3612 let range = range_from_lsp(diagnostic.range);
3613 let is_supporting = diagnostic
3614 .related_information
3615 .as_ref()
3616 .map_or(false, |infos| {
3617 infos.iter().any(|info| {
3618 primary_diagnostic_group_ids.contains_key(&(
3619 source,
3620 code.clone(),
3621 range_from_lsp(info.location.range),
3622 ))
3623 })
3624 });
3625
3626 let is_unnecessary = diagnostic.tags.as_ref().map_or(false, |tags| {
3627 tags.iter().any(|tag| *tag == DiagnosticTag::UNNECESSARY)
3628 });
3629
3630 if is_supporting {
3631 supporting_diagnostics.insert(
3632 (source, code.clone(), range),
3633 (diagnostic.severity, is_unnecessary),
3634 );
3635 } else {
3636 let group_id = post_inc(&mut self.next_diagnostic_group_id);
3637 let is_disk_based =
3638 source.map_or(false, |source| disk_based_sources.contains(source));
3639
3640 sources_by_group_id.insert(group_id, source);
3641 primary_diagnostic_group_ids
3642 .insert((source, code.clone(), range.clone()), group_id);
3643
3644 diagnostics.push(DiagnosticEntry {
3645 range,
3646 diagnostic: Diagnostic {
3647 source: diagnostic.source.clone(),
3648 code: code.clone(),
3649 severity: diagnostic.severity.unwrap_or(DiagnosticSeverity::ERROR),
3650 message: diagnostic.message.clone(),
3651 group_id,
3652 is_primary: true,
3653 is_valid: true,
3654 is_disk_based,
3655 is_unnecessary,
3656 },
3657 });
3658 if let Some(infos) = &diagnostic.related_information {
3659 for info in infos {
3660 if info.location.uri == params.uri && !info.message.is_empty() {
3661 let range = range_from_lsp(info.location.range);
3662 diagnostics.push(DiagnosticEntry {
3663 range,
3664 diagnostic: Diagnostic {
3665 source: diagnostic.source.clone(),
3666 code: code.clone(),
3667 severity: DiagnosticSeverity::INFORMATION,
3668 message: info.message.clone(),
3669 group_id,
3670 is_primary: false,
3671 is_valid: true,
3672 is_disk_based,
3673 is_unnecessary: false,
3674 },
3675 });
3676 }
3677 }
3678 }
3679 }
3680 }
3681
3682 for entry in &mut diagnostics {
3683 let diagnostic = &mut entry.diagnostic;
3684 if !diagnostic.is_primary {
3685 let source = *sources_by_group_id.get(&diagnostic.group_id).unwrap();
3686 if let Some(&(severity, is_unnecessary)) = supporting_diagnostics.get(&(
3687 source,
3688 diagnostic.code.clone(),
3689 entry.range.clone(),
3690 )) {
3691 if let Some(severity) = severity {
3692 diagnostic.severity = severity;
3693 }
3694 diagnostic.is_unnecessary = is_unnecessary;
3695 }
3696 }
3697 }
3698
3699 self.update_diagnostic_entries(
3700 language_server_id,
3701 abs_path,
3702 params.version,
3703 diagnostics,
3704 cx,
3705 )?;
3706 Ok(())
3707 }
3708
3709 pub fn update_diagnostic_entries(
3710 &mut self,
3711 server_id: LanguageServerId,
3712 abs_path: PathBuf,
3713 version: Option<i32>,
3714 diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
3715 cx: &mut ModelContext<Project>,
3716 ) -> Result<(), anyhow::Error> {
3717 let (worktree, relative_path) = self
3718 .find_local_worktree(&abs_path, cx)
3719 .ok_or_else(|| anyhow!("no worktree found for diagnostics path {abs_path:?}"))?;
3720
3721 let project_path = ProjectPath {
3722 worktree_id: worktree.read(cx).id(),
3723 path: relative_path.into(),
3724 };
3725
3726 if let Some(buffer) = self.get_open_buffer(&project_path, cx) {
3727 self.update_buffer_diagnostics(&buffer, server_id, version, diagnostics.clone(), cx)?;
3728 }
3729
3730 let updated = worktree.update(cx, |worktree, cx| {
3731 worktree
3732 .as_local_mut()
3733 .ok_or_else(|| anyhow!("not a local worktree"))?
3734 .update_diagnostics(server_id, project_path.path.clone(), diagnostics, cx)
3735 })?;
3736 if updated {
3737 cx.emit(Event::DiagnosticsUpdated {
3738 language_server_id: server_id,
3739 path: project_path,
3740 });
3741 }
3742 Ok(())
3743 }
3744
3745 fn update_buffer_diagnostics(
3746 &mut self,
3747 buffer: &ModelHandle<Buffer>,
3748 server_id: LanguageServerId,
3749 version: Option<i32>,
3750 mut diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
3751 cx: &mut ModelContext<Self>,
3752 ) -> Result<()> {
3753 fn compare_diagnostics(a: &Diagnostic, b: &Diagnostic) -> Ordering {
3754 Ordering::Equal
3755 .then_with(|| b.is_primary.cmp(&a.is_primary))
3756 .then_with(|| a.is_disk_based.cmp(&b.is_disk_based))
3757 .then_with(|| a.severity.cmp(&b.severity))
3758 .then_with(|| a.message.cmp(&b.message))
3759 }
3760
3761 let snapshot = self.buffer_snapshot_for_lsp_version(buffer, server_id, version, cx)?;
3762
3763 diagnostics.sort_unstable_by(|a, b| {
3764 Ordering::Equal
3765 .then_with(|| a.range.start.cmp(&b.range.start))
3766 .then_with(|| b.range.end.cmp(&a.range.end))
3767 .then_with(|| compare_diagnostics(&a.diagnostic, &b.diagnostic))
3768 });
3769
3770 let mut sanitized_diagnostics = Vec::new();
3771 let edits_since_save = Patch::new(
3772 snapshot
3773 .edits_since::<Unclipped<PointUtf16>>(buffer.read(cx).saved_version())
3774 .collect(),
3775 );
3776 for entry in diagnostics {
3777 let start;
3778 let end;
3779 if entry.diagnostic.is_disk_based {
3780 // Some diagnostics are based on files on disk instead of buffers'
3781 // current contents. Adjust these diagnostics' ranges to reflect
3782 // any unsaved edits.
3783 start = edits_since_save.old_to_new(entry.range.start);
3784 end = edits_since_save.old_to_new(entry.range.end);
3785 } else {
3786 start = entry.range.start;
3787 end = entry.range.end;
3788 }
3789
3790 let mut range = snapshot.clip_point_utf16(start, Bias::Left)
3791 ..snapshot.clip_point_utf16(end, Bias::Right);
3792
3793 // Expand empty ranges by one codepoint
3794 if range.start == range.end {
3795 // This will be go to the next boundary when being clipped
3796 range.end.column += 1;
3797 range.end = snapshot.clip_point_utf16(Unclipped(range.end), Bias::Right);
3798 if range.start == range.end && range.end.column > 0 {
3799 range.start.column -= 1;
3800 range.end = snapshot.clip_point_utf16(Unclipped(range.end), Bias::Left);
3801 }
3802 }
3803
3804 sanitized_diagnostics.push(DiagnosticEntry {
3805 range,
3806 diagnostic: entry.diagnostic,
3807 });
3808 }
3809 drop(edits_since_save);
3810
3811 let set = DiagnosticSet::new(sanitized_diagnostics, &snapshot);
3812 buffer.update(cx, |buffer, cx| {
3813 buffer.update_diagnostics(server_id, set, cx)
3814 });
3815 Ok(())
3816 }
3817
3818 pub fn reload_buffers(
3819 &self,
3820 buffers: HashSet<ModelHandle<Buffer>>,
3821 push_to_history: bool,
3822 cx: &mut ModelContext<Self>,
3823 ) -> Task<Result<ProjectTransaction>> {
3824 let mut local_buffers = Vec::new();
3825 let mut remote_buffers = None;
3826 for buffer_handle in buffers {
3827 let buffer = buffer_handle.read(cx);
3828 if buffer.is_dirty() {
3829 if let Some(file) = File::from_dyn(buffer.file()) {
3830 if file.is_local() {
3831 local_buffers.push(buffer_handle);
3832 } else {
3833 remote_buffers.get_or_insert(Vec::new()).push(buffer_handle);
3834 }
3835 }
3836 }
3837 }
3838
3839 let remote_buffers = self.remote_id().zip(remote_buffers);
3840 let client = self.client.clone();
3841
3842 cx.spawn(|this, mut cx| async move {
3843 let mut project_transaction = ProjectTransaction::default();
3844
3845 if let Some((project_id, remote_buffers)) = remote_buffers {
3846 let response = client
3847 .request(proto::ReloadBuffers {
3848 project_id,
3849 buffer_ids: remote_buffers
3850 .iter()
3851 .map(|buffer| buffer.read_with(&cx, |buffer, _| buffer.remote_id()))
3852 .collect(),
3853 })
3854 .await?
3855 .transaction
3856 .ok_or_else(|| anyhow!("missing transaction"))?;
3857 project_transaction = this
3858 .update(&mut cx, |this, cx| {
3859 this.deserialize_project_transaction(response, push_to_history, cx)
3860 })
3861 .await?;
3862 }
3863
3864 for buffer in local_buffers {
3865 let transaction = buffer
3866 .update(&mut cx, |buffer, cx| buffer.reload(cx))
3867 .await?;
3868 buffer.update(&mut cx, |buffer, cx| {
3869 if let Some(transaction) = transaction {
3870 if !push_to_history {
3871 buffer.forget_transaction(transaction.id);
3872 }
3873 project_transaction.0.insert(cx.handle(), transaction);
3874 }
3875 });
3876 }
3877
3878 Ok(project_transaction)
3879 })
3880 }
3881
3882 pub fn format(
3883 &self,
3884 buffers: HashSet<ModelHandle<Buffer>>,
3885 push_to_history: bool,
3886 trigger: FormatTrigger,
3887 cx: &mut ModelContext<Project>,
3888 ) -> Task<Result<ProjectTransaction>> {
3889 if self.is_local() {
3890 let mut buffers_with_paths_and_servers = buffers
3891 .into_iter()
3892 .filter_map(|buffer_handle| {
3893 let buffer = buffer_handle.read(cx);
3894 let file = File::from_dyn(buffer.file())?;
3895 let buffer_abs_path = file.as_local().map(|f| f.abs_path(cx));
3896 let server = self
3897 .primary_language_server_for_buffer(buffer, cx)
3898 .map(|s| s.1.clone());
3899 Some((buffer_handle, buffer_abs_path, server))
3900 })
3901 .collect::<Vec<_>>();
3902
3903 cx.spawn(|this, mut cx| async move {
3904 // Do not allow multiple concurrent formatting requests for the
3905 // same buffer.
3906 this.update(&mut cx, |this, cx| {
3907 buffers_with_paths_and_servers.retain(|(buffer, _, _)| {
3908 this.buffers_being_formatted
3909 .insert(buffer.read(cx).remote_id())
3910 });
3911 });
3912
3913 let _cleanup = defer({
3914 let this = this.clone();
3915 let mut cx = cx.clone();
3916 let buffers = &buffers_with_paths_and_servers;
3917 move || {
3918 this.update(&mut cx, |this, cx| {
3919 for (buffer, _, _) in buffers {
3920 this.buffers_being_formatted
3921 .remove(&buffer.read(cx).remote_id());
3922 }
3923 });
3924 }
3925 });
3926
3927 let mut project_transaction = ProjectTransaction::default();
3928 for (buffer, buffer_abs_path, language_server) in &buffers_with_paths_and_servers {
3929 let settings = buffer.read_with(&cx, |buffer, cx| {
3930 language_settings(buffer.language(), buffer.file(), cx).clone()
3931 });
3932
3933 let remove_trailing_whitespace = settings.remove_trailing_whitespace_on_save;
3934 let ensure_final_newline = settings.ensure_final_newline_on_save;
3935 let format_on_save = settings.format_on_save.clone();
3936 let formatter = settings.formatter.clone();
3937 let tab_size = settings.tab_size;
3938
3939 // First, format buffer's whitespace according to the settings.
3940 let trailing_whitespace_diff = if remove_trailing_whitespace {
3941 Some(
3942 buffer
3943 .read_with(&cx, |b, cx| b.remove_trailing_whitespace(cx))
3944 .await,
3945 )
3946 } else {
3947 None
3948 };
3949 let whitespace_transaction_id = buffer.update(&mut cx, |buffer, cx| {
3950 buffer.finalize_last_transaction();
3951 buffer.start_transaction();
3952 if let Some(diff) = trailing_whitespace_diff {
3953 buffer.apply_diff(diff, cx);
3954 }
3955 if ensure_final_newline {
3956 buffer.ensure_final_newline(cx);
3957 }
3958 buffer.end_transaction(cx)
3959 });
3960
3961 // Currently, formatting operations are represented differently depending on
3962 // whether they come from a language server or an external command.
3963 enum FormatOperation {
3964 Lsp(Vec<(Range<Anchor>, String)>),
3965 External(Diff),
3966 }
3967
3968 // Apply language-specific formatting using either a language server
3969 // or external command.
3970 let mut format_operation = None;
3971 match (formatter, format_on_save) {
3972 (_, FormatOnSave::Off) if trigger == FormatTrigger::Save => {}
3973
3974 (Formatter::LanguageServer, FormatOnSave::On | FormatOnSave::Off)
3975 | (_, FormatOnSave::LanguageServer) => {
3976 if let Some((language_server, buffer_abs_path)) =
3977 language_server.as_ref().zip(buffer_abs_path.as_ref())
3978 {
3979 format_operation = Some(FormatOperation::Lsp(
3980 Self::format_via_lsp(
3981 &this,
3982 &buffer,
3983 buffer_abs_path,
3984 &language_server,
3985 tab_size,
3986 &mut cx,
3987 )
3988 .await
3989 .context("failed to format via language server")?,
3990 ));
3991 }
3992 }
3993
3994 (
3995 Formatter::External { command, arguments },
3996 FormatOnSave::On | FormatOnSave::Off,
3997 )
3998 | (_, FormatOnSave::External { command, arguments }) => {
3999 if let Some(buffer_abs_path) = buffer_abs_path {
4000 format_operation = Self::format_via_external_command(
4001 &buffer,
4002 &buffer_abs_path,
4003 &command,
4004 &arguments,
4005 &mut cx,
4006 )
4007 .await
4008 .context(format!(
4009 "failed to format via external command {:?}",
4010 command
4011 ))?
4012 .map(FormatOperation::External);
4013 }
4014 }
4015 };
4016
4017 buffer.update(&mut cx, |b, cx| {
4018 // If the buffer had its whitespace formatted and was edited while the language-specific
4019 // formatting was being computed, avoid applying the language-specific formatting, because
4020 // it can't be grouped with the whitespace formatting in the undo history.
4021 if let Some(transaction_id) = whitespace_transaction_id {
4022 if b.peek_undo_stack()
4023 .map_or(true, |e| e.transaction_id() != transaction_id)
4024 {
4025 format_operation.take();
4026 }
4027 }
4028
4029 // Apply any language-specific formatting, and group the two formatting operations
4030 // in the buffer's undo history.
4031 if let Some(operation) = format_operation {
4032 match operation {
4033 FormatOperation::Lsp(edits) => {
4034 b.edit(edits, None, cx);
4035 }
4036 FormatOperation::External(diff) => {
4037 b.apply_diff(diff, cx);
4038 }
4039 }
4040
4041 if let Some(transaction_id) = whitespace_transaction_id {
4042 b.group_until_transaction(transaction_id);
4043 }
4044 }
4045
4046 if let Some(transaction) = b.finalize_last_transaction().cloned() {
4047 if !push_to_history {
4048 b.forget_transaction(transaction.id);
4049 }
4050 project_transaction.0.insert(buffer.clone(), transaction);
4051 }
4052 });
4053 }
4054
4055 Ok(project_transaction)
4056 })
4057 } else {
4058 let remote_id = self.remote_id();
4059 let client = self.client.clone();
4060 cx.spawn(|this, mut cx| async move {
4061 let mut project_transaction = ProjectTransaction::default();
4062 if let Some(project_id) = remote_id {
4063 let response = client
4064 .request(proto::FormatBuffers {
4065 project_id,
4066 trigger: trigger as i32,
4067 buffer_ids: buffers
4068 .iter()
4069 .map(|buffer| buffer.read_with(&cx, |buffer, _| buffer.remote_id()))
4070 .collect(),
4071 })
4072 .await?
4073 .transaction
4074 .ok_or_else(|| anyhow!("missing transaction"))?;
4075 project_transaction = this
4076 .update(&mut cx, |this, cx| {
4077 this.deserialize_project_transaction(response, push_to_history, cx)
4078 })
4079 .await?;
4080 }
4081 Ok(project_transaction)
4082 })
4083 }
4084 }
4085
4086 async fn format_via_lsp(
4087 this: &ModelHandle<Self>,
4088 buffer: &ModelHandle<Buffer>,
4089 abs_path: &Path,
4090 language_server: &Arc<LanguageServer>,
4091 tab_size: NonZeroU32,
4092 cx: &mut AsyncAppContext,
4093 ) -> Result<Vec<(Range<Anchor>, String)>> {
4094 let uri = lsp::Url::from_file_path(abs_path)
4095 .map_err(|_| anyhow!("failed to convert abs path to uri"))?;
4096 let text_document = lsp::TextDocumentIdentifier::new(uri);
4097 let capabilities = &language_server.capabilities();
4098
4099 let formatting_provider = capabilities.document_formatting_provider.as_ref();
4100 let range_formatting_provider = capabilities.document_range_formatting_provider.as_ref();
4101
4102 let lsp_edits = if matches!(formatting_provider, Some(p) if *p != OneOf::Left(false)) {
4103 language_server
4104 .request::<lsp::request::Formatting>(lsp::DocumentFormattingParams {
4105 text_document,
4106 options: lsp_command::lsp_formatting_options(tab_size.get()),
4107 work_done_progress_params: Default::default(),
4108 })
4109 .await?
4110 } else if matches!(range_formatting_provider, Some(p) if *p != OneOf::Left(false)) {
4111 let buffer_start = lsp::Position::new(0, 0);
4112 let buffer_end = buffer.read_with(cx, |b, _| point_to_lsp(b.max_point_utf16()));
4113
4114 language_server
4115 .request::<lsp::request::RangeFormatting>(lsp::DocumentRangeFormattingParams {
4116 text_document,
4117 range: lsp::Range::new(buffer_start, buffer_end),
4118 options: lsp_command::lsp_formatting_options(tab_size.get()),
4119 work_done_progress_params: Default::default(),
4120 })
4121 .await?
4122 } else {
4123 None
4124 };
4125
4126 if let Some(lsp_edits) = lsp_edits {
4127 this.update(cx, |this, cx| {
4128 this.edits_from_lsp(buffer, lsp_edits, language_server.server_id(), None, cx)
4129 })
4130 .await
4131 } else {
4132 Ok(Vec::new())
4133 }
4134 }
4135
4136 async fn format_via_external_command(
4137 buffer: &ModelHandle<Buffer>,
4138 buffer_abs_path: &Path,
4139 command: &str,
4140 arguments: &[String],
4141 cx: &mut AsyncAppContext,
4142 ) -> Result<Option<Diff>> {
4143 let working_dir_path = buffer.read_with(cx, |buffer, cx| {
4144 let file = File::from_dyn(buffer.file())?;
4145 let worktree = file.worktree.read(cx).as_local()?;
4146 let mut worktree_path = worktree.abs_path().to_path_buf();
4147 if worktree.root_entry()?.is_file() {
4148 worktree_path.pop();
4149 }
4150 Some(worktree_path)
4151 });
4152
4153 if let Some(working_dir_path) = working_dir_path {
4154 let mut child =
4155 smol::process::Command::new(command)
4156 .args(arguments.iter().map(|arg| {
4157 arg.replace("{buffer_path}", &buffer_abs_path.to_string_lossy())
4158 }))
4159 .current_dir(&working_dir_path)
4160 .stdin(smol::process::Stdio::piped())
4161 .stdout(smol::process::Stdio::piped())
4162 .stderr(smol::process::Stdio::piped())
4163 .spawn()?;
4164 let stdin = child
4165 .stdin
4166 .as_mut()
4167 .ok_or_else(|| anyhow!("failed to acquire stdin"))?;
4168 let text = buffer.read_with(cx, |buffer, _| buffer.as_rope().clone());
4169 for chunk in text.chunks() {
4170 stdin.write_all(chunk.as_bytes()).await?;
4171 }
4172 stdin.flush().await?;
4173
4174 let output = child.output().await?;
4175 if !output.status.success() {
4176 return Err(anyhow!(
4177 "command failed with exit code {:?}:\nstdout: {}\nstderr: {}",
4178 output.status.code(),
4179 String::from_utf8_lossy(&output.stdout),
4180 String::from_utf8_lossy(&output.stderr),
4181 ));
4182 }
4183
4184 let stdout = String::from_utf8(output.stdout)?;
4185 Ok(Some(
4186 buffer
4187 .read_with(cx, |buffer, cx| buffer.diff(stdout, cx))
4188 .await,
4189 ))
4190 } else {
4191 Ok(None)
4192 }
4193 }
4194
4195 pub fn definition<T: ToPointUtf16>(
4196 &self,
4197 buffer: &ModelHandle<Buffer>,
4198 position: T,
4199 cx: &mut ModelContext<Self>,
4200 ) -> Task<Result<Vec<LocationLink>>> {
4201 let position = position.to_point_utf16(buffer.read(cx));
4202 self.request_lsp(
4203 buffer.clone(),
4204 LanguageServerToQuery::Primary,
4205 GetDefinition { position },
4206 cx,
4207 )
4208 }
4209
4210 pub fn type_definition<T: ToPointUtf16>(
4211 &self,
4212 buffer: &ModelHandle<Buffer>,
4213 position: T,
4214 cx: &mut ModelContext<Self>,
4215 ) -> Task<Result<Vec<LocationLink>>> {
4216 let position = position.to_point_utf16(buffer.read(cx));
4217 self.request_lsp(
4218 buffer.clone(),
4219 LanguageServerToQuery::Primary,
4220 GetTypeDefinition { position },
4221 cx,
4222 )
4223 }
4224
4225 pub fn references<T: ToPointUtf16>(
4226 &self,
4227 buffer: &ModelHandle<Buffer>,
4228 position: T,
4229 cx: &mut ModelContext<Self>,
4230 ) -> Task<Result<Vec<Location>>> {
4231 let position = position.to_point_utf16(buffer.read(cx));
4232 self.request_lsp(
4233 buffer.clone(),
4234 LanguageServerToQuery::Primary,
4235 GetReferences { position },
4236 cx,
4237 )
4238 }
4239
4240 pub fn document_highlights<T: ToPointUtf16>(
4241 &self,
4242 buffer: &ModelHandle<Buffer>,
4243 position: T,
4244 cx: &mut ModelContext<Self>,
4245 ) -> Task<Result<Vec<DocumentHighlight>>> {
4246 let position = position.to_point_utf16(buffer.read(cx));
4247 self.request_lsp(
4248 buffer.clone(),
4249 LanguageServerToQuery::Primary,
4250 GetDocumentHighlights { position },
4251 cx,
4252 )
4253 }
4254
4255 pub fn symbols(&self, query: &str, cx: &mut ModelContext<Self>) -> Task<Result<Vec<Symbol>>> {
4256 if self.is_local() {
4257 let mut requests = Vec::new();
4258 for ((worktree_id, _), server_id) in self.language_server_ids.iter() {
4259 let worktree_id = *worktree_id;
4260 let worktree_handle = self.worktree_for_id(worktree_id, cx);
4261 let worktree = match worktree_handle.and_then(|tree| tree.read(cx).as_local()) {
4262 Some(worktree) => worktree,
4263 None => continue,
4264 };
4265 let worktree_abs_path = worktree.abs_path().clone();
4266
4267 let (adapter, language, server) = match self.language_servers.get(server_id) {
4268 Some(LanguageServerState::Running {
4269 adapter,
4270 language,
4271 server,
4272 ..
4273 }) => (adapter.clone(), language.clone(), server),
4274
4275 _ => continue,
4276 };
4277
4278 requests.push(
4279 server
4280 .request::<lsp::request::WorkspaceSymbolRequest>(
4281 lsp::WorkspaceSymbolParams {
4282 query: query.to_string(),
4283 ..Default::default()
4284 },
4285 )
4286 .log_err()
4287 .map(move |response| {
4288 let lsp_symbols = response.flatten().map(|symbol_response| match symbol_response {
4289 lsp::WorkspaceSymbolResponse::Flat(flat_responses) => {
4290 flat_responses.into_iter().map(|lsp_symbol| {
4291 (lsp_symbol.name, lsp_symbol.kind, lsp_symbol.location)
4292 }).collect::<Vec<_>>()
4293 }
4294 lsp::WorkspaceSymbolResponse::Nested(nested_responses) => {
4295 nested_responses.into_iter().filter_map(|lsp_symbol| {
4296 let location = match lsp_symbol.location {
4297 OneOf::Left(location) => location,
4298 OneOf::Right(_) => {
4299 error!("Unexpected: client capabilities forbid symbol resolutions in workspace.symbol.resolveSupport");
4300 return None
4301 }
4302 };
4303 Some((lsp_symbol.name, lsp_symbol.kind, location))
4304 }).collect::<Vec<_>>()
4305 }
4306 }).unwrap_or_default();
4307
4308 (
4309 adapter,
4310 language,
4311 worktree_id,
4312 worktree_abs_path,
4313 lsp_symbols,
4314 )
4315 }),
4316 );
4317 }
4318
4319 cx.spawn_weak(|this, cx| async move {
4320 let responses = futures::future::join_all(requests).await;
4321 let this = match this.upgrade(&cx) {
4322 Some(this) => this,
4323 None => return Ok(Vec::new()),
4324 };
4325
4326 let symbols = this.read_with(&cx, |this, cx| {
4327 let mut symbols = Vec::new();
4328 for (
4329 adapter,
4330 adapter_language,
4331 source_worktree_id,
4332 worktree_abs_path,
4333 lsp_symbols,
4334 ) in responses
4335 {
4336 symbols.extend(lsp_symbols.into_iter().filter_map(
4337 |(symbol_name, symbol_kind, symbol_location)| {
4338 let abs_path = symbol_location.uri.to_file_path().ok()?;
4339 let mut worktree_id = source_worktree_id;
4340 let path;
4341 if let Some((worktree, rel_path)) =
4342 this.find_local_worktree(&abs_path, cx)
4343 {
4344 worktree_id = worktree.read(cx).id();
4345 path = rel_path;
4346 } else {
4347 path = relativize_path(&worktree_abs_path, &abs_path);
4348 }
4349
4350 let project_path = ProjectPath {
4351 worktree_id,
4352 path: path.into(),
4353 };
4354 let signature = this.symbol_signature(&project_path);
4355 let adapter_language = adapter_language.clone();
4356 let language = this
4357 .languages
4358 .language_for_file(&project_path.path, None)
4359 .unwrap_or_else(move |_| adapter_language);
4360 let language_server_name = adapter.name.clone();
4361 Some(async move {
4362 let language = language.await;
4363 let label =
4364 language.label_for_symbol(&symbol_name, symbol_kind).await;
4365
4366 Symbol {
4367 language_server_name,
4368 source_worktree_id,
4369 path: project_path,
4370 label: label.unwrap_or_else(|| {
4371 CodeLabel::plain(symbol_name.clone(), None)
4372 }),
4373 kind: symbol_kind,
4374 name: symbol_name,
4375 range: range_from_lsp(symbol_location.range),
4376 signature,
4377 }
4378 })
4379 },
4380 ));
4381 }
4382
4383 symbols
4384 });
4385
4386 Ok(futures::future::join_all(symbols).await)
4387 })
4388 } else if let Some(project_id) = self.remote_id() {
4389 let request = self.client.request(proto::GetProjectSymbols {
4390 project_id,
4391 query: query.to_string(),
4392 });
4393 cx.spawn_weak(|this, cx| async move {
4394 let response = request.await?;
4395 let mut symbols = Vec::new();
4396 if let Some(this) = this.upgrade(&cx) {
4397 let new_symbols = this.read_with(&cx, |this, _| {
4398 response
4399 .symbols
4400 .into_iter()
4401 .map(|symbol| this.deserialize_symbol(symbol))
4402 .collect::<Vec<_>>()
4403 });
4404 symbols = futures::future::join_all(new_symbols)
4405 .await
4406 .into_iter()
4407 .filter_map(|symbol| symbol.log_err())
4408 .collect::<Vec<_>>();
4409 }
4410 Ok(symbols)
4411 })
4412 } else {
4413 Task::ready(Ok(Default::default()))
4414 }
4415 }
4416
4417 pub fn open_buffer_for_symbol(
4418 &mut self,
4419 symbol: &Symbol,
4420 cx: &mut ModelContext<Self>,
4421 ) -> Task<Result<ModelHandle<Buffer>>> {
4422 if self.is_local() {
4423 let language_server_id = if let Some(id) = self.language_server_ids.get(&(
4424 symbol.source_worktree_id,
4425 symbol.language_server_name.clone(),
4426 )) {
4427 *id
4428 } else {
4429 return Task::ready(Err(anyhow!(
4430 "language server for worktree and language not found"
4431 )));
4432 };
4433
4434 let worktree_abs_path = if let Some(worktree_abs_path) = self
4435 .worktree_for_id(symbol.path.worktree_id, cx)
4436 .and_then(|worktree| worktree.read(cx).as_local())
4437 .map(|local_worktree| local_worktree.abs_path())
4438 {
4439 worktree_abs_path
4440 } else {
4441 return Task::ready(Err(anyhow!("worktree not found for symbol")));
4442 };
4443 let symbol_abs_path = worktree_abs_path.join(&symbol.path.path);
4444 let symbol_uri = if let Ok(uri) = lsp::Url::from_file_path(symbol_abs_path) {
4445 uri
4446 } else {
4447 return Task::ready(Err(anyhow!("invalid symbol path")));
4448 };
4449
4450 self.open_local_buffer_via_lsp(
4451 symbol_uri,
4452 language_server_id,
4453 symbol.language_server_name.clone(),
4454 cx,
4455 )
4456 } else if let Some(project_id) = self.remote_id() {
4457 let request = self.client.request(proto::OpenBufferForSymbol {
4458 project_id,
4459 symbol: Some(serialize_symbol(symbol)),
4460 });
4461 cx.spawn(|this, mut cx| async move {
4462 let response = request.await?;
4463 this.update(&mut cx, |this, cx| {
4464 this.wait_for_remote_buffer(response.buffer_id, cx)
4465 })
4466 .await
4467 })
4468 } else {
4469 Task::ready(Err(anyhow!("project does not have a remote id")))
4470 }
4471 }
4472
4473 pub fn hover<T: ToPointUtf16>(
4474 &self,
4475 buffer: &ModelHandle<Buffer>,
4476 position: T,
4477 cx: &mut ModelContext<Self>,
4478 ) -> Task<Result<Option<Hover>>> {
4479 let position = position.to_point_utf16(buffer.read(cx));
4480 self.request_lsp(
4481 buffer.clone(),
4482 LanguageServerToQuery::Primary,
4483 GetHover { position },
4484 cx,
4485 )
4486 }
4487
4488 pub fn completions<T: ToOffset + ToPointUtf16>(
4489 &self,
4490 buffer: &ModelHandle<Buffer>,
4491 position: T,
4492 cx: &mut ModelContext<Self>,
4493 ) -> Task<Result<Vec<Completion>>> {
4494 let position = position.to_point_utf16(buffer.read(cx));
4495 if self.is_local() {
4496 let snapshot = buffer.read(cx).snapshot();
4497 let offset = position.to_offset(&snapshot);
4498 let scope = snapshot.language_scope_at(offset);
4499
4500 let server_ids: Vec<_> = self
4501 .language_servers_for_buffer(buffer.read(cx), cx)
4502 .filter(|(_, server)| server.capabilities().completion_provider.is_some())
4503 .filter(|(adapter, _)| {
4504 scope
4505 .as_ref()
4506 .map(|scope| scope.language_allowed(&adapter.name))
4507 .unwrap_or(true)
4508 })
4509 .map(|(_, server)| server.server_id())
4510 .collect();
4511
4512 let buffer = buffer.clone();
4513 cx.spawn(|this, mut cx| async move {
4514 let mut tasks = Vec::with_capacity(server_ids.len());
4515 this.update(&mut cx, |this, cx| {
4516 for server_id in server_ids {
4517 tasks.push(this.request_lsp(
4518 buffer.clone(),
4519 LanguageServerToQuery::Other(server_id),
4520 GetCompletions { position },
4521 cx,
4522 ));
4523 }
4524 });
4525
4526 let mut completions = Vec::new();
4527 for task in tasks {
4528 if let Ok(new_completions) = task.await {
4529 completions.extend_from_slice(&new_completions);
4530 }
4531 }
4532
4533 Ok(completions)
4534 })
4535 } else if let Some(project_id) = self.remote_id() {
4536 self.send_lsp_proto_request(buffer.clone(), project_id, GetCompletions { position }, cx)
4537 } else {
4538 Task::ready(Ok(Default::default()))
4539 }
4540 }
4541
4542 pub fn apply_additional_edits_for_completion(
4543 &self,
4544 buffer_handle: ModelHandle<Buffer>,
4545 completion: Completion,
4546 push_to_history: bool,
4547 cx: &mut ModelContext<Self>,
4548 ) -> Task<Result<Option<Transaction>>> {
4549 let buffer = buffer_handle.read(cx);
4550 let buffer_id = buffer.remote_id();
4551
4552 if self.is_local() {
4553 let server_id = completion.server_id;
4554 let lang_server = match self.language_server_for_buffer(buffer, server_id, cx) {
4555 Some((_, server)) => server.clone(),
4556 _ => return Task::ready(Ok(Default::default())),
4557 };
4558
4559 cx.spawn(|this, mut cx| async move {
4560 let can_resolve = lang_server
4561 .capabilities()
4562 .completion_provider
4563 .as_ref()
4564 .and_then(|options| options.resolve_provider)
4565 .unwrap_or(false);
4566 let additional_text_edits = if can_resolve {
4567 lang_server
4568 .request::<lsp::request::ResolveCompletionItem>(completion.lsp_completion)
4569 .await?
4570 .additional_text_edits
4571 } else {
4572 completion.lsp_completion.additional_text_edits
4573 };
4574 if let Some(edits) = additional_text_edits {
4575 let edits = this
4576 .update(&mut cx, |this, cx| {
4577 this.edits_from_lsp(
4578 &buffer_handle,
4579 edits,
4580 lang_server.server_id(),
4581 None,
4582 cx,
4583 )
4584 })
4585 .await?;
4586
4587 buffer_handle.update(&mut cx, |buffer, cx| {
4588 buffer.finalize_last_transaction();
4589 buffer.start_transaction();
4590
4591 for (range, text) in edits {
4592 let primary = &completion.old_range;
4593 let start_within = primary.start.cmp(&range.start, buffer).is_le()
4594 && primary.end.cmp(&range.start, buffer).is_ge();
4595 let end_within = range.start.cmp(&primary.end, buffer).is_le()
4596 && range.end.cmp(&primary.end, buffer).is_ge();
4597
4598 //Skip additional edits which overlap with the primary completion edit
4599 //https://github.com/zed-industries/zed/pull/1871
4600 if !start_within && !end_within {
4601 buffer.edit([(range, text)], None, cx);
4602 }
4603 }
4604
4605 let transaction = if buffer.end_transaction(cx).is_some() {
4606 let transaction = buffer.finalize_last_transaction().unwrap().clone();
4607 if !push_to_history {
4608 buffer.forget_transaction(transaction.id);
4609 }
4610 Some(transaction)
4611 } else {
4612 None
4613 };
4614 Ok(transaction)
4615 })
4616 } else {
4617 Ok(None)
4618 }
4619 })
4620 } else if let Some(project_id) = self.remote_id() {
4621 let client = self.client.clone();
4622 cx.spawn(|_, mut cx| async move {
4623 let response = client
4624 .request(proto::ApplyCompletionAdditionalEdits {
4625 project_id,
4626 buffer_id,
4627 completion: Some(language::proto::serialize_completion(&completion)),
4628 })
4629 .await?;
4630
4631 if let Some(transaction) = response.transaction {
4632 let transaction = language::proto::deserialize_transaction(transaction)?;
4633 buffer_handle
4634 .update(&mut cx, |buffer, _| {
4635 buffer.wait_for_edits(transaction.edit_ids.iter().copied())
4636 })
4637 .await?;
4638 if push_to_history {
4639 buffer_handle.update(&mut cx, |buffer, _| {
4640 buffer.push_transaction(transaction.clone(), Instant::now());
4641 });
4642 }
4643 Ok(Some(transaction))
4644 } else {
4645 Ok(None)
4646 }
4647 })
4648 } else {
4649 Task::ready(Err(anyhow!("project does not have a remote id")))
4650 }
4651 }
4652
4653 pub fn code_actions<T: Clone + ToOffset>(
4654 &self,
4655 buffer_handle: &ModelHandle<Buffer>,
4656 range: Range<T>,
4657 cx: &mut ModelContext<Self>,
4658 ) -> Task<Result<Vec<CodeAction>>> {
4659 let buffer = buffer_handle.read(cx);
4660 let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
4661 self.request_lsp(
4662 buffer_handle.clone(),
4663 LanguageServerToQuery::Primary,
4664 GetCodeActions { range },
4665 cx,
4666 )
4667 }
4668
4669 pub fn apply_code_action(
4670 &self,
4671 buffer_handle: ModelHandle<Buffer>,
4672 mut action: CodeAction,
4673 push_to_history: bool,
4674 cx: &mut ModelContext<Self>,
4675 ) -> Task<Result<ProjectTransaction>> {
4676 if self.is_local() {
4677 let buffer = buffer_handle.read(cx);
4678 let (lsp_adapter, lang_server) = if let Some((adapter, server)) =
4679 self.language_server_for_buffer(buffer, action.server_id, cx)
4680 {
4681 (adapter.clone(), server.clone())
4682 } else {
4683 return Task::ready(Ok(Default::default()));
4684 };
4685 let range = action.range.to_point_utf16(buffer);
4686
4687 cx.spawn(|this, mut cx| async move {
4688 if let Some(lsp_range) = action
4689 .lsp_action
4690 .data
4691 .as_mut()
4692 .and_then(|d| d.get_mut("codeActionParams"))
4693 .and_then(|d| d.get_mut("range"))
4694 {
4695 *lsp_range = serde_json::to_value(&range_to_lsp(range)).unwrap();
4696 action.lsp_action = lang_server
4697 .request::<lsp::request::CodeActionResolveRequest>(action.lsp_action)
4698 .await?;
4699 } else {
4700 let actions = this
4701 .update(&mut cx, |this, cx| {
4702 this.code_actions(&buffer_handle, action.range, cx)
4703 })
4704 .await?;
4705 action.lsp_action = actions
4706 .into_iter()
4707 .find(|a| a.lsp_action.title == action.lsp_action.title)
4708 .ok_or_else(|| anyhow!("code action is outdated"))?
4709 .lsp_action;
4710 }
4711
4712 if let Some(edit) = action.lsp_action.edit {
4713 if edit.changes.is_some() || edit.document_changes.is_some() {
4714 return Self::deserialize_workspace_edit(
4715 this,
4716 edit,
4717 push_to_history,
4718 lsp_adapter.clone(),
4719 lang_server.clone(),
4720 &mut cx,
4721 )
4722 .await;
4723 }
4724 }
4725
4726 if let Some(command) = action.lsp_action.command {
4727 this.update(&mut cx, |this, _| {
4728 this.last_workspace_edits_by_language_server
4729 .remove(&lang_server.server_id());
4730 });
4731
4732 let result = lang_server
4733 .request::<lsp::request::ExecuteCommand>(lsp::ExecuteCommandParams {
4734 command: command.command,
4735 arguments: command.arguments.unwrap_or_default(),
4736 ..Default::default()
4737 })
4738 .await;
4739
4740 if let Err(err) = result {
4741 // TODO: LSP ERROR
4742 return Err(err);
4743 }
4744
4745 return Ok(this.update(&mut cx, |this, _| {
4746 this.last_workspace_edits_by_language_server
4747 .remove(&lang_server.server_id())
4748 .unwrap_or_default()
4749 }));
4750 }
4751
4752 Ok(ProjectTransaction::default())
4753 })
4754 } else if let Some(project_id) = self.remote_id() {
4755 let client = self.client.clone();
4756 let request = proto::ApplyCodeAction {
4757 project_id,
4758 buffer_id: buffer_handle.read(cx).remote_id(),
4759 action: Some(language::proto::serialize_code_action(&action)),
4760 };
4761 cx.spawn(|this, mut cx| async move {
4762 let response = client
4763 .request(request)
4764 .await?
4765 .transaction
4766 .ok_or_else(|| anyhow!("missing transaction"))?;
4767 this.update(&mut cx, |this, cx| {
4768 this.deserialize_project_transaction(response, push_to_history, cx)
4769 })
4770 .await
4771 })
4772 } else {
4773 Task::ready(Err(anyhow!("project does not have a remote id")))
4774 }
4775 }
4776
4777 fn apply_on_type_formatting(
4778 &self,
4779 buffer: ModelHandle<Buffer>,
4780 position: Anchor,
4781 trigger: String,
4782 cx: &mut ModelContext<Self>,
4783 ) -> Task<Result<Option<Transaction>>> {
4784 if self.is_local() {
4785 cx.spawn(|this, mut cx| async move {
4786 // Do not allow multiple concurrent formatting requests for the
4787 // same buffer.
4788 this.update(&mut cx, |this, cx| {
4789 this.buffers_being_formatted
4790 .insert(buffer.read(cx).remote_id())
4791 });
4792
4793 let _cleanup = defer({
4794 let this = this.clone();
4795 let mut cx = cx.clone();
4796 let closure_buffer = buffer.clone();
4797 move || {
4798 this.update(&mut cx, |this, cx| {
4799 this.buffers_being_formatted
4800 .remove(&closure_buffer.read(cx).remote_id());
4801 });
4802 }
4803 });
4804
4805 buffer
4806 .update(&mut cx, |buffer, _| {
4807 buffer.wait_for_edits(Some(position.timestamp))
4808 })
4809 .await?;
4810 this.update(&mut cx, |this, cx| {
4811 let position = position.to_point_utf16(buffer.read(cx));
4812 this.on_type_format(buffer, position, trigger, false, cx)
4813 })
4814 .await
4815 })
4816 } else if let Some(project_id) = self.remote_id() {
4817 let client = self.client.clone();
4818 let request = proto::OnTypeFormatting {
4819 project_id,
4820 buffer_id: buffer.read(cx).remote_id(),
4821 position: Some(serialize_anchor(&position)),
4822 trigger,
4823 version: serialize_version(&buffer.read(cx).version()),
4824 };
4825 cx.spawn(|_, _| async move {
4826 client
4827 .request(request)
4828 .await?
4829 .transaction
4830 .map(language::proto::deserialize_transaction)
4831 .transpose()
4832 })
4833 } else {
4834 Task::ready(Err(anyhow!("project does not have a remote id")))
4835 }
4836 }
4837
4838 async fn deserialize_edits(
4839 this: ModelHandle<Self>,
4840 buffer_to_edit: ModelHandle<Buffer>,
4841 edits: Vec<lsp::TextEdit>,
4842 push_to_history: bool,
4843 _: Arc<CachedLspAdapter>,
4844 language_server: Arc<LanguageServer>,
4845 cx: &mut AsyncAppContext,
4846 ) -> Result<Option<Transaction>> {
4847 let edits = this
4848 .update(cx, |this, cx| {
4849 this.edits_from_lsp(
4850 &buffer_to_edit,
4851 edits,
4852 language_server.server_id(),
4853 None,
4854 cx,
4855 )
4856 })
4857 .await?;
4858
4859 let transaction = buffer_to_edit.update(cx, |buffer, cx| {
4860 buffer.finalize_last_transaction();
4861 buffer.start_transaction();
4862 for (range, text) in edits {
4863 buffer.edit([(range, text)], None, cx);
4864 }
4865
4866 if buffer.end_transaction(cx).is_some() {
4867 let transaction = buffer.finalize_last_transaction().unwrap().clone();
4868 if !push_to_history {
4869 buffer.forget_transaction(transaction.id);
4870 }
4871 Some(transaction)
4872 } else {
4873 None
4874 }
4875 });
4876
4877 Ok(transaction)
4878 }
4879
4880 async fn deserialize_workspace_edit(
4881 this: ModelHandle<Self>,
4882 edit: lsp::WorkspaceEdit,
4883 push_to_history: bool,
4884 lsp_adapter: Arc<CachedLspAdapter>,
4885 language_server: Arc<LanguageServer>,
4886 cx: &mut AsyncAppContext,
4887 ) -> Result<ProjectTransaction> {
4888 let fs = this.read_with(cx, |this, _| this.fs.clone());
4889 let mut operations = Vec::new();
4890 if let Some(document_changes) = edit.document_changes {
4891 match document_changes {
4892 lsp::DocumentChanges::Edits(edits) => {
4893 operations.extend(edits.into_iter().map(lsp::DocumentChangeOperation::Edit))
4894 }
4895 lsp::DocumentChanges::Operations(ops) => operations = ops,
4896 }
4897 } else if let Some(changes) = edit.changes {
4898 operations.extend(changes.into_iter().map(|(uri, edits)| {
4899 lsp::DocumentChangeOperation::Edit(lsp::TextDocumentEdit {
4900 text_document: lsp::OptionalVersionedTextDocumentIdentifier {
4901 uri,
4902 version: None,
4903 },
4904 edits: edits.into_iter().map(OneOf::Left).collect(),
4905 })
4906 }));
4907 }
4908
4909 let mut project_transaction = ProjectTransaction::default();
4910 for operation in operations {
4911 match operation {
4912 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Create(op)) => {
4913 let abs_path = op
4914 .uri
4915 .to_file_path()
4916 .map_err(|_| anyhow!("can't convert URI to path"))?;
4917
4918 if let Some(parent_path) = abs_path.parent() {
4919 fs.create_dir(parent_path).await?;
4920 }
4921 if abs_path.ends_with("/") {
4922 fs.create_dir(&abs_path).await?;
4923 } else {
4924 fs.create_file(&abs_path, op.options.map(Into::into).unwrap_or_default())
4925 .await?;
4926 }
4927 }
4928
4929 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Rename(op)) => {
4930 let source_abs_path = op
4931 .old_uri
4932 .to_file_path()
4933 .map_err(|_| anyhow!("can't convert URI to path"))?;
4934 let target_abs_path = op
4935 .new_uri
4936 .to_file_path()
4937 .map_err(|_| anyhow!("can't convert URI to path"))?;
4938 fs.rename(
4939 &source_abs_path,
4940 &target_abs_path,
4941 op.options.map(Into::into).unwrap_or_default(),
4942 )
4943 .await?;
4944 }
4945
4946 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Delete(op)) => {
4947 let abs_path = op
4948 .uri
4949 .to_file_path()
4950 .map_err(|_| anyhow!("can't convert URI to path"))?;
4951 let options = op.options.map(Into::into).unwrap_or_default();
4952 if abs_path.ends_with("/") {
4953 fs.remove_dir(&abs_path, options).await?;
4954 } else {
4955 fs.remove_file(&abs_path, options).await?;
4956 }
4957 }
4958
4959 lsp::DocumentChangeOperation::Edit(op) => {
4960 let buffer_to_edit = this
4961 .update(cx, |this, cx| {
4962 this.open_local_buffer_via_lsp(
4963 op.text_document.uri,
4964 language_server.server_id(),
4965 lsp_adapter.name.clone(),
4966 cx,
4967 )
4968 })
4969 .await?;
4970
4971 let edits = this
4972 .update(cx, |this, cx| {
4973 let edits = op.edits.into_iter().map(|edit| match edit {
4974 OneOf::Left(edit) => edit,
4975 OneOf::Right(edit) => edit.text_edit,
4976 });
4977 this.edits_from_lsp(
4978 &buffer_to_edit,
4979 edits,
4980 language_server.server_id(),
4981 op.text_document.version,
4982 cx,
4983 )
4984 })
4985 .await?;
4986
4987 let transaction = buffer_to_edit.update(cx, |buffer, cx| {
4988 buffer.finalize_last_transaction();
4989 buffer.start_transaction();
4990 for (range, text) in edits {
4991 buffer.edit([(range, text)], None, cx);
4992 }
4993 let transaction = if buffer.end_transaction(cx).is_some() {
4994 let transaction = buffer.finalize_last_transaction().unwrap().clone();
4995 if !push_to_history {
4996 buffer.forget_transaction(transaction.id);
4997 }
4998 Some(transaction)
4999 } else {
5000 None
5001 };
5002
5003 transaction
5004 });
5005 if let Some(transaction) = transaction {
5006 project_transaction.0.insert(buffer_to_edit, transaction);
5007 }
5008 }
5009 }
5010 }
5011
5012 Ok(project_transaction)
5013 }
5014
5015 pub fn prepare_rename<T: ToPointUtf16>(
5016 &self,
5017 buffer: ModelHandle<Buffer>,
5018 position: T,
5019 cx: &mut ModelContext<Self>,
5020 ) -> Task<Result<Option<Range<Anchor>>>> {
5021 let position = position.to_point_utf16(buffer.read(cx));
5022 self.request_lsp(
5023 buffer,
5024 LanguageServerToQuery::Primary,
5025 PrepareRename { position },
5026 cx,
5027 )
5028 }
5029
5030 pub fn perform_rename<T: ToPointUtf16>(
5031 &self,
5032 buffer: ModelHandle<Buffer>,
5033 position: T,
5034 new_name: String,
5035 push_to_history: bool,
5036 cx: &mut ModelContext<Self>,
5037 ) -> Task<Result<ProjectTransaction>> {
5038 let position = position.to_point_utf16(buffer.read(cx));
5039 self.request_lsp(
5040 buffer,
5041 LanguageServerToQuery::Primary,
5042 PerformRename {
5043 position,
5044 new_name,
5045 push_to_history,
5046 },
5047 cx,
5048 )
5049 }
5050
5051 pub fn on_type_format<T: ToPointUtf16>(
5052 &self,
5053 buffer: ModelHandle<Buffer>,
5054 position: T,
5055 trigger: String,
5056 push_to_history: bool,
5057 cx: &mut ModelContext<Self>,
5058 ) -> Task<Result<Option<Transaction>>> {
5059 let (position, tab_size) = buffer.read_with(cx, |buffer, cx| {
5060 let position = position.to_point_utf16(buffer);
5061 (
5062 position,
5063 language_settings(buffer.language_at(position).as_ref(), buffer.file(), cx)
5064 .tab_size,
5065 )
5066 });
5067 self.request_lsp(
5068 buffer.clone(),
5069 LanguageServerToQuery::Primary,
5070 OnTypeFormatting {
5071 position,
5072 trigger,
5073 options: lsp_command::lsp_formatting_options(tab_size.get()).into(),
5074 push_to_history,
5075 },
5076 cx,
5077 )
5078 }
5079
5080 pub fn inlay_hints<T: ToOffset>(
5081 &self,
5082 buffer_handle: ModelHandle<Buffer>,
5083 range: Range<T>,
5084 cx: &mut ModelContext<Self>,
5085 ) -> Task<anyhow::Result<Vec<InlayHint>>> {
5086 let buffer = buffer_handle.read(cx);
5087 let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
5088 let range_start = range.start;
5089 let range_end = range.end;
5090 let buffer_id = buffer.remote_id();
5091 let buffer_version = buffer.version().clone();
5092 let lsp_request = InlayHints { range };
5093
5094 if self.is_local() {
5095 let lsp_request_task = self.request_lsp(
5096 buffer_handle.clone(),
5097 LanguageServerToQuery::Primary,
5098 lsp_request,
5099 cx,
5100 );
5101 cx.spawn(|_, mut cx| async move {
5102 buffer_handle
5103 .update(&mut cx, |buffer, _| {
5104 buffer.wait_for_edits(vec![range_start.timestamp, range_end.timestamp])
5105 })
5106 .await
5107 .context("waiting for inlay hint request range edits")?;
5108 lsp_request_task.await.context("inlay hints LSP request")
5109 })
5110 } else if let Some(project_id) = self.remote_id() {
5111 let client = self.client.clone();
5112 let request = proto::InlayHints {
5113 project_id,
5114 buffer_id,
5115 start: Some(serialize_anchor(&range_start)),
5116 end: Some(serialize_anchor(&range_end)),
5117 version: serialize_version(&buffer_version),
5118 };
5119 cx.spawn(|project, cx| async move {
5120 let response = client
5121 .request(request)
5122 .await
5123 .context("inlay hints proto request")?;
5124 let hints_request_result = LspCommand::response_from_proto(
5125 lsp_request,
5126 response,
5127 project,
5128 buffer_handle.clone(),
5129 cx,
5130 )
5131 .await;
5132
5133 hints_request_result.context("inlay hints proto response conversion")
5134 })
5135 } else {
5136 Task::ready(Err(anyhow!("project does not have a remote id")))
5137 }
5138 }
5139
5140 pub fn resolve_inlay_hint(
5141 &self,
5142 hint: InlayHint,
5143 buffer_handle: ModelHandle<Buffer>,
5144 server_id: LanguageServerId,
5145 cx: &mut ModelContext<Self>,
5146 ) -> Task<anyhow::Result<InlayHint>> {
5147 if self.is_local() {
5148 let buffer = buffer_handle.read(cx);
5149 let (_, lang_server) = if let Some((adapter, server)) =
5150 self.language_server_for_buffer(buffer, server_id, cx)
5151 {
5152 (adapter.clone(), server.clone())
5153 } else {
5154 return Task::ready(Ok(hint));
5155 };
5156 if !InlayHints::can_resolve_inlays(lang_server.capabilities()) {
5157 return Task::ready(Ok(hint));
5158 }
5159
5160 let buffer_snapshot = buffer.snapshot();
5161 cx.spawn(|_, mut cx| async move {
5162 let resolve_task = lang_server.request::<lsp::request::InlayHintResolveRequest>(
5163 InlayHints::project_to_lsp_hint(hint, &buffer_snapshot),
5164 );
5165 let resolved_hint = resolve_task
5166 .await
5167 .context("inlay hint resolve LSP request")?;
5168 let resolved_hint = InlayHints::lsp_to_project_hint(
5169 resolved_hint,
5170 &buffer_handle,
5171 server_id,
5172 ResolveState::Resolved,
5173 false,
5174 &mut cx,
5175 )
5176 .await?;
5177 Ok(resolved_hint)
5178 })
5179 } else if let Some(project_id) = self.remote_id() {
5180 let client = self.client.clone();
5181 let request = proto::ResolveInlayHint {
5182 project_id,
5183 buffer_id: buffer_handle.read(cx).remote_id(),
5184 language_server_id: server_id.0 as u64,
5185 hint: Some(InlayHints::project_to_proto_hint(hint.clone())),
5186 };
5187 cx.spawn(|_, _| async move {
5188 let response = client
5189 .request(request)
5190 .await
5191 .context("inlay hints proto request")?;
5192 match response.hint {
5193 Some(resolved_hint) => InlayHints::proto_to_project_hint(resolved_hint)
5194 .context("inlay hints proto resolve response conversion"),
5195 None => Ok(hint),
5196 }
5197 })
5198 } else {
5199 Task::ready(Err(anyhow!("project does not have a remote id")))
5200 }
5201 }
5202
5203 #[allow(clippy::type_complexity)]
5204 pub fn search(
5205 &self,
5206 query: SearchQuery,
5207 cx: &mut ModelContext<Self>,
5208 ) -> Receiver<(ModelHandle<Buffer>, Vec<Range<Anchor>>)> {
5209 if self.is_local() {
5210 self.search_local(query, cx)
5211 } else if let Some(project_id) = self.remote_id() {
5212 let (tx, rx) = smol::channel::unbounded();
5213 let request = self.client.request(query.to_proto(project_id));
5214 cx.spawn(|this, mut cx| async move {
5215 let response = request.await?;
5216 let mut result = HashMap::default();
5217 for location in response.locations {
5218 let target_buffer = this
5219 .update(&mut cx, |this, cx| {
5220 this.wait_for_remote_buffer(location.buffer_id, cx)
5221 })
5222 .await?;
5223 let start = location
5224 .start
5225 .and_then(deserialize_anchor)
5226 .ok_or_else(|| anyhow!("missing target start"))?;
5227 let end = location
5228 .end
5229 .and_then(deserialize_anchor)
5230 .ok_or_else(|| anyhow!("missing target end"))?;
5231 result
5232 .entry(target_buffer)
5233 .or_insert(Vec::new())
5234 .push(start..end)
5235 }
5236 for (buffer, ranges) in result {
5237 let _ = tx.send((buffer, ranges)).await;
5238 }
5239 Result::<(), anyhow::Error>::Ok(())
5240 })
5241 .detach_and_log_err(cx);
5242 rx
5243 } else {
5244 unimplemented!();
5245 }
5246 }
5247
5248 pub fn search_local(
5249 &self,
5250 query: SearchQuery,
5251 cx: &mut ModelContext<Self>,
5252 ) -> Receiver<(ModelHandle<Buffer>, Vec<Range<Anchor>>)> {
5253 // Local search is split into several phases.
5254 // TL;DR is that we do 2 passes; initial pass to pick files which contain at least one match
5255 // and the second phase that finds positions of all the matches found in the candidate files.
5256 // The Receiver obtained from this function returns matches sorted by buffer path. Files without a buffer path are reported first.
5257 //
5258 // It gets a bit hairy though, because we must account for files that do not have a persistent representation
5259 // on FS. Namely, if you have an untitled buffer or unsaved changes in a buffer, we want to scan that too.
5260 //
5261 // 1. We initialize a queue of match candidates and feed all opened buffers into it (== unsaved files / untitled buffers).
5262 // 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
5263 // of FS version for that file altogether - after all, what we have in memory is more up-to-date than what's in FS.
5264 // 2. At this point, we have a list of all potentially matching buffers/files.
5265 // We sort that list by buffer path - this list is retained for later use.
5266 // We ensure that all buffers are now opened and available in project.
5267 // 3. We run a scan over all the candidate buffers on multiple background threads.
5268 // We cannot assume that there will even be a match - while at least one match
5269 // is guaranteed for files obtained from FS, the buffers we got from memory (unsaved files/unnamed buffers) might not have a match at all.
5270 // There is also an auxilliary background thread responsible for result gathering.
5271 // 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),
5272 // it keeps it around. It reports matches in sorted order, though it accepts them in unsorted order as well.
5273 // 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
5274 // entry - which might already be available thanks to out-of-order processing.
5275 //
5276 // We could also report matches fully out-of-order, without maintaining a sorted list of matching paths.
5277 // 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.
5278 // 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
5279 // in face of constantly updating list of sorted matches.
5280 // Meanwhile, this implementation offers index stability, since the matches are already reported in a sorted order.
5281 let snapshots = self
5282 .visible_worktrees(cx)
5283 .filter_map(|tree| {
5284 let tree = tree.read(cx).as_local()?;
5285 Some(tree.snapshot())
5286 })
5287 .collect::<Vec<_>>();
5288
5289 let background = cx.background().clone();
5290 let path_count: usize = snapshots.iter().map(|s| s.visible_file_count()).sum();
5291 if path_count == 0 {
5292 let (_, rx) = smol::channel::bounded(1024);
5293 return rx;
5294 }
5295 let workers = background.num_cpus().min(path_count);
5296 let (matching_paths_tx, matching_paths_rx) = smol::channel::bounded(1024);
5297 let mut unnamed_files = vec![];
5298 let opened_buffers = self
5299 .opened_buffers
5300 .iter()
5301 .filter_map(|(_, b)| {
5302 let buffer = b.upgrade(cx)?;
5303 let snapshot = buffer.read_with(cx, |buffer, _| buffer.snapshot());
5304 if let Some(path) = snapshot.file().map(|file| file.path()) {
5305 Some((path.clone(), (buffer, snapshot)))
5306 } else {
5307 unnamed_files.push(buffer);
5308 None
5309 }
5310 })
5311 .collect();
5312 cx.background()
5313 .spawn(Self::background_search(
5314 unnamed_files,
5315 opened_buffers,
5316 cx.background().clone(),
5317 self.fs.clone(),
5318 workers,
5319 query.clone(),
5320 path_count,
5321 snapshots,
5322 matching_paths_tx,
5323 ))
5324 .detach();
5325
5326 let (buffers, buffers_rx) = Self::sort_candidates_and_open_buffers(matching_paths_rx, cx);
5327 let background = cx.background().clone();
5328 let (result_tx, result_rx) = smol::channel::bounded(1024);
5329 cx.background()
5330 .spawn(async move {
5331 let Ok(buffers) = buffers.await else {
5332 return;
5333 };
5334
5335 let buffers_len = buffers.len();
5336 if buffers_len == 0 {
5337 return;
5338 }
5339 let query = &query;
5340 let (finished_tx, mut finished_rx) = smol::channel::unbounded();
5341 background
5342 .scoped(|scope| {
5343 #[derive(Clone)]
5344 struct FinishedStatus {
5345 entry: Option<(ModelHandle<Buffer>, Vec<Range<Anchor>>)>,
5346 buffer_index: SearchMatchCandidateIndex,
5347 }
5348
5349 for _ in 0..workers {
5350 let finished_tx = finished_tx.clone();
5351 let mut buffers_rx = buffers_rx.clone();
5352 scope.spawn(async move {
5353 while let Some((entry, buffer_index)) = buffers_rx.next().await {
5354 let buffer_matches = if let Some((_, snapshot)) = entry.as_ref()
5355 {
5356 if query.file_matches(
5357 snapshot.file().map(|file| file.path().as_ref()),
5358 ) {
5359 query
5360 .search(&snapshot, None)
5361 .await
5362 .iter()
5363 .map(|range| {
5364 snapshot.anchor_before(range.start)
5365 ..snapshot.anchor_after(range.end)
5366 })
5367 .collect()
5368 } else {
5369 Vec::new()
5370 }
5371 } else {
5372 Vec::new()
5373 };
5374
5375 let status = if !buffer_matches.is_empty() {
5376 let entry = if let Some((buffer, _)) = entry.as_ref() {
5377 Some((buffer.clone(), buffer_matches))
5378 } else {
5379 None
5380 };
5381 FinishedStatus {
5382 entry,
5383 buffer_index,
5384 }
5385 } else {
5386 FinishedStatus {
5387 entry: None,
5388 buffer_index,
5389 }
5390 };
5391 if finished_tx.send(status).await.is_err() {
5392 break;
5393 }
5394 }
5395 });
5396 }
5397 // Report sorted matches
5398 scope.spawn(async move {
5399 let mut current_index = 0;
5400 let mut scratch = vec![None; buffers_len];
5401 while let Some(status) = finished_rx.next().await {
5402 debug_assert!(
5403 scratch[status.buffer_index].is_none(),
5404 "Got match status of position {} twice",
5405 status.buffer_index
5406 );
5407 let index = status.buffer_index;
5408 scratch[index] = Some(status);
5409 while current_index < buffers_len {
5410 let Some(current_entry) = scratch[current_index].take() else {
5411 // We intentionally **do not** increment `current_index` here. When next element arrives
5412 // from `finished_rx`, we will inspect the same position again, hoping for it to be Some(_)
5413 // this time.
5414 break;
5415 };
5416 if let Some(entry) = current_entry.entry {
5417 result_tx.send(entry).await.log_err();
5418 }
5419 current_index += 1;
5420 }
5421 if current_index == buffers_len {
5422 break;
5423 }
5424 }
5425 });
5426 })
5427 .await;
5428 })
5429 .detach();
5430 result_rx
5431 }
5432 /// Pick paths that might potentially contain a match of a given search query.
5433 async fn background_search(
5434 unnamed_buffers: Vec<ModelHandle<Buffer>>,
5435 opened_buffers: HashMap<Arc<Path>, (ModelHandle<Buffer>, BufferSnapshot)>,
5436 background: Arc<Background>,
5437 fs: Arc<dyn Fs>,
5438 workers: usize,
5439 query: SearchQuery,
5440 path_count: usize,
5441 snapshots: Vec<LocalSnapshot>,
5442 matching_paths_tx: Sender<SearchMatchCandidate>,
5443 ) {
5444 let fs = &fs;
5445 let query = &query;
5446 let matching_paths_tx = &matching_paths_tx;
5447 let snapshots = &snapshots;
5448 let paths_per_worker = (path_count + workers - 1) / workers;
5449 for buffer in unnamed_buffers {
5450 matching_paths_tx
5451 .send(SearchMatchCandidate::OpenBuffer {
5452 buffer: buffer.clone(),
5453 path: None,
5454 })
5455 .await
5456 .log_err();
5457 }
5458 for (path, (buffer, _)) in opened_buffers.iter() {
5459 matching_paths_tx
5460 .send(SearchMatchCandidate::OpenBuffer {
5461 buffer: buffer.clone(),
5462 path: Some(path.clone()),
5463 })
5464 .await
5465 .log_err();
5466 }
5467 background
5468 .scoped(|scope| {
5469 for worker_ix in 0..workers {
5470 let worker_start_ix = worker_ix * paths_per_worker;
5471 let worker_end_ix = worker_start_ix + paths_per_worker;
5472 let unnamed_buffers = opened_buffers.clone();
5473 scope.spawn(async move {
5474 let mut snapshot_start_ix = 0;
5475 let mut abs_path = PathBuf::new();
5476 for snapshot in snapshots {
5477 let snapshot_end_ix = snapshot_start_ix + snapshot.visible_file_count();
5478 if worker_end_ix <= snapshot_start_ix {
5479 break;
5480 } else if worker_start_ix > snapshot_end_ix {
5481 snapshot_start_ix = snapshot_end_ix;
5482 continue;
5483 } else {
5484 let start_in_snapshot =
5485 worker_start_ix.saturating_sub(snapshot_start_ix);
5486 let end_in_snapshot =
5487 cmp::min(worker_end_ix, snapshot_end_ix) - snapshot_start_ix;
5488
5489 for entry in snapshot
5490 .files(false, start_in_snapshot)
5491 .take(end_in_snapshot - start_in_snapshot)
5492 {
5493 if matching_paths_tx.is_closed() {
5494 break;
5495 }
5496 if unnamed_buffers.contains_key(&entry.path) {
5497 continue;
5498 }
5499 let matches = if query.file_matches(Some(&entry.path)) {
5500 abs_path.clear();
5501 abs_path.push(&snapshot.abs_path());
5502 abs_path.push(&entry.path);
5503 if let Some(file) = fs.open_sync(&abs_path).await.log_err()
5504 {
5505 query.detect(file).unwrap_or(false)
5506 } else {
5507 false
5508 }
5509 } else {
5510 false
5511 };
5512
5513 if matches {
5514 let project_path = SearchMatchCandidate::Path {
5515 worktree_id: snapshot.id(),
5516 path: entry.path.clone(),
5517 };
5518 if matching_paths_tx.send(project_path).await.is_err() {
5519 break;
5520 }
5521 }
5522 }
5523
5524 snapshot_start_ix = snapshot_end_ix;
5525 }
5526 }
5527 });
5528 }
5529 })
5530 .await;
5531 }
5532
5533 fn request_lsp<R: LspCommand>(
5534 &self,
5535 buffer_handle: ModelHandle<Buffer>,
5536 server: LanguageServerToQuery,
5537 request: R,
5538 cx: &mut ModelContext<Self>,
5539 ) -> Task<Result<R::Response>>
5540 where
5541 <R::LspRequest as lsp::request::Request>::Result: Send,
5542 {
5543 let buffer = buffer_handle.read(cx);
5544 if self.is_local() {
5545 let language_server = match server {
5546 LanguageServerToQuery::Primary => {
5547 match self.primary_language_server_for_buffer(buffer, cx) {
5548 Some((_, server)) => Some(Arc::clone(server)),
5549 None => return Task::ready(Ok(Default::default())),
5550 }
5551 }
5552 LanguageServerToQuery::Other(id) => self
5553 .language_server_for_buffer(buffer, id, cx)
5554 .map(|(_, server)| Arc::clone(server)),
5555 };
5556 let file = File::from_dyn(buffer.file()).and_then(File::as_local);
5557 if let (Some(file), Some(language_server)) = (file, language_server) {
5558 let lsp_params = request.to_lsp(&file.abs_path(cx), buffer, &language_server, cx);
5559 return cx.spawn(|this, cx| async move {
5560 if !request.check_capabilities(language_server.capabilities()) {
5561 return Ok(Default::default());
5562 }
5563
5564 let result = language_server.request::<R::LspRequest>(lsp_params).await;
5565 let response = match result {
5566 Ok(response) => response,
5567
5568 Err(err) => {
5569 log::warn!(
5570 "Generic lsp request to {} failed: {}",
5571 language_server.name(),
5572 err
5573 );
5574 return Err(err);
5575 }
5576 };
5577
5578 request
5579 .response_from_lsp(
5580 response,
5581 this,
5582 buffer_handle,
5583 language_server.server_id(),
5584 cx,
5585 )
5586 .await
5587 });
5588 }
5589 } else if let Some(project_id) = self.remote_id() {
5590 return self.send_lsp_proto_request(buffer_handle, project_id, request, cx);
5591 }
5592
5593 Task::ready(Ok(Default::default()))
5594 }
5595
5596 fn send_lsp_proto_request<R: LspCommand>(
5597 &self,
5598 buffer: ModelHandle<Buffer>,
5599 project_id: u64,
5600 request: R,
5601 cx: &mut ModelContext<'_, Project>,
5602 ) -> Task<anyhow::Result<<R as LspCommand>::Response>> {
5603 let rpc = self.client.clone();
5604 let message = request.to_proto(project_id, buffer.read(cx));
5605 cx.spawn_weak(|this, cx| async move {
5606 // Ensure the project is still alive by the time the task
5607 // is scheduled.
5608 this.upgrade(&cx)
5609 .ok_or_else(|| anyhow!("project dropped"))?;
5610 let response = rpc.request(message).await?;
5611 let this = this
5612 .upgrade(&cx)
5613 .ok_or_else(|| anyhow!("project dropped"))?;
5614 if this.read_with(&cx, |this, _| this.is_read_only()) {
5615 Err(anyhow!("disconnected before completing request"))
5616 } else {
5617 request
5618 .response_from_proto(response, this, buffer, cx)
5619 .await
5620 }
5621 })
5622 }
5623
5624 fn sort_candidates_and_open_buffers(
5625 mut matching_paths_rx: Receiver<SearchMatchCandidate>,
5626 cx: &mut ModelContext<Self>,
5627 ) -> (
5628 futures::channel::oneshot::Receiver<Vec<SearchMatchCandidate>>,
5629 Receiver<(
5630 Option<(ModelHandle<Buffer>, BufferSnapshot)>,
5631 SearchMatchCandidateIndex,
5632 )>,
5633 ) {
5634 let (buffers_tx, buffers_rx) = smol::channel::bounded(1024);
5635 let (sorted_buffers_tx, sorted_buffers_rx) = futures::channel::oneshot::channel();
5636 cx.spawn(|this, cx| async move {
5637 let mut buffers = vec![];
5638 while let Some(entry) = matching_paths_rx.next().await {
5639 buffers.push(entry);
5640 }
5641 buffers.sort_by_key(|candidate| candidate.path());
5642 let matching_paths = buffers.clone();
5643 let _ = sorted_buffers_tx.send(buffers);
5644 for (index, candidate) in matching_paths.into_iter().enumerate() {
5645 if buffers_tx.is_closed() {
5646 break;
5647 }
5648 let this = this.clone();
5649 let buffers_tx = buffers_tx.clone();
5650 cx.spawn(|mut cx| async move {
5651 let buffer = match candidate {
5652 SearchMatchCandidate::OpenBuffer { buffer, .. } => Some(buffer),
5653 SearchMatchCandidate::Path { worktree_id, path } => this
5654 .update(&mut cx, |this, cx| {
5655 this.open_buffer((worktree_id, path), cx)
5656 })
5657 .await
5658 .log_err(),
5659 };
5660 if let Some(buffer) = buffer {
5661 let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
5662 buffers_tx
5663 .send((Some((buffer, snapshot)), index))
5664 .await
5665 .log_err();
5666 } else {
5667 buffers_tx.send((None, index)).await.log_err();
5668 }
5669
5670 Ok::<_, anyhow::Error>(())
5671 })
5672 .detach();
5673 }
5674 })
5675 .detach();
5676 (sorted_buffers_rx, buffers_rx)
5677 }
5678
5679 pub fn find_or_create_local_worktree(
5680 &mut self,
5681 abs_path: impl AsRef<Path>,
5682 visible: bool,
5683 cx: &mut ModelContext<Self>,
5684 ) -> Task<Result<(ModelHandle<Worktree>, PathBuf)>> {
5685 let abs_path = abs_path.as_ref();
5686 if let Some((tree, relative_path)) = self.find_local_worktree(abs_path, cx) {
5687 Task::ready(Ok((tree, relative_path)))
5688 } else {
5689 let worktree = self.create_local_worktree(abs_path, visible, cx);
5690 cx.foreground()
5691 .spawn(async move { Ok((worktree.await?, PathBuf::new())) })
5692 }
5693 }
5694
5695 pub fn find_local_worktree(
5696 &self,
5697 abs_path: &Path,
5698 cx: &AppContext,
5699 ) -> Option<(ModelHandle<Worktree>, PathBuf)> {
5700 for tree in &self.worktrees {
5701 if let Some(tree) = tree.upgrade(cx) {
5702 if let Some(relative_path) = tree
5703 .read(cx)
5704 .as_local()
5705 .and_then(|t| abs_path.strip_prefix(t.abs_path()).ok())
5706 {
5707 return Some((tree.clone(), relative_path.into()));
5708 }
5709 }
5710 }
5711 None
5712 }
5713
5714 pub fn is_shared(&self) -> bool {
5715 match &self.client_state {
5716 Some(ProjectClientState::Local { .. }) => true,
5717 _ => false,
5718 }
5719 }
5720
5721 fn create_local_worktree(
5722 &mut self,
5723 abs_path: impl AsRef<Path>,
5724 visible: bool,
5725 cx: &mut ModelContext<Self>,
5726 ) -> Task<Result<ModelHandle<Worktree>>> {
5727 let fs = self.fs.clone();
5728 let client = self.client.clone();
5729 let next_entry_id = self.next_entry_id.clone();
5730 let path: Arc<Path> = abs_path.as_ref().into();
5731 let task = self
5732 .loading_local_worktrees
5733 .entry(path.clone())
5734 .or_insert_with(|| {
5735 cx.spawn(|project, mut cx| {
5736 async move {
5737 let worktree = Worktree::local(
5738 client.clone(),
5739 path.clone(),
5740 visible,
5741 fs,
5742 next_entry_id,
5743 &mut cx,
5744 )
5745 .await;
5746
5747 project.update(&mut cx, |project, _| {
5748 project.loading_local_worktrees.remove(&path);
5749 });
5750
5751 let worktree = worktree?;
5752 project.update(&mut cx, |project, cx| project.add_worktree(&worktree, cx));
5753 Ok(worktree)
5754 }
5755 .map_err(Arc::new)
5756 })
5757 .shared()
5758 })
5759 .clone();
5760 cx.foreground().spawn(async move {
5761 match task.await {
5762 Ok(worktree) => Ok(worktree),
5763 Err(err) => Err(anyhow!("{}", err)),
5764 }
5765 })
5766 }
5767
5768 pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut ModelContext<Self>) {
5769 self.worktrees.retain(|worktree| {
5770 if let Some(worktree) = worktree.upgrade(cx) {
5771 let id = worktree.read(cx).id();
5772 if id == id_to_remove {
5773 cx.emit(Event::WorktreeRemoved(id));
5774 false
5775 } else {
5776 true
5777 }
5778 } else {
5779 false
5780 }
5781 });
5782 self.metadata_changed(cx);
5783 }
5784
5785 fn add_worktree(&mut self, worktree: &ModelHandle<Worktree>, cx: &mut ModelContext<Self>) {
5786 cx.observe(worktree, |_, _, cx| cx.notify()).detach();
5787 if worktree.read(cx).is_local() {
5788 cx.subscribe(worktree, |this, worktree, event, cx| match event {
5789 worktree::Event::UpdatedEntries(changes) => {
5790 this.update_local_worktree_buffers(&worktree, changes, cx);
5791 this.update_local_worktree_language_servers(&worktree, changes, cx);
5792 this.update_local_worktree_settings(&worktree, changes, cx);
5793 cx.emit(Event::WorktreeUpdatedEntries(
5794 worktree.read(cx).id(),
5795 changes.clone(),
5796 ));
5797 }
5798 worktree::Event::UpdatedGitRepositories(updated_repos) => {
5799 this.update_local_worktree_buffers_git_repos(worktree, updated_repos, cx)
5800 }
5801 })
5802 .detach();
5803 }
5804
5805 let push_strong_handle = {
5806 let worktree = worktree.read(cx);
5807 self.is_shared() || worktree.is_visible() || worktree.is_remote()
5808 };
5809 if push_strong_handle {
5810 self.worktrees
5811 .push(WorktreeHandle::Strong(worktree.clone()));
5812 } else {
5813 self.worktrees
5814 .push(WorktreeHandle::Weak(worktree.downgrade()));
5815 }
5816
5817 let handle_id = worktree.id();
5818 cx.observe_release(worktree, move |this, worktree, cx| {
5819 let _ = this.remove_worktree(worktree.id(), cx);
5820 cx.update_global::<SettingsStore, _, _>(|store, cx| {
5821 store.clear_local_settings(handle_id, cx).log_err()
5822 });
5823 })
5824 .detach();
5825
5826 cx.emit(Event::WorktreeAdded);
5827 self.metadata_changed(cx);
5828 }
5829
5830 fn update_local_worktree_buffers(
5831 &mut self,
5832 worktree_handle: &ModelHandle<Worktree>,
5833 changes: &[(Arc<Path>, ProjectEntryId, PathChange)],
5834 cx: &mut ModelContext<Self>,
5835 ) {
5836 let snapshot = worktree_handle.read(cx).snapshot();
5837
5838 let mut renamed_buffers = Vec::new();
5839 for (path, entry_id, _) in changes {
5840 let worktree_id = worktree_handle.read(cx).id();
5841 let project_path = ProjectPath {
5842 worktree_id,
5843 path: path.clone(),
5844 };
5845
5846 let buffer_id = match self.local_buffer_ids_by_entry_id.get(entry_id) {
5847 Some(&buffer_id) => buffer_id,
5848 None => match self.local_buffer_ids_by_path.get(&project_path) {
5849 Some(&buffer_id) => buffer_id,
5850 None => continue,
5851 },
5852 };
5853
5854 let open_buffer = self.opened_buffers.get(&buffer_id);
5855 let buffer = if let Some(buffer) = open_buffer.and_then(|buffer| buffer.upgrade(cx)) {
5856 buffer
5857 } else {
5858 self.opened_buffers.remove(&buffer_id);
5859 self.local_buffer_ids_by_path.remove(&project_path);
5860 self.local_buffer_ids_by_entry_id.remove(entry_id);
5861 continue;
5862 };
5863
5864 buffer.update(cx, |buffer, cx| {
5865 if let Some(old_file) = File::from_dyn(buffer.file()) {
5866 if old_file.worktree != *worktree_handle {
5867 return;
5868 }
5869
5870 let new_file = if let Some(entry) = snapshot.entry_for_id(old_file.entry_id) {
5871 File {
5872 is_local: true,
5873 entry_id: entry.id,
5874 mtime: entry.mtime,
5875 path: entry.path.clone(),
5876 worktree: worktree_handle.clone(),
5877 is_deleted: false,
5878 }
5879 } else if let Some(entry) = snapshot.entry_for_path(old_file.path().as_ref()) {
5880 File {
5881 is_local: true,
5882 entry_id: entry.id,
5883 mtime: entry.mtime,
5884 path: entry.path.clone(),
5885 worktree: worktree_handle.clone(),
5886 is_deleted: false,
5887 }
5888 } else {
5889 File {
5890 is_local: true,
5891 entry_id: old_file.entry_id,
5892 path: old_file.path().clone(),
5893 mtime: old_file.mtime(),
5894 worktree: worktree_handle.clone(),
5895 is_deleted: true,
5896 }
5897 };
5898
5899 let old_path = old_file.abs_path(cx);
5900 if new_file.abs_path(cx) != old_path {
5901 renamed_buffers.push((cx.handle(), old_file.clone()));
5902 self.local_buffer_ids_by_path.remove(&project_path);
5903 self.local_buffer_ids_by_path.insert(
5904 ProjectPath {
5905 worktree_id,
5906 path: path.clone(),
5907 },
5908 buffer_id,
5909 );
5910 }
5911
5912 if new_file.entry_id != *entry_id {
5913 self.local_buffer_ids_by_entry_id.remove(entry_id);
5914 self.local_buffer_ids_by_entry_id
5915 .insert(new_file.entry_id, buffer_id);
5916 }
5917
5918 if new_file != *old_file {
5919 if let Some(project_id) = self.remote_id() {
5920 self.client
5921 .send(proto::UpdateBufferFile {
5922 project_id,
5923 buffer_id: buffer_id as u64,
5924 file: Some(new_file.to_proto()),
5925 })
5926 .log_err();
5927 }
5928
5929 buffer.file_updated(Arc::new(new_file), cx).detach();
5930 }
5931 }
5932 });
5933 }
5934
5935 for (buffer, old_file) in renamed_buffers {
5936 self.unregister_buffer_from_language_servers(&buffer, &old_file, cx);
5937 self.detect_language_for_buffer(&buffer, cx);
5938 self.register_buffer_with_language_servers(&buffer, cx);
5939 }
5940 }
5941
5942 fn update_local_worktree_language_servers(
5943 &mut self,
5944 worktree_handle: &ModelHandle<Worktree>,
5945 changes: &[(Arc<Path>, ProjectEntryId, PathChange)],
5946 cx: &mut ModelContext<Self>,
5947 ) {
5948 if changes.is_empty() {
5949 return;
5950 }
5951
5952 let worktree_id = worktree_handle.read(cx).id();
5953 let mut language_server_ids = self
5954 .language_server_ids
5955 .iter()
5956 .filter_map(|((server_worktree_id, _), server_id)| {
5957 (*server_worktree_id == worktree_id).then_some(*server_id)
5958 })
5959 .collect::<Vec<_>>();
5960 language_server_ids.sort();
5961 language_server_ids.dedup();
5962
5963 let abs_path = worktree_handle.read(cx).abs_path();
5964 for server_id in &language_server_ids {
5965 if let Some(LanguageServerState::Running {
5966 server,
5967 watched_paths,
5968 ..
5969 }) = self.language_servers.get(server_id)
5970 {
5971 if let Some(watched_paths) = watched_paths.get(&worktree_id) {
5972 let params = lsp::DidChangeWatchedFilesParams {
5973 changes: changes
5974 .iter()
5975 .filter_map(|(path, _, change)| {
5976 if !watched_paths.is_match(&path) {
5977 return None;
5978 }
5979 let typ = match change {
5980 PathChange::Loaded => return None,
5981 PathChange::Added => lsp::FileChangeType::CREATED,
5982 PathChange::Removed => lsp::FileChangeType::DELETED,
5983 PathChange::Updated => lsp::FileChangeType::CHANGED,
5984 PathChange::AddedOrUpdated => lsp::FileChangeType::CHANGED,
5985 };
5986 Some(lsp::FileEvent {
5987 uri: lsp::Url::from_file_path(abs_path.join(path)).unwrap(),
5988 typ,
5989 })
5990 })
5991 .collect(),
5992 };
5993
5994 if !params.changes.is_empty() {
5995 server
5996 .notify::<lsp::notification::DidChangeWatchedFiles>(params)
5997 .log_err();
5998 }
5999 }
6000 }
6001 }
6002 }
6003
6004 fn update_local_worktree_buffers_git_repos(
6005 &mut self,
6006 worktree_handle: ModelHandle<Worktree>,
6007 changed_repos: &UpdatedGitRepositoriesSet,
6008 cx: &mut ModelContext<Self>,
6009 ) {
6010 debug_assert!(worktree_handle.read(cx).is_local());
6011
6012 // Identify the loading buffers whose containing repository that has changed.
6013 let future_buffers = self
6014 .loading_buffers_by_path
6015 .iter()
6016 .filter_map(|(project_path, receiver)| {
6017 if project_path.worktree_id != worktree_handle.read(cx).id() {
6018 return None;
6019 }
6020 let path = &project_path.path;
6021 changed_repos
6022 .iter()
6023 .find(|(work_dir, _)| path.starts_with(work_dir))?;
6024 let receiver = receiver.clone();
6025 let path = path.clone();
6026 Some(async move {
6027 wait_for_loading_buffer(receiver)
6028 .await
6029 .ok()
6030 .map(|buffer| (buffer, path))
6031 })
6032 })
6033 .collect::<FuturesUnordered<_>>();
6034
6035 // Identify the current buffers whose containing repository has changed.
6036 let current_buffers = self
6037 .opened_buffers
6038 .values()
6039 .filter_map(|buffer| {
6040 let buffer = buffer.upgrade(cx)?;
6041 let file = File::from_dyn(buffer.read(cx).file())?;
6042 if file.worktree != worktree_handle {
6043 return None;
6044 }
6045 let path = file.path();
6046 changed_repos
6047 .iter()
6048 .find(|(work_dir, _)| path.starts_with(work_dir))?;
6049 Some((buffer, path.clone()))
6050 })
6051 .collect::<Vec<_>>();
6052
6053 if future_buffers.len() + current_buffers.len() == 0 {
6054 return;
6055 }
6056
6057 let remote_id = self.remote_id();
6058 let client = self.client.clone();
6059 cx.spawn_weak(move |_, mut cx| async move {
6060 // Wait for all of the buffers to load.
6061 let future_buffers = future_buffers.collect::<Vec<_>>().await;
6062
6063 // Reload the diff base for every buffer whose containing git repository has changed.
6064 let snapshot =
6065 worktree_handle.read_with(&cx, |tree, _| tree.as_local().unwrap().snapshot());
6066 let diff_bases_by_buffer = cx
6067 .background()
6068 .spawn(async move {
6069 future_buffers
6070 .into_iter()
6071 .filter_map(|e| e)
6072 .chain(current_buffers)
6073 .filter_map(|(buffer, path)| {
6074 let (work_directory, repo) =
6075 snapshot.repository_and_work_directory_for_path(&path)?;
6076 let repo = snapshot.get_local_repo(&repo)?;
6077 let relative_path = path.strip_prefix(&work_directory).ok()?;
6078 let base_text = repo.repo_ptr.lock().load_index_text(&relative_path);
6079 Some((buffer, base_text))
6080 })
6081 .collect::<Vec<_>>()
6082 })
6083 .await;
6084
6085 // Assign the new diff bases on all of the buffers.
6086 for (buffer, diff_base) in diff_bases_by_buffer {
6087 let buffer_id = buffer.update(&mut cx, |buffer, cx| {
6088 buffer.set_diff_base(diff_base.clone(), cx);
6089 buffer.remote_id()
6090 });
6091 if let Some(project_id) = remote_id {
6092 client
6093 .send(proto::UpdateDiffBase {
6094 project_id,
6095 buffer_id,
6096 diff_base,
6097 })
6098 .log_err();
6099 }
6100 }
6101 })
6102 .detach();
6103 }
6104
6105 fn update_local_worktree_settings(
6106 &mut self,
6107 worktree: &ModelHandle<Worktree>,
6108 changes: &UpdatedEntriesSet,
6109 cx: &mut ModelContext<Self>,
6110 ) {
6111 let project_id = self.remote_id();
6112 let worktree_id = worktree.id();
6113 let worktree = worktree.read(cx).as_local().unwrap();
6114 let remote_worktree_id = worktree.id();
6115
6116 let mut settings_contents = Vec::new();
6117 for (path, _, change) in changes.iter() {
6118 if path.ends_with(&*LOCAL_SETTINGS_RELATIVE_PATH) {
6119 let settings_dir = Arc::from(
6120 path.ancestors()
6121 .nth(LOCAL_SETTINGS_RELATIVE_PATH.components().count())
6122 .unwrap(),
6123 );
6124 let fs = self.fs.clone();
6125 let removed = *change == PathChange::Removed;
6126 let abs_path = worktree.absolutize(path);
6127 settings_contents.push(async move {
6128 (settings_dir, (!removed).then_some(fs.load(&abs_path).await))
6129 });
6130 }
6131 }
6132
6133 if settings_contents.is_empty() {
6134 return;
6135 }
6136
6137 let client = self.client.clone();
6138 cx.spawn_weak(move |_, mut cx| async move {
6139 let settings_contents: Vec<(Arc<Path>, _)> =
6140 futures::future::join_all(settings_contents).await;
6141 cx.update(|cx| {
6142 cx.update_global::<SettingsStore, _, _>(|store, cx| {
6143 for (directory, file_content) in settings_contents {
6144 let file_content = file_content.and_then(|content| content.log_err());
6145 store
6146 .set_local_settings(
6147 worktree_id,
6148 directory.clone(),
6149 file_content.as_ref().map(String::as_str),
6150 cx,
6151 )
6152 .log_err();
6153 if let Some(remote_id) = project_id {
6154 client
6155 .send(proto::UpdateWorktreeSettings {
6156 project_id: remote_id,
6157 worktree_id: remote_worktree_id.to_proto(),
6158 path: directory.to_string_lossy().into_owned(),
6159 content: file_content,
6160 })
6161 .log_err();
6162 }
6163 }
6164 });
6165 });
6166 })
6167 .detach();
6168 }
6169
6170 pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
6171 let new_active_entry = entry.and_then(|project_path| {
6172 let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
6173 let entry = worktree.read(cx).entry_for_path(project_path.path)?;
6174 Some(entry.id)
6175 });
6176 if new_active_entry != self.active_entry {
6177 self.active_entry = new_active_entry;
6178 cx.emit(Event::ActiveEntryChanged(new_active_entry));
6179 }
6180 }
6181
6182 pub fn language_servers_running_disk_based_diagnostics(
6183 &self,
6184 ) -> impl Iterator<Item = LanguageServerId> + '_ {
6185 self.language_server_statuses
6186 .iter()
6187 .filter_map(|(id, status)| {
6188 if status.has_pending_diagnostic_updates {
6189 Some(*id)
6190 } else {
6191 None
6192 }
6193 })
6194 }
6195
6196 pub fn diagnostic_summary(&self, cx: &AppContext) -> DiagnosticSummary {
6197 let mut summary = DiagnosticSummary::default();
6198 for (_, _, path_summary) in self.diagnostic_summaries(cx) {
6199 summary.error_count += path_summary.error_count;
6200 summary.warning_count += path_summary.warning_count;
6201 }
6202 summary
6203 }
6204
6205 pub fn diagnostic_summaries<'a>(
6206 &'a self,
6207 cx: &'a AppContext,
6208 ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
6209 self.visible_worktrees(cx).flat_map(move |worktree| {
6210 let worktree = worktree.read(cx);
6211 let worktree_id = worktree.id();
6212 worktree
6213 .diagnostic_summaries()
6214 .map(move |(path, server_id, summary)| {
6215 (ProjectPath { worktree_id, path }, server_id, summary)
6216 })
6217 })
6218 }
6219
6220 pub fn disk_based_diagnostics_started(
6221 &mut self,
6222 language_server_id: LanguageServerId,
6223 cx: &mut ModelContext<Self>,
6224 ) {
6225 cx.emit(Event::DiskBasedDiagnosticsStarted { language_server_id });
6226 }
6227
6228 pub fn disk_based_diagnostics_finished(
6229 &mut self,
6230 language_server_id: LanguageServerId,
6231 cx: &mut ModelContext<Self>,
6232 ) {
6233 cx.emit(Event::DiskBasedDiagnosticsFinished { language_server_id });
6234 }
6235
6236 pub fn active_entry(&self) -> Option<ProjectEntryId> {
6237 self.active_entry
6238 }
6239
6240 pub fn entry_for_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<Entry> {
6241 self.worktree_for_id(path.worktree_id, cx)?
6242 .read(cx)
6243 .entry_for_path(&path.path)
6244 .cloned()
6245 }
6246
6247 pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &AppContext) -> Option<ProjectPath> {
6248 let worktree = self.worktree_for_entry(entry_id, cx)?;
6249 let worktree = worktree.read(cx);
6250 let worktree_id = worktree.id();
6251 let path = worktree.entry_for_id(entry_id)?.path.clone();
6252 Some(ProjectPath { worktree_id, path })
6253 }
6254
6255 pub fn absolute_path(&self, project_path: &ProjectPath, cx: &AppContext) -> Option<PathBuf> {
6256 let workspace_root = self
6257 .worktree_for_id(project_path.worktree_id, cx)?
6258 .read(cx)
6259 .abs_path();
6260 let project_path = project_path.path.as_ref();
6261
6262 Some(if project_path == Path::new("") {
6263 workspace_root.to_path_buf()
6264 } else {
6265 workspace_root.join(project_path)
6266 })
6267 }
6268
6269 // RPC message handlers
6270
6271 async fn handle_unshare_project(
6272 this: ModelHandle<Self>,
6273 _: TypedEnvelope<proto::UnshareProject>,
6274 _: Arc<Client>,
6275 mut cx: AsyncAppContext,
6276 ) -> Result<()> {
6277 this.update(&mut cx, |this, cx| {
6278 if this.is_local() {
6279 this.unshare(cx)?;
6280 } else {
6281 this.disconnected_from_host(cx);
6282 }
6283 Ok(())
6284 })
6285 }
6286
6287 async fn handle_add_collaborator(
6288 this: ModelHandle<Self>,
6289 mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
6290 _: Arc<Client>,
6291 mut cx: AsyncAppContext,
6292 ) -> Result<()> {
6293 let collaborator = envelope
6294 .payload
6295 .collaborator
6296 .take()
6297 .ok_or_else(|| anyhow!("empty collaborator"))?;
6298
6299 let collaborator = Collaborator::from_proto(collaborator)?;
6300 this.update(&mut cx, |this, cx| {
6301 this.shared_buffers.remove(&collaborator.peer_id);
6302 cx.emit(Event::CollaboratorJoined(collaborator.peer_id));
6303 this.collaborators
6304 .insert(collaborator.peer_id, collaborator);
6305 cx.notify();
6306 });
6307
6308 Ok(())
6309 }
6310
6311 async fn handle_update_project_collaborator(
6312 this: ModelHandle<Self>,
6313 envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
6314 _: Arc<Client>,
6315 mut cx: AsyncAppContext,
6316 ) -> Result<()> {
6317 let old_peer_id = envelope
6318 .payload
6319 .old_peer_id
6320 .ok_or_else(|| anyhow!("missing old peer id"))?;
6321 let new_peer_id = envelope
6322 .payload
6323 .new_peer_id
6324 .ok_or_else(|| anyhow!("missing new peer id"))?;
6325 this.update(&mut cx, |this, cx| {
6326 let collaborator = this
6327 .collaborators
6328 .remove(&old_peer_id)
6329 .ok_or_else(|| anyhow!("received UpdateProjectCollaborator for unknown peer"))?;
6330 let is_host = collaborator.replica_id == 0;
6331 this.collaborators.insert(new_peer_id, collaborator);
6332
6333 let buffers = this.shared_buffers.remove(&old_peer_id);
6334 log::info!(
6335 "peer {} became {}. moving buffers {:?}",
6336 old_peer_id,
6337 new_peer_id,
6338 &buffers
6339 );
6340 if let Some(buffers) = buffers {
6341 this.shared_buffers.insert(new_peer_id, buffers);
6342 }
6343
6344 if is_host {
6345 this.opened_buffers
6346 .retain(|_, buffer| !matches!(buffer, OpenBuffer::Operations(_)));
6347 this.buffer_ordered_messages_tx
6348 .unbounded_send(BufferOrderedMessage::Resync)
6349 .unwrap();
6350 }
6351
6352 cx.emit(Event::CollaboratorUpdated {
6353 old_peer_id,
6354 new_peer_id,
6355 });
6356 cx.notify();
6357 Ok(())
6358 })
6359 }
6360
6361 async fn handle_remove_collaborator(
6362 this: ModelHandle<Self>,
6363 envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
6364 _: Arc<Client>,
6365 mut cx: AsyncAppContext,
6366 ) -> Result<()> {
6367 this.update(&mut cx, |this, cx| {
6368 let peer_id = envelope
6369 .payload
6370 .peer_id
6371 .ok_or_else(|| anyhow!("invalid peer id"))?;
6372 let replica_id = this
6373 .collaborators
6374 .remove(&peer_id)
6375 .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
6376 .replica_id;
6377 for buffer in this.opened_buffers.values() {
6378 if let Some(buffer) = buffer.upgrade(cx) {
6379 buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
6380 }
6381 }
6382 this.shared_buffers.remove(&peer_id);
6383
6384 cx.emit(Event::CollaboratorLeft(peer_id));
6385 cx.notify();
6386 Ok(())
6387 })
6388 }
6389
6390 async fn handle_update_project(
6391 this: ModelHandle<Self>,
6392 envelope: TypedEnvelope<proto::UpdateProject>,
6393 _: Arc<Client>,
6394 mut cx: AsyncAppContext,
6395 ) -> Result<()> {
6396 this.update(&mut cx, |this, cx| {
6397 // Don't handle messages that were sent before the response to us joining the project
6398 if envelope.message_id > this.join_project_response_message_id {
6399 this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
6400 }
6401 Ok(())
6402 })
6403 }
6404
6405 async fn handle_update_worktree(
6406 this: ModelHandle<Self>,
6407 envelope: TypedEnvelope<proto::UpdateWorktree>,
6408 _: Arc<Client>,
6409 mut cx: AsyncAppContext,
6410 ) -> Result<()> {
6411 this.update(&mut cx, |this, cx| {
6412 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
6413 if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
6414 worktree.update(cx, |worktree, _| {
6415 let worktree = worktree.as_remote_mut().unwrap();
6416 worktree.update_from_remote(envelope.payload);
6417 });
6418 }
6419 Ok(())
6420 })
6421 }
6422
6423 async fn handle_update_worktree_settings(
6424 this: ModelHandle<Self>,
6425 envelope: TypedEnvelope<proto::UpdateWorktreeSettings>,
6426 _: Arc<Client>,
6427 mut cx: AsyncAppContext,
6428 ) -> Result<()> {
6429 this.update(&mut cx, |this, cx| {
6430 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
6431 if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
6432 cx.update_global::<SettingsStore, _, _>(|store, cx| {
6433 store
6434 .set_local_settings(
6435 worktree.id(),
6436 PathBuf::from(&envelope.payload.path).into(),
6437 envelope.payload.content.as_ref().map(String::as_str),
6438 cx,
6439 )
6440 .log_err();
6441 });
6442 }
6443 Ok(())
6444 })
6445 }
6446
6447 async fn handle_create_project_entry(
6448 this: ModelHandle<Self>,
6449 envelope: TypedEnvelope<proto::CreateProjectEntry>,
6450 _: Arc<Client>,
6451 mut cx: AsyncAppContext,
6452 ) -> Result<proto::ProjectEntryResponse> {
6453 let worktree = this.update(&mut cx, |this, cx| {
6454 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
6455 this.worktree_for_id(worktree_id, cx)
6456 .ok_or_else(|| anyhow!("worktree not found"))
6457 })?;
6458 let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
6459 let entry = worktree
6460 .update(&mut cx, |worktree, cx| {
6461 let worktree = worktree.as_local_mut().unwrap();
6462 let path = PathBuf::from(envelope.payload.path);
6463 worktree.create_entry(path, envelope.payload.is_directory, cx)
6464 })
6465 .await?;
6466 Ok(proto::ProjectEntryResponse {
6467 entry: Some((&entry).into()),
6468 worktree_scan_id: worktree_scan_id as u64,
6469 })
6470 }
6471
6472 async fn handle_rename_project_entry(
6473 this: ModelHandle<Self>,
6474 envelope: TypedEnvelope<proto::RenameProjectEntry>,
6475 _: Arc<Client>,
6476 mut cx: AsyncAppContext,
6477 ) -> Result<proto::ProjectEntryResponse> {
6478 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
6479 let worktree = this.read_with(&cx, |this, cx| {
6480 this.worktree_for_entry(entry_id, cx)
6481 .ok_or_else(|| anyhow!("worktree not found"))
6482 })?;
6483 let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
6484 let entry = worktree
6485 .update(&mut cx, |worktree, cx| {
6486 let new_path = PathBuf::from(envelope.payload.new_path);
6487 worktree
6488 .as_local_mut()
6489 .unwrap()
6490 .rename_entry(entry_id, new_path, cx)
6491 .ok_or_else(|| anyhow!("invalid entry"))
6492 })?
6493 .await?;
6494 Ok(proto::ProjectEntryResponse {
6495 entry: Some((&entry).into()),
6496 worktree_scan_id: worktree_scan_id as u64,
6497 })
6498 }
6499
6500 async fn handle_copy_project_entry(
6501 this: ModelHandle<Self>,
6502 envelope: TypedEnvelope<proto::CopyProjectEntry>,
6503 _: Arc<Client>,
6504 mut cx: AsyncAppContext,
6505 ) -> Result<proto::ProjectEntryResponse> {
6506 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
6507 let worktree = this.read_with(&cx, |this, cx| {
6508 this.worktree_for_entry(entry_id, cx)
6509 .ok_or_else(|| anyhow!("worktree not found"))
6510 })?;
6511 let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
6512 let entry = worktree
6513 .update(&mut cx, |worktree, cx| {
6514 let new_path = PathBuf::from(envelope.payload.new_path);
6515 worktree
6516 .as_local_mut()
6517 .unwrap()
6518 .copy_entry(entry_id, new_path, cx)
6519 .ok_or_else(|| anyhow!("invalid entry"))
6520 })?
6521 .await?;
6522 Ok(proto::ProjectEntryResponse {
6523 entry: Some((&entry).into()),
6524 worktree_scan_id: worktree_scan_id as u64,
6525 })
6526 }
6527
6528 async fn handle_delete_project_entry(
6529 this: ModelHandle<Self>,
6530 envelope: TypedEnvelope<proto::DeleteProjectEntry>,
6531 _: Arc<Client>,
6532 mut cx: AsyncAppContext,
6533 ) -> Result<proto::ProjectEntryResponse> {
6534 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
6535
6536 this.update(&mut cx, |_, cx| cx.emit(Event::DeletedEntry(entry_id)));
6537
6538 let worktree = this.read_with(&cx, |this, cx| {
6539 this.worktree_for_entry(entry_id, cx)
6540 .ok_or_else(|| anyhow!("worktree not found"))
6541 })?;
6542 let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
6543 worktree
6544 .update(&mut cx, |worktree, cx| {
6545 worktree
6546 .as_local_mut()
6547 .unwrap()
6548 .delete_entry(entry_id, cx)
6549 .ok_or_else(|| anyhow!("invalid entry"))
6550 })?
6551 .await?;
6552 Ok(proto::ProjectEntryResponse {
6553 entry: None,
6554 worktree_scan_id: worktree_scan_id as u64,
6555 })
6556 }
6557
6558 async fn handle_expand_project_entry(
6559 this: ModelHandle<Self>,
6560 envelope: TypedEnvelope<proto::ExpandProjectEntry>,
6561 _: Arc<Client>,
6562 mut cx: AsyncAppContext,
6563 ) -> Result<proto::ExpandProjectEntryResponse> {
6564 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
6565 let worktree = this
6566 .read_with(&cx, |this, cx| this.worktree_for_entry(entry_id, cx))
6567 .ok_or_else(|| anyhow!("invalid request"))?;
6568 worktree
6569 .update(&mut cx, |worktree, cx| {
6570 worktree
6571 .as_local_mut()
6572 .unwrap()
6573 .expand_entry(entry_id, cx)
6574 .ok_or_else(|| anyhow!("invalid entry"))
6575 })?
6576 .await?;
6577 let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id()) as u64;
6578 Ok(proto::ExpandProjectEntryResponse { worktree_scan_id })
6579 }
6580
6581 async fn handle_update_diagnostic_summary(
6582 this: ModelHandle<Self>,
6583 envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
6584 _: Arc<Client>,
6585 mut cx: AsyncAppContext,
6586 ) -> Result<()> {
6587 this.update(&mut cx, |this, cx| {
6588 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
6589 if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
6590 if let Some(summary) = envelope.payload.summary {
6591 let project_path = ProjectPath {
6592 worktree_id,
6593 path: Path::new(&summary.path).into(),
6594 };
6595 worktree.update(cx, |worktree, _| {
6596 worktree
6597 .as_remote_mut()
6598 .unwrap()
6599 .update_diagnostic_summary(project_path.path.clone(), &summary);
6600 });
6601 cx.emit(Event::DiagnosticsUpdated {
6602 language_server_id: LanguageServerId(summary.language_server_id as usize),
6603 path: project_path,
6604 });
6605 }
6606 }
6607 Ok(())
6608 })
6609 }
6610
6611 async fn handle_start_language_server(
6612 this: ModelHandle<Self>,
6613 envelope: TypedEnvelope<proto::StartLanguageServer>,
6614 _: Arc<Client>,
6615 mut cx: AsyncAppContext,
6616 ) -> Result<()> {
6617 let server = envelope
6618 .payload
6619 .server
6620 .ok_or_else(|| anyhow!("invalid server"))?;
6621 this.update(&mut cx, |this, cx| {
6622 this.language_server_statuses.insert(
6623 LanguageServerId(server.id as usize),
6624 LanguageServerStatus {
6625 name: server.name,
6626 pending_work: Default::default(),
6627 has_pending_diagnostic_updates: false,
6628 progress_tokens: Default::default(),
6629 },
6630 );
6631 cx.notify();
6632 });
6633 Ok(())
6634 }
6635
6636 async fn handle_update_language_server(
6637 this: ModelHandle<Self>,
6638 envelope: TypedEnvelope<proto::UpdateLanguageServer>,
6639 _: Arc<Client>,
6640 mut cx: AsyncAppContext,
6641 ) -> Result<()> {
6642 this.update(&mut cx, |this, cx| {
6643 let language_server_id = LanguageServerId(envelope.payload.language_server_id as usize);
6644
6645 match envelope
6646 .payload
6647 .variant
6648 .ok_or_else(|| anyhow!("invalid variant"))?
6649 {
6650 proto::update_language_server::Variant::WorkStart(payload) => {
6651 this.on_lsp_work_start(
6652 language_server_id,
6653 payload.token,
6654 LanguageServerProgress {
6655 message: payload.message,
6656 percentage: payload.percentage.map(|p| p as usize),
6657 last_update_at: Instant::now(),
6658 },
6659 cx,
6660 );
6661 }
6662
6663 proto::update_language_server::Variant::WorkProgress(payload) => {
6664 this.on_lsp_work_progress(
6665 language_server_id,
6666 payload.token,
6667 LanguageServerProgress {
6668 message: payload.message,
6669 percentage: payload.percentage.map(|p| p as usize),
6670 last_update_at: Instant::now(),
6671 },
6672 cx,
6673 );
6674 }
6675
6676 proto::update_language_server::Variant::WorkEnd(payload) => {
6677 this.on_lsp_work_end(language_server_id, payload.token, cx);
6678 }
6679
6680 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(_) => {
6681 this.disk_based_diagnostics_started(language_server_id, cx);
6682 }
6683
6684 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(_) => {
6685 this.disk_based_diagnostics_finished(language_server_id, cx)
6686 }
6687 }
6688
6689 Ok(())
6690 })
6691 }
6692
6693 async fn handle_update_buffer(
6694 this: ModelHandle<Self>,
6695 envelope: TypedEnvelope<proto::UpdateBuffer>,
6696 _: Arc<Client>,
6697 mut cx: AsyncAppContext,
6698 ) -> Result<proto::Ack> {
6699 this.update(&mut cx, |this, cx| {
6700 let payload = envelope.payload.clone();
6701 let buffer_id = payload.buffer_id;
6702 let ops = payload
6703 .operations
6704 .into_iter()
6705 .map(language::proto::deserialize_operation)
6706 .collect::<Result<Vec<_>, _>>()?;
6707 let is_remote = this.is_remote();
6708 match this.opened_buffers.entry(buffer_id) {
6709 hash_map::Entry::Occupied(mut e) => match e.get_mut() {
6710 OpenBuffer::Strong(buffer) => {
6711 buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx))?;
6712 }
6713 OpenBuffer::Operations(operations) => operations.extend_from_slice(&ops),
6714 OpenBuffer::Weak(_) => {}
6715 },
6716 hash_map::Entry::Vacant(e) => {
6717 assert!(
6718 is_remote,
6719 "received buffer update from {:?}",
6720 envelope.original_sender_id
6721 );
6722 e.insert(OpenBuffer::Operations(ops));
6723 }
6724 }
6725 Ok(proto::Ack {})
6726 })
6727 }
6728
6729 async fn handle_create_buffer_for_peer(
6730 this: ModelHandle<Self>,
6731 envelope: TypedEnvelope<proto::CreateBufferForPeer>,
6732 _: Arc<Client>,
6733 mut cx: AsyncAppContext,
6734 ) -> Result<()> {
6735 this.update(&mut cx, |this, cx| {
6736 match envelope
6737 .payload
6738 .variant
6739 .ok_or_else(|| anyhow!("missing variant"))?
6740 {
6741 proto::create_buffer_for_peer::Variant::State(mut state) => {
6742 let mut buffer_file = None;
6743 if let Some(file) = state.file.take() {
6744 let worktree_id = WorktreeId::from_proto(file.worktree_id);
6745 let worktree = this.worktree_for_id(worktree_id, cx).ok_or_else(|| {
6746 anyhow!("no worktree found for id {}", file.worktree_id)
6747 })?;
6748 buffer_file = Some(Arc::new(File::from_proto(file, worktree.clone(), cx)?)
6749 as Arc<dyn language::File>);
6750 }
6751
6752 let buffer_id = state.id;
6753 let buffer = cx.add_model(|_| {
6754 Buffer::from_proto(this.replica_id(), state, buffer_file).unwrap()
6755 });
6756 this.incomplete_remote_buffers
6757 .insert(buffer_id, Some(buffer));
6758 }
6759 proto::create_buffer_for_peer::Variant::Chunk(chunk) => {
6760 let buffer = this
6761 .incomplete_remote_buffers
6762 .get(&chunk.buffer_id)
6763 .cloned()
6764 .flatten()
6765 .ok_or_else(|| {
6766 anyhow!(
6767 "received chunk for buffer {} without initial state",
6768 chunk.buffer_id
6769 )
6770 })?;
6771 let operations = chunk
6772 .operations
6773 .into_iter()
6774 .map(language::proto::deserialize_operation)
6775 .collect::<Result<Vec<_>>>()?;
6776 buffer.update(cx, |buffer, cx| buffer.apply_ops(operations, cx))?;
6777
6778 if chunk.is_last {
6779 this.incomplete_remote_buffers.remove(&chunk.buffer_id);
6780 this.register_buffer(&buffer, cx)?;
6781 }
6782 }
6783 }
6784
6785 Ok(())
6786 })
6787 }
6788
6789 async fn handle_update_diff_base(
6790 this: ModelHandle<Self>,
6791 envelope: TypedEnvelope<proto::UpdateDiffBase>,
6792 _: Arc<Client>,
6793 mut cx: AsyncAppContext,
6794 ) -> Result<()> {
6795 this.update(&mut cx, |this, cx| {
6796 let buffer_id = envelope.payload.buffer_id;
6797 let diff_base = envelope.payload.diff_base;
6798 if let Some(buffer) = this
6799 .opened_buffers
6800 .get_mut(&buffer_id)
6801 .and_then(|b| b.upgrade(cx))
6802 .or_else(|| {
6803 this.incomplete_remote_buffers
6804 .get(&buffer_id)
6805 .cloned()
6806 .flatten()
6807 })
6808 {
6809 buffer.update(cx, |buffer, cx| buffer.set_diff_base(diff_base, cx));
6810 }
6811 Ok(())
6812 })
6813 }
6814
6815 async fn handle_update_buffer_file(
6816 this: ModelHandle<Self>,
6817 envelope: TypedEnvelope<proto::UpdateBufferFile>,
6818 _: Arc<Client>,
6819 mut cx: AsyncAppContext,
6820 ) -> Result<()> {
6821 let buffer_id = envelope.payload.buffer_id;
6822
6823 this.update(&mut cx, |this, cx| {
6824 let payload = envelope.payload.clone();
6825 if let Some(buffer) = this
6826 .opened_buffers
6827 .get(&buffer_id)
6828 .and_then(|b| b.upgrade(cx))
6829 .or_else(|| {
6830 this.incomplete_remote_buffers
6831 .get(&buffer_id)
6832 .cloned()
6833 .flatten()
6834 })
6835 {
6836 let file = payload.file.ok_or_else(|| anyhow!("invalid file"))?;
6837 let worktree = this
6838 .worktree_for_id(WorktreeId::from_proto(file.worktree_id), cx)
6839 .ok_or_else(|| anyhow!("no such worktree"))?;
6840 let file = File::from_proto(file, worktree, cx)?;
6841 buffer.update(cx, |buffer, cx| {
6842 buffer.file_updated(Arc::new(file), cx).detach();
6843 });
6844 this.detect_language_for_buffer(&buffer, cx);
6845 }
6846 Ok(())
6847 })
6848 }
6849
6850 async fn handle_save_buffer(
6851 this: ModelHandle<Self>,
6852 envelope: TypedEnvelope<proto::SaveBuffer>,
6853 _: Arc<Client>,
6854 mut cx: AsyncAppContext,
6855 ) -> Result<proto::BufferSaved> {
6856 let buffer_id = envelope.payload.buffer_id;
6857 let (project_id, buffer) = this.update(&mut cx, |this, cx| {
6858 let project_id = this.remote_id().ok_or_else(|| anyhow!("not connected"))?;
6859 let buffer = this
6860 .opened_buffers
6861 .get(&buffer_id)
6862 .and_then(|buffer| buffer.upgrade(cx))
6863 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
6864 anyhow::Ok((project_id, buffer))
6865 })?;
6866 buffer
6867 .update(&mut cx, |buffer, _| {
6868 buffer.wait_for_version(deserialize_version(&envelope.payload.version))
6869 })
6870 .await?;
6871 let buffer_id = buffer.read_with(&cx, |buffer, _| buffer.remote_id());
6872
6873 this.update(&mut cx, |this, cx| this.save_buffer(buffer.clone(), cx))
6874 .await?;
6875 Ok(buffer.read_with(&cx, |buffer, _| proto::BufferSaved {
6876 project_id,
6877 buffer_id,
6878 version: serialize_version(buffer.saved_version()),
6879 mtime: Some(buffer.saved_mtime().into()),
6880 fingerprint: language::proto::serialize_fingerprint(buffer.saved_version_fingerprint()),
6881 }))
6882 }
6883
6884 async fn handle_reload_buffers(
6885 this: ModelHandle<Self>,
6886 envelope: TypedEnvelope<proto::ReloadBuffers>,
6887 _: Arc<Client>,
6888 mut cx: AsyncAppContext,
6889 ) -> Result<proto::ReloadBuffersResponse> {
6890 let sender_id = envelope.original_sender_id()?;
6891 let reload = this.update(&mut cx, |this, cx| {
6892 let mut buffers = HashSet::default();
6893 for buffer_id in &envelope.payload.buffer_ids {
6894 buffers.insert(
6895 this.opened_buffers
6896 .get(buffer_id)
6897 .and_then(|buffer| buffer.upgrade(cx))
6898 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
6899 );
6900 }
6901 Ok::<_, anyhow::Error>(this.reload_buffers(buffers, false, cx))
6902 })?;
6903
6904 let project_transaction = reload.await?;
6905 let project_transaction = this.update(&mut cx, |this, cx| {
6906 this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
6907 });
6908 Ok(proto::ReloadBuffersResponse {
6909 transaction: Some(project_transaction),
6910 })
6911 }
6912
6913 async fn handle_synchronize_buffers(
6914 this: ModelHandle<Self>,
6915 envelope: TypedEnvelope<proto::SynchronizeBuffers>,
6916 _: Arc<Client>,
6917 mut cx: AsyncAppContext,
6918 ) -> Result<proto::SynchronizeBuffersResponse> {
6919 let project_id = envelope.payload.project_id;
6920 let mut response = proto::SynchronizeBuffersResponse {
6921 buffers: Default::default(),
6922 };
6923
6924 this.update(&mut cx, |this, cx| {
6925 let Some(guest_id) = envelope.original_sender_id else {
6926 error!("missing original_sender_id on SynchronizeBuffers request");
6927 return;
6928 };
6929
6930 this.shared_buffers.entry(guest_id).or_default().clear();
6931 for buffer in envelope.payload.buffers {
6932 let buffer_id = buffer.id;
6933 let remote_version = language::proto::deserialize_version(&buffer.version);
6934 if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
6935 this.shared_buffers
6936 .entry(guest_id)
6937 .or_default()
6938 .insert(buffer_id);
6939
6940 let buffer = buffer.read(cx);
6941 response.buffers.push(proto::BufferVersion {
6942 id: buffer_id,
6943 version: language::proto::serialize_version(&buffer.version),
6944 });
6945
6946 let operations = buffer.serialize_ops(Some(remote_version), cx);
6947 let client = this.client.clone();
6948 if let Some(file) = buffer.file() {
6949 client
6950 .send(proto::UpdateBufferFile {
6951 project_id,
6952 buffer_id: buffer_id as u64,
6953 file: Some(file.to_proto()),
6954 })
6955 .log_err();
6956 }
6957
6958 client
6959 .send(proto::UpdateDiffBase {
6960 project_id,
6961 buffer_id: buffer_id as u64,
6962 diff_base: buffer.diff_base().map(Into::into),
6963 })
6964 .log_err();
6965
6966 client
6967 .send(proto::BufferReloaded {
6968 project_id,
6969 buffer_id,
6970 version: language::proto::serialize_version(buffer.saved_version()),
6971 mtime: Some(buffer.saved_mtime().into()),
6972 fingerprint: language::proto::serialize_fingerprint(
6973 buffer.saved_version_fingerprint(),
6974 ),
6975 line_ending: language::proto::serialize_line_ending(
6976 buffer.line_ending(),
6977 ) as i32,
6978 })
6979 .log_err();
6980
6981 cx.background()
6982 .spawn(
6983 async move {
6984 let operations = operations.await;
6985 for chunk in split_operations(operations) {
6986 client
6987 .request(proto::UpdateBuffer {
6988 project_id,
6989 buffer_id,
6990 operations: chunk,
6991 })
6992 .await?;
6993 }
6994 anyhow::Ok(())
6995 }
6996 .log_err(),
6997 )
6998 .detach();
6999 }
7000 }
7001 });
7002
7003 Ok(response)
7004 }
7005
7006 async fn handle_format_buffers(
7007 this: ModelHandle<Self>,
7008 envelope: TypedEnvelope<proto::FormatBuffers>,
7009 _: Arc<Client>,
7010 mut cx: AsyncAppContext,
7011 ) -> Result<proto::FormatBuffersResponse> {
7012 let sender_id = envelope.original_sender_id()?;
7013 let format = this.update(&mut cx, |this, cx| {
7014 let mut buffers = HashSet::default();
7015 for buffer_id in &envelope.payload.buffer_ids {
7016 buffers.insert(
7017 this.opened_buffers
7018 .get(buffer_id)
7019 .and_then(|buffer| buffer.upgrade(cx))
7020 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
7021 );
7022 }
7023 let trigger = FormatTrigger::from_proto(envelope.payload.trigger);
7024 Ok::<_, anyhow::Error>(this.format(buffers, false, trigger, cx))
7025 })?;
7026
7027 let project_transaction = format.await?;
7028 let project_transaction = this.update(&mut cx, |this, cx| {
7029 this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
7030 });
7031 Ok(proto::FormatBuffersResponse {
7032 transaction: Some(project_transaction),
7033 })
7034 }
7035
7036 async fn handle_apply_additional_edits_for_completion(
7037 this: ModelHandle<Self>,
7038 envelope: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
7039 _: Arc<Client>,
7040 mut cx: AsyncAppContext,
7041 ) -> Result<proto::ApplyCompletionAdditionalEditsResponse> {
7042 let (buffer, completion) = this.update(&mut cx, |this, cx| {
7043 let buffer = this
7044 .opened_buffers
7045 .get(&envelope.payload.buffer_id)
7046 .and_then(|buffer| buffer.upgrade(cx))
7047 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
7048 let language = buffer.read(cx).language();
7049 let completion = language::proto::deserialize_completion(
7050 envelope
7051 .payload
7052 .completion
7053 .ok_or_else(|| anyhow!("invalid completion"))?,
7054 language.cloned(),
7055 );
7056 Ok::<_, anyhow::Error>((buffer, completion))
7057 })?;
7058
7059 let completion = completion.await?;
7060
7061 let apply_additional_edits = this.update(&mut cx, |this, cx| {
7062 this.apply_additional_edits_for_completion(buffer, completion, false, cx)
7063 });
7064
7065 Ok(proto::ApplyCompletionAdditionalEditsResponse {
7066 transaction: apply_additional_edits
7067 .await?
7068 .as_ref()
7069 .map(language::proto::serialize_transaction),
7070 })
7071 }
7072
7073 async fn handle_apply_code_action(
7074 this: ModelHandle<Self>,
7075 envelope: TypedEnvelope<proto::ApplyCodeAction>,
7076 _: Arc<Client>,
7077 mut cx: AsyncAppContext,
7078 ) -> Result<proto::ApplyCodeActionResponse> {
7079 let sender_id = envelope.original_sender_id()?;
7080 let action = language::proto::deserialize_code_action(
7081 envelope
7082 .payload
7083 .action
7084 .ok_or_else(|| anyhow!("invalid action"))?,
7085 )?;
7086 let apply_code_action = this.update(&mut cx, |this, cx| {
7087 let buffer = this
7088 .opened_buffers
7089 .get(&envelope.payload.buffer_id)
7090 .and_then(|buffer| buffer.upgrade(cx))
7091 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
7092 Ok::<_, anyhow::Error>(this.apply_code_action(buffer, action, false, cx))
7093 })?;
7094
7095 let project_transaction = apply_code_action.await?;
7096 let project_transaction = this.update(&mut cx, |this, cx| {
7097 this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
7098 });
7099 Ok(proto::ApplyCodeActionResponse {
7100 transaction: Some(project_transaction),
7101 })
7102 }
7103
7104 async fn handle_on_type_formatting(
7105 this: ModelHandle<Self>,
7106 envelope: TypedEnvelope<proto::OnTypeFormatting>,
7107 _: Arc<Client>,
7108 mut cx: AsyncAppContext,
7109 ) -> Result<proto::OnTypeFormattingResponse> {
7110 let on_type_formatting = this.update(&mut cx, |this, cx| {
7111 let buffer = this
7112 .opened_buffers
7113 .get(&envelope.payload.buffer_id)
7114 .and_then(|buffer| buffer.upgrade(cx))
7115 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
7116 let position = envelope
7117 .payload
7118 .position
7119 .and_then(deserialize_anchor)
7120 .ok_or_else(|| anyhow!("invalid position"))?;
7121 Ok::<_, anyhow::Error>(this.apply_on_type_formatting(
7122 buffer,
7123 position,
7124 envelope.payload.trigger.clone(),
7125 cx,
7126 ))
7127 })?;
7128
7129 let transaction = on_type_formatting
7130 .await?
7131 .as_ref()
7132 .map(language::proto::serialize_transaction);
7133 Ok(proto::OnTypeFormattingResponse { transaction })
7134 }
7135
7136 async fn handle_inlay_hints(
7137 this: ModelHandle<Self>,
7138 envelope: TypedEnvelope<proto::InlayHints>,
7139 _: Arc<Client>,
7140 mut cx: AsyncAppContext,
7141 ) -> Result<proto::InlayHintsResponse> {
7142 let sender_id = envelope.original_sender_id()?;
7143 let buffer = this.update(&mut cx, |this, cx| {
7144 this.opened_buffers
7145 .get(&envelope.payload.buffer_id)
7146 .and_then(|buffer| buffer.upgrade(cx))
7147 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
7148 })?;
7149 let buffer_version = deserialize_version(&envelope.payload.version);
7150
7151 buffer
7152 .update(&mut cx, |buffer, _| {
7153 buffer.wait_for_version(buffer_version.clone())
7154 })
7155 .await
7156 .with_context(|| {
7157 format!(
7158 "waiting for version {:?} for buffer {}",
7159 buffer_version,
7160 buffer.id()
7161 )
7162 })?;
7163
7164 let start = envelope
7165 .payload
7166 .start
7167 .and_then(deserialize_anchor)
7168 .context("missing range start")?;
7169 let end = envelope
7170 .payload
7171 .end
7172 .and_then(deserialize_anchor)
7173 .context("missing range end")?;
7174 let buffer_hints = this
7175 .update(&mut cx, |project, cx| {
7176 project.inlay_hints(buffer, start..end, cx)
7177 })
7178 .await
7179 .context("inlay hints fetch")?;
7180
7181 Ok(this.update(&mut cx, |project, cx| {
7182 InlayHints::response_to_proto(buffer_hints, project, sender_id, &buffer_version, cx)
7183 }))
7184 }
7185
7186 async fn handle_resolve_inlay_hint(
7187 this: ModelHandle<Self>,
7188 envelope: TypedEnvelope<proto::ResolveInlayHint>,
7189 _: Arc<Client>,
7190 mut cx: AsyncAppContext,
7191 ) -> Result<proto::ResolveInlayHintResponse> {
7192 let proto_hint = envelope
7193 .payload
7194 .hint
7195 .expect("incorrect protobuf resolve inlay hint message: missing the inlay hint");
7196 let hint = InlayHints::proto_to_project_hint(proto_hint)
7197 .context("resolved proto inlay hint conversion")?;
7198 let buffer = this.update(&mut cx, |this, cx| {
7199 this.opened_buffers
7200 .get(&envelope.payload.buffer_id)
7201 .and_then(|buffer| buffer.upgrade(cx))
7202 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
7203 })?;
7204 let response_hint = this
7205 .update(&mut cx, |project, cx| {
7206 project.resolve_inlay_hint(
7207 hint,
7208 buffer,
7209 LanguageServerId(envelope.payload.language_server_id as usize),
7210 cx,
7211 )
7212 })
7213 .await
7214 .context("inlay hints fetch")?;
7215 Ok(proto::ResolveInlayHintResponse {
7216 hint: Some(InlayHints::project_to_proto_hint(response_hint)),
7217 })
7218 }
7219
7220 async fn handle_refresh_inlay_hints(
7221 this: ModelHandle<Self>,
7222 _: TypedEnvelope<proto::RefreshInlayHints>,
7223 _: Arc<Client>,
7224 mut cx: AsyncAppContext,
7225 ) -> Result<proto::Ack> {
7226 this.update(&mut cx, |_, cx| {
7227 cx.emit(Event::RefreshInlayHints);
7228 });
7229 Ok(proto::Ack {})
7230 }
7231
7232 async fn handle_lsp_command<T: LspCommand>(
7233 this: ModelHandle<Self>,
7234 envelope: TypedEnvelope<T::ProtoRequest>,
7235 _: Arc<Client>,
7236 mut cx: AsyncAppContext,
7237 ) -> Result<<T::ProtoRequest as proto::RequestMessage>::Response>
7238 where
7239 <T::LspRequest as lsp::request::Request>::Result: Send,
7240 {
7241 let sender_id = envelope.original_sender_id()?;
7242 let buffer_id = T::buffer_id_from_proto(&envelope.payload);
7243 let buffer_handle = this.read_with(&cx, |this, _| {
7244 this.opened_buffers
7245 .get(&buffer_id)
7246 .and_then(|buffer| buffer.upgrade(&cx))
7247 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
7248 })?;
7249 let request = T::from_proto(
7250 envelope.payload,
7251 this.clone(),
7252 buffer_handle.clone(),
7253 cx.clone(),
7254 )
7255 .await?;
7256 let buffer_version = buffer_handle.read_with(&cx, |buffer, _| buffer.version());
7257 let response = this
7258 .update(&mut cx, |this, cx| {
7259 this.request_lsp(buffer_handle, LanguageServerToQuery::Primary, request, cx)
7260 })
7261 .await?;
7262 this.update(&mut cx, |this, cx| {
7263 Ok(T::response_to_proto(
7264 response,
7265 this,
7266 sender_id,
7267 &buffer_version,
7268 cx,
7269 ))
7270 })
7271 }
7272
7273 async fn handle_get_project_symbols(
7274 this: ModelHandle<Self>,
7275 envelope: TypedEnvelope<proto::GetProjectSymbols>,
7276 _: Arc<Client>,
7277 mut cx: AsyncAppContext,
7278 ) -> Result<proto::GetProjectSymbolsResponse> {
7279 let symbols = this
7280 .update(&mut cx, |this, cx| {
7281 this.symbols(&envelope.payload.query, cx)
7282 })
7283 .await?;
7284
7285 Ok(proto::GetProjectSymbolsResponse {
7286 symbols: symbols.iter().map(serialize_symbol).collect(),
7287 })
7288 }
7289
7290 async fn handle_search_project(
7291 this: ModelHandle<Self>,
7292 envelope: TypedEnvelope<proto::SearchProject>,
7293 _: Arc<Client>,
7294 mut cx: AsyncAppContext,
7295 ) -> Result<proto::SearchProjectResponse> {
7296 let peer_id = envelope.original_sender_id()?;
7297 let query = SearchQuery::from_proto(envelope.payload)?;
7298 let mut result = this.update(&mut cx, |this, cx| this.search(query, cx));
7299
7300 cx.spawn(|mut cx| async move {
7301 let mut locations = Vec::new();
7302 while let Some((buffer, ranges)) = result.next().await {
7303 for range in ranges {
7304 let start = serialize_anchor(&range.start);
7305 let end = serialize_anchor(&range.end);
7306 let buffer_id = this.update(&mut cx, |this, cx| {
7307 this.create_buffer_for_peer(&buffer, peer_id, cx)
7308 });
7309 locations.push(proto::Location {
7310 buffer_id,
7311 start: Some(start),
7312 end: Some(end),
7313 });
7314 }
7315 }
7316 Ok(proto::SearchProjectResponse { locations })
7317 })
7318 .await
7319 }
7320
7321 async fn handle_open_buffer_for_symbol(
7322 this: ModelHandle<Self>,
7323 envelope: TypedEnvelope<proto::OpenBufferForSymbol>,
7324 _: Arc<Client>,
7325 mut cx: AsyncAppContext,
7326 ) -> Result<proto::OpenBufferForSymbolResponse> {
7327 let peer_id = envelope.original_sender_id()?;
7328 let symbol = envelope
7329 .payload
7330 .symbol
7331 .ok_or_else(|| anyhow!("invalid symbol"))?;
7332 let symbol = this
7333 .read_with(&cx, |this, _| this.deserialize_symbol(symbol))
7334 .await?;
7335 let symbol = this.read_with(&cx, |this, _| {
7336 let signature = this.symbol_signature(&symbol.path);
7337 if signature == symbol.signature {
7338 Ok(symbol)
7339 } else {
7340 Err(anyhow!("invalid symbol signature"))
7341 }
7342 })?;
7343 let buffer = this
7344 .update(&mut cx, |this, cx| this.open_buffer_for_symbol(&symbol, cx))
7345 .await?;
7346
7347 Ok(proto::OpenBufferForSymbolResponse {
7348 buffer_id: this.update(&mut cx, |this, cx| {
7349 this.create_buffer_for_peer(&buffer, peer_id, cx)
7350 }),
7351 })
7352 }
7353
7354 fn symbol_signature(&self, project_path: &ProjectPath) -> [u8; 32] {
7355 let mut hasher = Sha256::new();
7356 hasher.update(project_path.worktree_id.to_proto().to_be_bytes());
7357 hasher.update(project_path.path.to_string_lossy().as_bytes());
7358 hasher.update(self.nonce.to_be_bytes());
7359 hasher.finalize().as_slice().try_into().unwrap()
7360 }
7361
7362 async fn handle_open_buffer_by_id(
7363 this: ModelHandle<Self>,
7364 envelope: TypedEnvelope<proto::OpenBufferById>,
7365 _: Arc<Client>,
7366 mut cx: AsyncAppContext,
7367 ) -> Result<proto::OpenBufferResponse> {
7368 let peer_id = envelope.original_sender_id()?;
7369 let buffer = this
7370 .update(&mut cx, |this, cx| {
7371 this.open_buffer_by_id(envelope.payload.id, cx)
7372 })
7373 .await?;
7374 this.update(&mut cx, |this, cx| {
7375 Ok(proto::OpenBufferResponse {
7376 buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx),
7377 })
7378 })
7379 }
7380
7381 async fn handle_open_buffer_by_path(
7382 this: ModelHandle<Self>,
7383 envelope: TypedEnvelope<proto::OpenBufferByPath>,
7384 _: Arc<Client>,
7385 mut cx: AsyncAppContext,
7386 ) -> Result<proto::OpenBufferResponse> {
7387 let peer_id = envelope.original_sender_id()?;
7388 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
7389 let open_buffer = this.update(&mut cx, |this, cx| {
7390 this.open_buffer(
7391 ProjectPath {
7392 worktree_id,
7393 path: PathBuf::from(envelope.payload.path).into(),
7394 },
7395 cx,
7396 )
7397 });
7398
7399 let buffer = open_buffer.await?;
7400 this.update(&mut cx, |this, cx| {
7401 Ok(proto::OpenBufferResponse {
7402 buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx),
7403 })
7404 })
7405 }
7406
7407 fn serialize_project_transaction_for_peer(
7408 &mut self,
7409 project_transaction: ProjectTransaction,
7410 peer_id: proto::PeerId,
7411 cx: &mut AppContext,
7412 ) -> proto::ProjectTransaction {
7413 let mut serialized_transaction = proto::ProjectTransaction {
7414 buffer_ids: Default::default(),
7415 transactions: Default::default(),
7416 };
7417 for (buffer, transaction) in project_transaction.0 {
7418 serialized_transaction
7419 .buffer_ids
7420 .push(self.create_buffer_for_peer(&buffer, peer_id, cx));
7421 serialized_transaction
7422 .transactions
7423 .push(language::proto::serialize_transaction(&transaction));
7424 }
7425 serialized_transaction
7426 }
7427
7428 fn deserialize_project_transaction(
7429 &mut self,
7430 message: proto::ProjectTransaction,
7431 push_to_history: bool,
7432 cx: &mut ModelContext<Self>,
7433 ) -> Task<Result<ProjectTransaction>> {
7434 cx.spawn(|this, mut cx| async move {
7435 let mut project_transaction = ProjectTransaction::default();
7436 for (buffer_id, transaction) in message.buffer_ids.into_iter().zip(message.transactions)
7437 {
7438 let buffer = this
7439 .update(&mut cx, |this, cx| {
7440 this.wait_for_remote_buffer(buffer_id, cx)
7441 })
7442 .await?;
7443 let transaction = language::proto::deserialize_transaction(transaction)?;
7444 project_transaction.0.insert(buffer, transaction);
7445 }
7446
7447 for (buffer, transaction) in &project_transaction.0 {
7448 buffer
7449 .update(&mut cx, |buffer, _| {
7450 buffer.wait_for_edits(transaction.edit_ids.iter().copied())
7451 })
7452 .await?;
7453
7454 if push_to_history {
7455 buffer.update(&mut cx, |buffer, _| {
7456 buffer.push_transaction(transaction.clone(), Instant::now());
7457 });
7458 }
7459 }
7460
7461 Ok(project_transaction)
7462 })
7463 }
7464
7465 fn create_buffer_for_peer(
7466 &mut self,
7467 buffer: &ModelHandle<Buffer>,
7468 peer_id: proto::PeerId,
7469 cx: &mut AppContext,
7470 ) -> u64 {
7471 let buffer_id = buffer.read(cx).remote_id();
7472 if let Some(ProjectClientState::Local { updates_tx, .. }) = &self.client_state {
7473 updates_tx
7474 .unbounded_send(LocalProjectUpdate::CreateBufferForPeer { peer_id, buffer_id })
7475 .ok();
7476 }
7477 buffer_id
7478 }
7479
7480 fn wait_for_remote_buffer(
7481 &mut self,
7482 id: u64,
7483 cx: &mut ModelContext<Self>,
7484 ) -> Task<Result<ModelHandle<Buffer>>> {
7485 let mut opened_buffer_rx = self.opened_buffer.1.clone();
7486
7487 cx.spawn_weak(|this, mut cx| async move {
7488 let buffer = loop {
7489 let Some(this) = this.upgrade(&cx) else {
7490 return Err(anyhow!("project dropped"));
7491 };
7492
7493 let buffer = this.read_with(&cx, |this, cx| {
7494 this.opened_buffers
7495 .get(&id)
7496 .and_then(|buffer| buffer.upgrade(cx))
7497 });
7498
7499 if let Some(buffer) = buffer {
7500 break buffer;
7501 } else if this.read_with(&cx, |this, _| this.is_read_only()) {
7502 return Err(anyhow!("disconnected before buffer {} could be opened", id));
7503 }
7504
7505 this.update(&mut cx, |this, _| {
7506 this.incomplete_remote_buffers.entry(id).or_default();
7507 });
7508 drop(this);
7509
7510 opened_buffer_rx
7511 .next()
7512 .await
7513 .ok_or_else(|| anyhow!("project dropped while waiting for buffer"))?;
7514 };
7515
7516 Ok(buffer)
7517 })
7518 }
7519
7520 fn synchronize_remote_buffers(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
7521 let project_id = match self.client_state.as_ref() {
7522 Some(ProjectClientState::Remote {
7523 sharing_has_stopped,
7524 remote_id,
7525 ..
7526 }) => {
7527 if *sharing_has_stopped {
7528 return Task::ready(Err(anyhow!(
7529 "can't synchronize remote buffers on a readonly project"
7530 )));
7531 } else {
7532 *remote_id
7533 }
7534 }
7535 Some(ProjectClientState::Local { .. }) | None => {
7536 return Task::ready(Err(anyhow!(
7537 "can't synchronize remote buffers on a local project"
7538 )))
7539 }
7540 };
7541
7542 let client = self.client.clone();
7543 cx.spawn(|this, cx| async move {
7544 let (buffers, incomplete_buffer_ids) = this.read_with(&cx, |this, cx| {
7545 let buffers = this
7546 .opened_buffers
7547 .iter()
7548 .filter_map(|(id, buffer)| {
7549 let buffer = buffer.upgrade(cx)?;
7550 Some(proto::BufferVersion {
7551 id: *id,
7552 version: language::proto::serialize_version(&buffer.read(cx).version),
7553 })
7554 })
7555 .collect();
7556 let incomplete_buffer_ids = this
7557 .incomplete_remote_buffers
7558 .keys()
7559 .copied()
7560 .collect::<Vec<_>>();
7561
7562 (buffers, incomplete_buffer_ids)
7563 });
7564 let response = client
7565 .request(proto::SynchronizeBuffers {
7566 project_id,
7567 buffers,
7568 })
7569 .await?;
7570
7571 let send_updates_for_buffers = response.buffers.into_iter().map(|buffer| {
7572 let client = client.clone();
7573 let buffer_id = buffer.id;
7574 let remote_version = language::proto::deserialize_version(&buffer.version);
7575 this.read_with(&cx, |this, cx| {
7576 if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
7577 let operations = buffer.read(cx).serialize_ops(Some(remote_version), cx);
7578 cx.background().spawn(async move {
7579 let operations = operations.await;
7580 for chunk in split_operations(operations) {
7581 client
7582 .request(proto::UpdateBuffer {
7583 project_id,
7584 buffer_id,
7585 operations: chunk,
7586 })
7587 .await?;
7588 }
7589 anyhow::Ok(())
7590 })
7591 } else {
7592 Task::ready(Ok(()))
7593 }
7594 })
7595 });
7596
7597 // Any incomplete buffers have open requests waiting. Request that the host sends
7598 // creates these buffers for us again to unblock any waiting futures.
7599 for id in incomplete_buffer_ids {
7600 cx.background()
7601 .spawn(client.request(proto::OpenBufferById { project_id, id }))
7602 .detach();
7603 }
7604
7605 futures::future::join_all(send_updates_for_buffers)
7606 .await
7607 .into_iter()
7608 .collect()
7609 })
7610 }
7611
7612 pub fn worktree_metadata_protos(&self, cx: &AppContext) -> Vec<proto::WorktreeMetadata> {
7613 self.worktrees(cx)
7614 .map(|worktree| {
7615 let worktree = worktree.read(cx);
7616 proto::WorktreeMetadata {
7617 id: worktree.id().to_proto(),
7618 root_name: worktree.root_name().into(),
7619 visible: worktree.is_visible(),
7620 abs_path: worktree.abs_path().to_string_lossy().into(),
7621 }
7622 })
7623 .collect()
7624 }
7625
7626 fn set_worktrees_from_proto(
7627 &mut self,
7628 worktrees: Vec<proto::WorktreeMetadata>,
7629 cx: &mut ModelContext<Project>,
7630 ) -> Result<()> {
7631 let replica_id = self.replica_id();
7632 let remote_id = self.remote_id().ok_or_else(|| anyhow!("invalid project"))?;
7633
7634 let mut old_worktrees_by_id = self
7635 .worktrees
7636 .drain(..)
7637 .filter_map(|worktree| {
7638 let worktree = worktree.upgrade(cx)?;
7639 Some((worktree.read(cx).id(), worktree))
7640 })
7641 .collect::<HashMap<_, _>>();
7642
7643 for worktree in worktrees {
7644 if let Some(old_worktree) =
7645 old_worktrees_by_id.remove(&WorktreeId::from_proto(worktree.id))
7646 {
7647 self.worktrees.push(WorktreeHandle::Strong(old_worktree));
7648 } else {
7649 let worktree =
7650 Worktree::remote(remote_id, replica_id, worktree, self.client.clone(), cx);
7651 let _ = self.add_worktree(&worktree, cx);
7652 }
7653 }
7654
7655 self.metadata_changed(cx);
7656 for id in old_worktrees_by_id.keys() {
7657 cx.emit(Event::WorktreeRemoved(*id));
7658 }
7659
7660 Ok(())
7661 }
7662
7663 fn set_collaborators_from_proto(
7664 &mut self,
7665 messages: Vec<proto::Collaborator>,
7666 cx: &mut ModelContext<Self>,
7667 ) -> Result<()> {
7668 let mut collaborators = HashMap::default();
7669 for message in messages {
7670 let collaborator = Collaborator::from_proto(message)?;
7671 collaborators.insert(collaborator.peer_id, collaborator);
7672 }
7673 for old_peer_id in self.collaborators.keys() {
7674 if !collaborators.contains_key(old_peer_id) {
7675 cx.emit(Event::CollaboratorLeft(*old_peer_id));
7676 }
7677 }
7678 self.collaborators = collaborators;
7679 Ok(())
7680 }
7681
7682 fn deserialize_symbol(
7683 &self,
7684 serialized_symbol: proto::Symbol,
7685 ) -> impl Future<Output = Result<Symbol>> {
7686 let languages = self.languages.clone();
7687 async move {
7688 let source_worktree_id = WorktreeId::from_proto(serialized_symbol.source_worktree_id);
7689 let worktree_id = WorktreeId::from_proto(serialized_symbol.worktree_id);
7690 let start = serialized_symbol
7691 .start
7692 .ok_or_else(|| anyhow!("invalid start"))?;
7693 let end = serialized_symbol
7694 .end
7695 .ok_or_else(|| anyhow!("invalid end"))?;
7696 let kind = unsafe { mem::transmute(serialized_symbol.kind) };
7697 let path = ProjectPath {
7698 worktree_id,
7699 path: PathBuf::from(serialized_symbol.path).into(),
7700 };
7701 let language = languages
7702 .language_for_file(&path.path, None)
7703 .await
7704 .log_err();
7705 Ok(Symbol {
7706 language_server_name: LanguageServerName(
7707 serialized_symbol.language_server_name.into(),
7708 ),
7709 source_worktree_id,
7710 path,
7711 label: {
7712 match language {
7713 Some(language) => {
7714 language
7715 .label_for_symbol(&serialized_symbol.name, kind)
7716 .await
7717 }
7718 None => None,
7719 }
7720 .unwrap_or_else(|| CodeLabel::plain(serialized_symbol.name.clone(), None))
7721 },
7722
7723 name: serialized_symbol.name,
7724 range: Unclipped(PointUtf16::new(start.row, start.column))
7725 ..Unclipped(PointUtf16::new(end.row, end.column)),
7726 kind,
7727 signature: serialized_symbol
7728 .signature
7729 .try_into()
7730 .map_err(|_| anyhow!("invalid signature"))?,
7731 })
7732 }
7733 }
7734
7735 async fn handle_buffer_saved(
7736 this: ModelHandle<Self>,
7737 envelope: TypedEnvelope<proto::BufferSaved>,
7738 _: Arc<Client>,
7739 mut cx: AsyncAppContext,
7740 ) -> Result<()> {
7741 let fingerprint = deserialize_fingerprint(&envelope.payload.fingerprint)?;
7742 let version = deserialize_version(&envelope.payload.version);
7743 let mtime = envelope
7744 .payload
7745 .mtime
7746 .ok_or_else(|| anyhow!("missing mtime"))?
7747 .into();
7748
7749 this.update(&mut cx, |this, cx| {
7750 let buffer = this
7751 .opened_buffers
7752 .get(&envelope.payload.buffer_id)
7753 .and_then(|buffer| buffer.upgrade(cx))
7754 .or_else(|| {
7755 this.incomplete_remote_buffers
7756 .get(&envelope.payload.buffer_id)
7757 .and_then(|b| b.clone())
7758 });
7759 if let Some(buffer) = buffer {
7760 buffer.update(cx, |buffer, cx| {
7761 buffer.did_save(version, fingerprint, mtime, cx);
7762 });
7763 }
7764 Ok(())
7765 })
7766 }
7767
7768 async fn handle_buffer_reloaded(
7769 this: ModelHandle<Self>,
7770 envelope: TypedEnvelope<proto::BufferReloaded>,
7771 _: Arc<Client>,
7772 mut cx: AsyncAppContext,
7773 ) -> Result<()> {
7774 let payload = envelope.payload;
7775 let version = deserialize_version(&payload.version);
7776 let fingerprint = deserialize_fingerprint(&payload.fingerprint)?;
7777 let line_ending = deserialize_line_ending(
7778 proto::LineEnding::from_i32(payload.line_ending)
7779 .ok_or_else(|| anyhow!("missing line ending"))?,
7780 );
7781 let mtime = payload
7782 .mtime
7783 .ok_or_else(|| anyhow!("missing mtime"))?
7784 .into();
7785 this.update(&mut cx, |this, cx| {
7786 let buffer = this
7787 .opened_buffers
7788 .get(&payload.buffer_id)
7789 .and_then(|buffer| buffer.upgrade(cx))
7790 .or_else(|| {
7791 this.incomplete_remote_buffers
7792 .get(&payload.buffer_id)
7793 .cloned()
7794 .flatten()
7795 });
7796 if let Some(buffer) = buffer {
7797 buffer.update(cx, |buffer, cx| {
7798 buffer.did_reload(version, fingerprint, line_ending, mtime, cx);
7799 });
7800 }
7801 Ok(())
7802 })
7803 }
7804
7805 #[allow(clippy::type_complexity)]
7806 fn edits_from_lsp(
7807 &mut self,
7808 buffer: &ModelHandle<Buffer>,
7809 lsp_edits: impl 'static + Send + IntoIterator<Item = lsp::TextEdit>,
7810 server_id: LanguageServerId,
7811 version: Option<i32>,
7812 cx: &mut ModelContext<Self>,
7813 ) -> Task<Result<Vec<(Range<Anchor>, String)>>> {
7814 let snapshot = self.buffer_snapshot_for_lsp_version(buffer, server_id, version, cx);
7815 cx.background().spawn(async move {
7816 let snapshot = snapshot?;
7817 let mut lsp_edits = lsp_edits
7818 .into_iter()
7819 .map(|edit| (range_from_lsp(edit.range), edit.new_text))
7820 .collect::<Vec<_>>();
7821 lsp_edits.sort_by_key(|(range, _)| range.start);
7822
7823 let mut lsp_edits = lsp_edits.into_iter().peekable();
7824 let mut edits = Vec::new();
7825 while let Some((range, mut new_text)) = lsp_edits.next() {
7826 // Clip invalid ranges provided by the language server.
7827 let mut range = snapshot.clip_point_utf16(range.start, Bias::Left)
7828 ..snapshot.clip_point_utf16(range.end, Bias::Left);
7829
7830 // Combine any LSP edits that are adjacent.
7831 //
7832 // Also, combine LSP edits that are separated from each other by only
7833 // a newline. This is important because for some code actions,
7834 // Rust-analyzer rewrites the entire buffer via a series of edits that
7835 // are separated by unchanged newline characters.
7836 //
7837 // In order for the diffing logic below to work properly, any edits that
7838 // cancel each other out must be combined into one.
7839 while let Some((next_range, next_text)) = lsp_edits.peek() {
7840 if next_range.start.0 > range.end {
7841 if next_range.start.0.row > range.end.row + 1
7842 || next_range.start.0.column > 0
7843 || snapshot.clip_point_utf16(
7844 Unclipped(PointUtf16::new(range.end.row, u32::MAX)),
7845 Bias::Left,
7846 ) > range.end
7847 {
7848 break;
7849 }
7850 new_text.push('\n');
7851 }
7852 range.end = snapshot.clip_point_utf16(next_range.end, Bias::Left);
7853 new_text.push_str(next_text);
7854 lsp_edits.next();
7855 }
7856
7857 // For multiline edits, perform a diff of the old and new text so that
7858 // we can identify the changes more precisely, preserving the locations
7859 // of any anchors positioned in the unchanged regions.
7860 if range.end.row > range.start.row {
7861 let mut offset = range.start.to_offset(&snapshot);
7862 let old_text = snapshot.text_for_range(range).collect::<String>();
7863
7864 let diff = TextDiff::from_lines(old_text.as_str(), &new_text);
7865 let mut moved_since_edit = true;
7866 for change in diff.iter_all_changes() {
7867 let tag = change.tag();
7868 let value = change.value();
7869 match tag {
7870 ChangeTag::Equal => {
7871 offset += value.len();
7872 moved_since_edit = true;
7873 }
7874 ChangeTag::Delete => {
7875 let start = snapshot.anchor_after(offset);
7876 let end = snapshot.anchor_before(offset + value.len());
7877 if moved_since_edit {
7878 edits.push((start..end, String::new()));
7879 } else {
7880 edits.last_mut().unwrap().0.end = end;
7881 }
7882 offset += value.len();
7883 moved_since_edit = false;
7884 }
7885 ChangeTag::Insert => {
7886 if moved_since_edit {
7887 let anchor = snapshot.anchor_after(offset);
7888 edits.push((anchor..anchor, value.to_string()));
7889 } else {
7890 edits.last_mut().unwrap().1.push_str(value);
7891 }
7892 moved_since_edit = false;
7893 }
7894 }
7895 }
7896 } else if range.end == range.start {
7897 let anchor = snapshot.anchor_after(range.start);
7898 edits.push((anchor..anchor, new_text));
7899 } else {
7900 let edit_start = snapshot.anchor_after(range.start);
7901 let edit_end = snapshot.anchor_before(range.end);
7902 edits.push((edit_start..edit_end, new_text));
7903 }
7904 }
7905
7906 Ok(edits)
7907 })
7908 }
7909
7910 fn buffer_snapshot_for_lsp_version(
7911 &mut self,
7912 buffer: &ModelHandle<Buffer>,
7913 server_id: LanguageServerId,
7914 version: Option<i32>,
7915 cx: &AppContext,
7916 ) -> Result<TextBufferSnapshot> {
7917 const OLD_VERSIONS_TO_RETAIN: i32 = 10;
7918
7919 if let Some(version) = version {
7920 let buffer_id = buffer.read(cx).remote_id();
7921 let snapshots = self
7922 .buffer_snapshots
7923 .get_mut(&buffer_id)
7924 .and_then(|m| m.get_mut(&server_id))
7925 .ok_or_else(|| {
7926 anyhow!("no snapshots found for buffer {buffer_id} and server {server_id}")
7927 })?;
7928
7929 let found_snapshot = snapshots
7930 .binary_search_by_key(&version, |e| e.version)
7931 .map(|ix| snapshots[ix].snapshot.clone())
7932 .map_err(|_| {
7933 anyhow!("snapshot not found for buffer {buffer_id} server {server_id} at version {version}")
7934 })?;
7935
7936 snapshots.retain(|snapshot| snapshot.version + OLD_VERSIONS_TO_RETAIN >= version);
7937 Ok(found_snapshot)
7938 } else {
7939 Ok((buffer.read(cx)).text_snapshot())
7940 }
7941 }
7942
7943 pub fn language_servers(
7944 &self,
7945 ) -> impl '_ + Iterator<Item = (LanguageServerId, LanguageServerName, WorktreeId)> {
7946 self.language_server_ids
7947 .iter()
7948 .map(|((worktree_id, server_name), server_id)| {
7949 (*server_id, server_name.clone(), *worktree_id)
7950 })
7951 }
7952
7953 pub fn supplementary_language_servers(
7954 &self,
7955 ) -> impl '_
7956 + Iterator<
7957 Item = (
7958 &LanguageServerId,
7959 &(LanguageServerName, Arc<LanguageServer>),
7960 ),
7961 > {
7962 self.supplementary_language_servers.iter()
7963 }
7964
7965 pub fn language_server_for_id(&self, id: LanguageServerId) -> Option<Arc<LanguageServer>> {
7966 if let Some(LanguageServerState::Running { server, .. }) = self.language_servers.get(&id) {
7967 Some(server.clone())
7968 } else if let Some((_, server)) = self.supplementary_language_servers.get(&id) {
7969 Some(Arc::clone(server))
7970 } else {
7971 None
7972 }
7973 }
7974
7975 pub fn language_servers_for_buffer(
7976 &self,
7977 buffer: &Buffer,
7978 cx: &AppContext,
7979 ) -> impl Iterator<Item = (&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
7980 self.language_server_ids_for_buffer(buffer, cx)
7981 .into_iter()
7982 .filter_map(|server_id| match self.language_servers.get(&server_id)? {
7983 LanguageServerState::Running {
7984 adapter, server, ..
7985 } => Some((adapter, server)),
7986 _ => None,
7987 })
7988 }
7989
7990 fn primary_language_server_for_buffer(
7991 &self,
7992 buffer: &Buffer,
7993 cx: &AppContext,
7994 ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
7995 self.language_servers_for_buffer(buffer, cx).next()
7996 }
7997
7998 pub fn language_server_for_buffer(
7999 &self,
8000 buffer: &Buffer,
8001 server_id: LanguageServerId,
8002 cx: &AppContext,
8003 ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
8004 self.language_servers_for_buffer(buffer, cx)
8005 .find(|(_, s)| s.server_id() == server_id)
8006 }
8007
8008 fn language_server_ids_for_buffer(
8009 &self,
8010 buffer: &Buffer,
8011 cx: &AppContext,
8012 ) -> Vec<LanguageServerId> {
8013 if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language()) {
8014 let worktree_id = file.worktree_id(cx);
8015 language
8016 .lsp_adapters()
8017 .iter()
8018 .flat_map(|adapter| {
8019 let key = (worktree_id, adapter.name.clone());
8020 self.language_server_ids.get(&key).copied()
8021 })
8022 .collect()
8023 } else {
8024 Vec::new()
8025 }
8026 }
8027}
8028
8029fn subscribe_for_copilot_events(
8030 copilot: &ModelHandle<Copilot>,
8031 cx: &mut ModelContext<'_, Project>,
8032) -> gpui::Subscription {
8033 cx.subscribe(
8034 copilot,
8035 |project, copilot, copilot_event, cx| match copilot_event {
8036 copilot::Event::CopilotLanguageServerStarted => {
8037 match copilot.read(cx).language_server() {
8038 Some((name, copilot_server)) => {
8039 // Another event wants to re-add the server that was already added and subscribed to, avoid doing it again.
8040 if !copilot_server.has_notification_handler::<copilot::request::LogMessage>() {
8041 let new_server_id = copilot_server.server_id();
8042 let weak_project = cx.weak_handle();
8043 let copilot_log_subscription = copilot_server
8044 .on_notification::<copilot::request::LogMessage, _>(
8045 move |params, mut cx| {
8046 if let Some(project) = weak_project.upgrade(&mut cx) {
8047 project.update(&mut cx, |_, cx| {
8048 cx.emit(Event::LanguageServerLog(
8049 new_server_id,
8050 params.message,
8051 ));
8052 })
8053 }
8054 },
8055 );
8056 project.supplementary_language_servers.insert(new_server_id, (name.clone(), Arc::clone(copilot_server)));
8057 project.copilot_log_subscription = Some(copilot_log_subscription);
8058 cx.emit(Event::LanguageServerAdded(new_server_id));
8059 }
8060 }
8061 None => debug_panic!("Received Copilot language server started event, but no language server is running"),
8062 }
8063 }
8064 },
8065 )
8066}
8067
8068fn glob_literal_prefix<'a>(glob: &'a str) -> &'a str {
8069 let mut literal_end = 0;
8070 for (i, part) in glob.split(path::MAIN_SEPARATOR).enumerate() {
8071 if part.contains(&['*', '?', '{', '}']) {
8072 break;
8073 } else {
8074 if i > 0 {
8075 // Acount for separator prior to this part
8076 literal_end += path::MAIN_SEPARATOR.len_utf8();
8077 }
8078 literal_end += part.len();
8079 }
8080 }
8081 &glob[..literal_end]
8082}
8083
8084impl WorktreeHandle {
8085 pub fn upgrade(&self, cx: &AppContext) -> Option<ModelHandle<Worktree>> {
8086 match self {
8087 WorktreeHandle::Strong(handle) => Some(handle.clone()),
8088 WorktreeHandle::Weak(handle) => handle.upgrade(cx),
8089 }
8090 }
8091
8092 pub fn handle_id(&self) -> usize {
8093 match self {
8094 WorktreeHandle::Strong(handle) => handle.id(),
8095 WorktreeHandle::Weak(handle) => handle.id(),
8096 }
8097 }
8098}
8099
8100impl OpenBuffer {
8101 pub fn upgrade(&self, cx: &impl BorrowAppContext) -> Option<ModelHandle<Buffer>> {
8102 match self {
8103 OpenBuffer::Strong(handle) => Some(handle.clone()),
8104 OpenBuffer::Weak(handle) => handle.upgrade(cx),
8105 OpenBuffer::Operations(_) => None,
8106 }
8107 }
8108}
8109
8110pub struct PathMatchCandidateSet {
8111 pub snapshot: Snapshot,
8112 pub include_ignored: bool,
8113 pub include_root_name: bool,
8114}
8115
8116impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
8117 type Candidates = PathMatchCandidateSetIter<'a>;
8118
8119 fn id(&self) -> usize {
8120 self.snapshot.id().to_usize()
8121 }
8122
8123 fn len(&self) -> usize {
8124 if self.include_ignored {
8125 self.snapshot.file_count()
8126 } else {
8127 self.snapshot.visible_file_count()
8128 }
8129 }
8130
8131 fn prefix(&self) -> Arc<str> {
8132 if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
8133 self.snapshot.root_name().into()
8134 } else if self.include_root_name {
8135 format!("{}/", self.snapshot.root_name()).into()
8136 } else {
8137 "".into()
8138 }
8139 }
8140
8141 fn candidates(&'a self, start: usize) -> Self::Candidates {
8142 PathMatchCandidateSetIter {
8143 traversal: self.snapshot.files(self.include_ignored, start),
8144 }
8145 }
8146}
8147
8148pub struct PathMatchCandidateSetIter<'a> {
8149 traversal: Traversal<'a>,
8150}
8151
8152impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
8153 type Item = fuzzy::PathMatchCandidate<'a>;
8154
8155 fn next(&mut self) -> Option<Self::Item> {
8156 self.traversal.next().map(|entry| {
8157 if let EntryKind::File(char_bag) = entry.kind {
8158 fuzzy::PathMatchCandidate {
8159 path: &entry.path,
8160 char_bag,
8161 }
8162 } else {
8163 unreachable!()
8164 }
8165 })
8166 }
8167}
8168
8169impl Entity for Project {
8170 type Event = Event;
8171
8172 fn release(&mut self, cx: &mut gpui::AppContext) {
8173 match &self.client_state {
8174 Some(ProjectClientState::Local { .. }) => {
8175 let _ = self.unshare_internal(cx);
8176 }
8177 Some(ProjectClientState::Remote { remote_id, .. }) => {
8178 let _ = self.client.send(proto::LeaveProject {
8179 project_id: *remote_id,
8180 });
8181 self.disconnected_from_host_internal(cx);
8182 }
8183 _ => {}
8184 }
8185 }
8186
8187 fn app_will_quit(
8188 &mut self,
8189 _: &mut AppContext,
8190 ) -> Option<std::pin::Pin<Box<dyn 'static + Future<Output = ()>>>> {
8191 let shutdown_futures = self
8192 .language_servers
8193 .drain()
8194 .map(|(_, server_state)| async {
8195 use LanguageServerState::*;
8196 match server_state {
8197 Running { server, .. } => server.shutdown()?.await,
8198 Starting(task) => task.await?.shutdown()?.await,
8199 }
8200 })
8201 .collect::<Vec<_>>();
8202
8203 Some(
8204 async move {
8205 futures::future::join_all(shutdown_futures).await;
8206 }
8207 .boxed(),
8208 )
8209 }
8210}
8211
8212impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
8213 fn from((worktree_id, path): (WorktreeId, P)) -> Self {
8214 Self {
8215 worktree_id,
8216 path: path.as_ref().into(),
8217 }
8218 }
8219}
8220
8221impl ProjectLspAdapterDelegate {
8222 fn new(project: &Project, cx: &ModelContext<Project>) -> Arc<Self> {
8223 Arc::new(Self {
8224 project: cx.handle(),
8225 http_client: project.client.http_client(),
8226 })
8227 }
8228}
8229
8230impl LspAdapterDelegate for ProjectLspAdapterDelegate {
8231 fn show_notification(&self, message: &str, cx: &mut AppContext) {
8232 self.project
8233 .update(cx, |_, cx| cx.emit(Event::Notification(message.to_owned())));
8234 }
8235
8236 fn http_client(&self) -> Arc<dyn HttpClient> {
8237 self.http_client.clone()
8238 }
8239}
8240
8241fn serialize_symbol(symbol: &Symbol) -> proto::Symbol {
8242 proto::Symbol {
8243 language_server_name: symbol.language_server_name.0.to_string(),
8244 source_worktree_id: symbol.source_worktree_id.to_proto(),
8245 worktree_id: symbol.path.worktree_id.to_proto(),
8246 path: symbol.path.path.to_string_lossy().to_string(),
8247 name: symbol.name.clone(),
8248 kind: unsafe { mem::transmute(symbol.kind) },
8249 start: Some(proto::PointUtf16 {
8250 row: symbol.range.start.0.row,
8251 column: symbol.range.start.0.column,
8252 }),
8253 end: Some(proto::PointUtf16 {
8254 row: symbol.range.end.0.row,
8255 column: symbol.range.end.0.column,
8256 }),
8257 signature: symbol.signature.to_vec(),
8258 }
8259}
8260
8261fn relativize_path(base: &Path, path: &Path) -> PathBuf {
8262 let mut path_components = path.components();
8263 let mut base_components = base.components();
8264 let mut components: Vec<Component> = Vec::new();
8265 loop {
8266 match (path_components.next(), base_components.next()) {
8267 (None, None) => break,
8268 (Some(a), None) => {
8269 components.push(a);
8270 components.extend(path_components.by_ref());
8271 break;
8272 }
8273 (None, _) => components.push(Component::ParentDir),
8274 (Some(a), Some(b)) if components.is_empty() && a == b => (),
8275 (Some(a), Some(b)) if b == Component::CurDir => components.push(a),
8276 (Some(a), Some(_)) => {
8277 components.push(Component::ParentDir);
8278 for _ in base_components {
8279 components.push(Component::ParentDir);
8280 }
8281 components.push(a);
8282 components.extend(path_components.by_ref());
8283 break;
8284 }
8285 }
8286 }
8287 components.iter().map(|c| c.as_os_str()).collect()
8288}
8289
8290impl Item for Buffer {
8291 fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
8292 File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
8293 }
8294
8295 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
8296 File::from_dyn(self.file()).map(|file| ProjectPath {
8297 worktree_id: file.worktree_id(cx),
8298 path: file.path().clone(),
8299 })
8300 }
8301}
8302
8303async fn wait_for_loading_buffer(
8304 mut receiver: postage::watch::Receiver<Option<Result<ModelHandle<Buffer>, Arc<anyhow::Error>>>>,
8305) -> Result<ModelHandle<Buffer>, Arc<anyhow::Error>> {
8306 loop {
8307 if let Some(result) = receiver.borrow().as_ref() {
8308 match result {
8309 Ok(buffer) => return Ok(buffer.to_owned()),
8310 Err(e) => return Err(e.to_owned()),
8311 }
8312 }
8313 receiver.next().await;
8314 }
8315}
8316
8317fn include_text(server: &lsp::LanguageServer) -> bool {
8318 server
8319 .capabilities()
8320 .text_document_sync
8321 .as_ref()
8322 .and_then(|sync| match sync {
8323 lsp::TextDocumentSyncCapability::Kind(_) => None,
8324 lsp::TextDocumentSyncCapability::Options(options) => options.save.as_ref(),
8325 })
8326 .and_then(|save_options| match save_options {
8327 lsp::TextDocumentSyncSaveOptions::Supported(_) => None,
8328 lsp::TextDocumentSyncSaveOptions::SaveOptions(options) => options.include_text,
8329 })
8330 .unwrap_or(false)
8331}