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