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