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