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