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