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