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