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