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