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