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