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