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