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