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