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