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