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