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