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