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