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