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