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