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