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