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