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