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