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