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