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 server
2703 .notify::<lsp::notification::DidSaveTextDocument>(
2704 lsp::DidSaveTextDocumentParams {
2705 text_document: text_document.clone(),
2706 text,
2707 },
2708 )
2709 .log_err();
2710 }
2711
2712 for language_server_id in self.language_server_ids_for_buffer(buffer.read(cx), cx) {
2713 self.simulate_disk_based_diagnostics_events_if_needed(language_server_id, cx);
2714 }
2715 }
2716 BufferEvent::FileHandleChanged => {
2717 let Some(file) = File::from_dyn(buffer.read(cx).file()) else {
2718 return None;
2719 };
2720
2721 let remote_id = buffer.read(cx).remote_id();
2722 if let Some(entry_id) = file.entry_id {
2723 match self.local_buffer_ids_by_entry_id.get(&entry_id) {
2724 Some(_) => {
2725 return None;
2726 }
2727 None => {
2728 self.local_buffer_ids_by_entry_id
2729 .insert(entry_id, remote_id);
2730 }
2731 }
2732 };
2733 self.local_buffer_ids_by_path.insert(
2734 ProjectPath {
2735 worktree_id: file.worktree_id(cx),
2736 path: file.path.clone(),
2737 },
2738 remote_id,
2739 );
2740 }
2741 _ => {}
2742 }
2743
2744 None
2745 }
2746
2747 // After saving a buffer using a language server that doesn't provide a disk-based progress token,
2748 // kick off a timer that will reset every time the buffer is saved. If the timer eventually fires,
2749 // simulate disk-based diagnostics being finished so that other pieces of UI (e.g., project
2750 // diagnostics view, diagnostic status bar) can update. We don't emit an event right away because
2751 // the language server might take some time to publish diagnostics.
2752 fn simulate_disk_based_diagnostics_events_if_needed(
2753 &mut self,
2754 language_server_id: LanguageServerId,
2755 cx: &mut ModelContext<Self>,
2756 ) {
2757 const DISK_BASED_DIAGNOSTICS_DEBOUNCE: Duration = Duration::from_secs(1);
2758
2759 let Some(LanguageServerState::Running {
2760 simulate_disk_based_diagnostics_completion,
2761 adapter,
2762 ..
2763 }) = self.language_servers.get_mut(&language_server_id)
2764 else {
2765 return;
2766 };
2767
2768 if adapter.disk_based_diagnostics_progress_token.is_some() {
2769 return;
2770 }
2771
2772 let prev_task = simulate_disk_based_diagnostics_completion.replace(cx.spawn(
2773 move |this, mut cx| async move {
2774 cx.background_executor()
2775 .timer(DISK_BASED_DIAGNOSTICS_DEBOUNCE)
2776 .await;
2777
2778 this.update(&mut cx, |this, cx| {
2779 this.disk_based_diagnostics_finished(language_server_id, cx);
2780
2781 if let Some(LanguageServerState::Running {
2782 simulate_disk_based_diagnostics_completion,
2783 ..
2784 }) = this.language_servers.get_mut(&language_server_id)
2785 {
2786 *simulate_disk_based_diagnostics_completion = None;
2787 }
2788 })
2789 .ok();
2790 },
2791 ));
2792
2793 if prev_task.is_none() {
2794 self.disk_based_diagnostics_started(language_server_id, cx);
2795 }
2796 }
2797
2798 fn request_buffer_diff_recalculation(
2799 &mut self,
2800 buffer: &Model<Buffer>,
2801 cx: &mut ModelContext<Self>,
2802 ) {
2803 self.buffers_needing_diff.insert(buffer.downgrade());
2804 let first_insertion = self.buffers_needing_diff.len() == 1;
2805
2806 let settings = ProjectSettings::get_global(cx);
2807 let delay = if let Some(delay) = settings.git.gutter_debounce {
2808 delay
2809 } else {
2810 if first_insertion {
2811 let this = cx.weak_model();
2812 cx.defer(move |cx| {
2813 if let Some(this) = this.upgrade() {
2814 this.update(cx, |this, cx| {
2815 this.recalculate_buffer_diffs(cx).detach();
2816 });
2817 }
2818 });
2819 }
2820 return;
2821 };
2822
2823 const MIN_DELAY: u64 = 50;
2824 let delay = delay.max(MIN_DELAY);
2825 let duration = Duration::from_millis(delay);
2826
2827 self.git_diff_debouncer
2828 .fire_new(duration, cx, move |this, cx| {
2829 this.recalculate_buffer_diffs(cx)
2830 });
2831 }
2832
2833 fn recalculate_buffer_diffs(&mut self, cx: &mut ModelContext<Self>) -> Task<()> {
2834 let buffers = self.buffers_needing_diff.drain().collect::<Vec<_>>();
2835 cx.spawn(move |this, mut cx| async move {
2836 let tasks: Vec<_> = buffers
2837 .iter()
2838 .filter_map(|buffer| {
2839 let buffer = buffer.upgrade()?;
2840 buffer
2841 .update(&mut cx, |buffer, cx| buffer.git_diff_recalc(cx))
2842 .ok()
2843 .flatten()
2844 })
2845 .collect();
2846
2847 futures::future::join_all(tasks).await;
2848
2849 this.update(&mut cx, |this, cx| {
2850 if this.buffers_needing_diff.is_empty() {
2851 // TODO: Would a `ModelContext<Project>.notify()` suffice here?
2852 for buffer in buffers {
2853 if let Some(buffer) = buffer.upgrade() {
2854 buffer.update(cx, |_, cx| cx.notify());
2855 }
2856 }
2857 } else {
2858 this.recalculate_buffer_diffs(cx).detach();
2859 }
2860 })
2861 .ok();
2862 })
2863 }
2864
2865 fn language_servers_for_worktree(
2866 &self,
2867 worktree_id: WorktreeId,
2868 ) -> impl Iterator<Item = (&Arc<CachedLspAdapter>, &Arc<Language>, &Arc<LanguageServer>)> {
2869 self.language_server_ids
2870 .iter()
2871 .filter_map(move |((language_server_worktree_id, _), id)| {
2872 if *language_server_worktree_id == worktree_id {
2873 if let Some(LanguageServerState::Running {
2874 adapter,
2875 language,
2876 server,
2877 ..
2878 }) = self.language_servers.get(id)
2879 {
2880 return Some((adapter, language, server));
2881 }
2882 }
2883 None
2884 })
2885 }
2886
2887 fn maintain_buffer_languages(
2888 languages: Arc<LanguageRegistry>,
2889 cx: &mut ModelContext<Project>,
2890 ) -> Task<()> {
2891 let mut subscription = languages.subscribe();
2892 let mut prev_reload_count = languages.reload_count();
2893 cx.spawn(move |project, mut cx| async move {
2894 while let Some(()) = subscription.next().await {
2895 if let Some(project) = project.upgrade() {
2896 // If the language registry has been reloaded, then remove and
2897 // re-assign the languages on all open buffers.
2898 let reload_count = languages.reload_count();
2899 if reload_count > prev_reload_count {
2900 prev_reload_count = reload_count;
2901 project
2902 .update(&mut cx, |this, cx| {
2903 let buffers = this
2904 .opened_buffers
2905 .values()
2906 .filter_map(|b| b.upgrade())
2907 .collect::<Vec<_>>();
2908 for buffer in buffers {
2909 if let Some(f) = File::from_dyn(buffer.read(cx).file()).cloned()
2910 {
2911 this.unregister_buffer_from_language_servers(
2912 &buffer, &f, cx,
2913 );
2914 buffer
2915 .update(cx, |buffer, cx| buffer.set_language(None, cx));
2916 }
2917 }
2918 })
2919 .ok();
2920 }
2921
2922 project
2923 .update(&mut cx, |project, cx| {
2924 let mut plain_text_buffers = Vec::new();
2925 let mut buffers_with_unknown_injections = Vec::new();
2926 for buffer in project.opened_buffers.values() {
2927 if let Some(handle) = buffer.upgrade() {
2928 let buffer = &handle.read(cx);
2929 if buffer.language().is_none()
2930 || buffer.language() == Some(&*language::PLAIN_TEXT)
2931 {
2932 plain_text_buffers.push(handle);
2933 } else if buffer.contains_unknown_injections() {
2934 buffers_with_unknown_injections.push(handle);
2935 }
2936 }
2937 }
2938
2939 for buffer in plain_text_buffers {
2940 project.detect_language_for_buffer(&buffer, cx);
2941 project.register_buffer_with_language_servers(&buffer, cx);
2942 }
2943
2944 for buffer in buffers_with_unknown_injections {
2945 buffer.update(cx, |buffer, cx| buffer.reparse(cx));
2946 }
2947 })
2948 .ok();
2949 }
2950 }
2951 })
2952 }
2953
2954 fn maintain_workspace_config(cx: &mut ModelContext<Project>) -> Task<Result<()>> {
2955 let (mut settings_changed_tx, mut settings_changed_rx) = watch::channel();
2956 let _ = postage::stream::Stream::try_recv(&mut settings_changed_rx);
2957
2958 let settings_observation = cx.observe_global::<SettingsStore>(move |_, _| {
2959 *settings_changed_tx.borrow_mut() = ();
2960 });
2961
2962 cx.spawn(move |this, mut cx| async move {
2963 while let Some(()) = settings_changed_rx.next().await {
2964 let servers = this.update(&mut cx, |this, cx| {
2965 this.language_server_ids
2966 .iter()
2967 .filter_map(|((worktree_id, _), server_id)| {
2968 let worktree = this.worktree_for_id(*worktree_id, cx)?;
2969 let state = this.language_servers.get(server_id)?;
2970 let delegate = ProjectLspAdapterDelegate::new(this, &worktree, cx);
2971 match state {
2972 LanguageServerState::Starting(_) => None,
2973 LanguageServerState::Running {
2974 adapter, server, ..
2975 } => Some((
2976 adapter.adapter.clone(),
2977 server.clone(),
2978 delegate as Arc<dyn LspAdapterDelegate>,
2979 )),
2980 }
2981 })
2982 .collect::<Vec<_>>()
2983 })?;
2984
2985 for (adapter, server, delegate) in servers {
2986 let settings = adapter.workspace_configuration(&delegate, &mut cx).await?;
2987
2988 server
2989 .notify::<lsp::notification::DidChangeConfiguration>(
2990 lsp::DidChangeConfigurationParams { settings },
2991 )
2992 .ok();
2993 }
2994 }
2995
2996 drop(settings_observation);
2997 anyhow::Ok(())
2998 })
2999 }
3000
3001 fn detect_language_for_buffer(
3002 &mut self,
3003 buffer_handle: &Model<Buffer>,
3004 cx: &mut ModelContext<Self>,
3005 ) {
3006 // If the buffer has a language, set it and start the language server if we haven't already.
3007 let buffer = buffer_handle.read(cx);
3008 let Some(file) = buffer.file() else {
3009 return;
3010 };
3011 let content = buffer.as_rope();
3012 let Some(new_language_result) = self
3013 .languages
3014 .language_for_file(file, Some(content), cx)
3015 .now_or_never()
3016 else {
3017 return;
3018 };
3019
3020 match new_language_result {
3021 Err(e) => {
3022 if e.is::<language::LanguageNotFound>() {
3023 cx.emit(Event::LanguageNotFound(buffer_handle.clone()))
3024 }
3025 }
3026 Ok(new_language) => {
3027 self.set_language_for_buffer(buffer_handle, new_language, cx);
3028 }
3029 };
3030 }
3031
3032 pub fn set_language_for_buffer(
3033 &mut self,
3034 buffer: &Model<Buffer>,
3035 new_language: Arc<Language>,
3036 cx: &mut ModelContext<Self>,
3037 ) {
3038 buffer.update(cx, |buffer, cx| {
3039 if buffer.language().map_or(true, |old_language| {
3040 !Arc::ptr_eq(old_language, &new_language)
3041 }) {
3042 buffer.set_language(Some(new_language.clone()), cx);
3043 }
3044 });
3045
3046 let buffer_file = buffer.read(cx).file().cloned();
3047 let settings = language_settings(Some(&new_language), buffer_file.as_ref(), cx).clone();
3048 let buffer_file = File::from_dyn(buffer_file.as_ref());
3049 let worktree = buffer_file.as_ref().map(|f| f.worktree_id(cx));
3050 if let Some(prettier_plugins) =
3051 prettier_support::prettier_plugins_for_language(&new_language, &settings)
3052 {
3053 self.install_default_prettier(worktree, prettier_plugins.iter().cloned(), cx);
3054 };
3055 if let Some(file) = buffer_file {
3056 let worktree = file.worktree.clone();
3057 if worktree.read(cx).is_local() {
3058 self.start_language_servers(&worktree, new_language, cx);
3059 }
3060 }
3061 }
3062
3063 fn start_language_servers(
3064 &mut self,
3065 worktree: &Model<Worktree>,
3066 language: Arc<Language>,
3067 cx: &mut ModelContext<Self>,
3068 ) {
3069 let root_file = worktree.update(cx, |tree, cx| tree.root_file(cx));
3070 let settings = language_settings(Some(&language), root_file.map(|f| f as _).as_ref(), cx);
3071 if !settings.enable_language_server {
3072 return;
3073 }
3074
3075 let available_lsp_adapters = self.languages.clone().lsp_adapters(&language);
3076 let available_language_servers = available_lsp_adapters
3077 .iter()
3078 .map(|lsp_adapter| lsp_adapter.name.clone())
3079 .collect::<Vec<_>>();
3080
3081 let desired_language_servers =
3082 settings.customized_language_servers(&available_language_servers);
3083
3084 let mut enabled_lsp_adapters: Vec<Arc<CachedLspAdapter>> = Vec::new();
3085 for desired_language_server in desired_language_servers {
3086 if let Some(adapter) = available_lsp_adapters
3087 .iter()
3088 .find(|adapter| adapter.name == desired_language_server)
3089 {
3090 enabled_lsp_adapters.push(adapter.clone());
3091 continue;
3092 }
3093
3094 if let Some(adapter) = self
3095 .languages
3096 .load_available_lsp_adapter(&desired_language_server)
3097 {
3098 self.languages()
3099 .register_lsp_adapter(language.name(), adapter.adapter.clone());
3100 enabled_lsp_adapters.push(adapter);
3101 continue;
3102 }
3103
3104 log::warn!(
3105 "no language server found matching '{}'",
3106 desired_language_server.0
3107 );
3108 }
3109
3110 log::info!(
3111 "starting language servers for {language}: {adapters}",
3112 language = language.name(),
3113 adapters = enabled_lsp_adapters
3114 .iter()
3115 .map(|adapter| adapter.name.0.as_ref())
3116 .join(", ")
3117 );
3118
3119 for adapter in enabled_lsp_adapters {
3120 self.start_language_server(worktree, adapter, language.clone(), cx);
3121 }
3122 }
3123
3124 fn start_language_server(
3125 &mut self,
3126 worktree_handle: &Model<Worktree>,
3127 adapter: Arc<CachedLspAdapter>,
3128 language: Arc<Language>,
3129 cx: &mut ModelContext<Self>,
3130 ) {
3131 if adapter.reinstall_attempt_count.load(SeqCst) > MAX_SERVER_REINSTALL_ATTEMPT_COUNT {
3132 return;
3133 }
3134
3135 let worktree = worktree_handle.read(cx);
3136 let worktree_id = worktree.id();
3137 let worktree_path = worktree.abs_path();
3138 let key = (worktree_id, adapter.name.clone());
3139 if self.language_server_ids.contains_key(&key) {
3140 return;
3141 }
3142
3143 let stderr_capture = Arc::new(Mutex::new(Some(String::new())));
3144 let lsp_adapter_delegate = ProjectLspAdapterDelegate::new(self, worktree_handle, cx);
3145 let pending_server = match self.languages.create_pending_language_server(
3146 stderr_capture.clone(),
3147 language.clone(),
3148 adapter.clone(),
3149 Arc::clone(&worktree_path),
3150 lsp_adapter_delegate.clone(),
3151 cx,
3152 ) {
3153 Some(pending_server) => pending_server,
3154 None => return,
3155 };
3156
3157 let project_settings = ProjectSettings::get(
3158 Some(SettingsLocation {
3159 worktree_id: worktree_id.to_proto() as usize,
3160 path: Path::new(""),
3161 }),
3162 cx,
3163 );
3164 let lsp = project_settings.lsp.get(&adapter.name.0);
3165 let override_options = lsp.and_then(|s| s.initialization_options.clone());
3166
3167 let server_id = pending_server.server_id;
3168 let container_dir = pending_server.container_dir.clone();
3169 let state = LanguageServerState::Starting({
3170 let adapter = adapter.clone();
3171 let server_name = adapter.name.0.clone();
3172 let language = language.clone();
3173 let key = key.clone();
3174
3175 cx.spawn(move |this, mut cx| async move {
3176 let result = Self::setup_and_insert_language_server(
3177 this.clone(),
3178 lsp_adapter_delegate,
3179 override_options,
3180 pending_server,
3181 adapter.clone(),
3182 language.clone(),
3183 server_id,
3184 key,
3185 &mut cx,
3186 )
3187 .await;
3188
3189 match result {
3190 Ok(server) => {
3191 stderr_capture.lock().take();
3192 server
3193 }
3194
3195 Err(err) => {
3196 log::error!("failed to start language server {server_name:?}: {err}");
3197 log::error!("server stderr: {:?}", stderr_capture.lock().take());
3198
3199 let this = this.upgrade()?;
3200 let container_dir = container_dir?;
3201
3202 let attempt_count = adapter.reinstall_attempt_count.fetch_add(1, SeqCst);
3203 if attempt_count >= MAX_SERVER_REINSTALL_ATTEMPT_COUNT {
3204 let max = MAX_SERVER_REINSTALL_ATTEMPT_COUNT;
3205 log::error!("Hit {max} reinstallation attempts for {server_name:?}");
3206 return None;
3207 }
3208
3209 log::info!(
3210 "retrying installation of language server {server_name:?} in {}s",
3211 SERVER_REINSTALL_DEBOUNCE_TIMEOUT.as_secs()
3212 );
3213 cx.background_executor()
3214 .timer(SERVER_REINSTALL_DEBOUNCE_TIMEOUT)
3215 .await;
3216
3217 let installation_test_binary = adapter
3218 .installation_test_binary(container_dir.to_path_buf())
3219 .await;
3220
3221 this.update(&mut cx, |_, cx| {
3222 Self::check_errored_server(
3223 language,
3224 adapter,
3225 server_id,
3226 installation_test_binary,
3227 cx,
3228 )
3229 })
3230 .ok();
3231
3232 None
3233 }
3234 }
3235 })
3236 });
3237
3238 self.language_servers.insert(server_id, state);
3239 self.language_server_ids.insert(key, server_id);
3240 }
3241
3242 fn reinstall_language_server(
3243 &mut self,
3244 language: Arc<Language>,
3245 adapter: Arc<CachedLspAdapter>,
3246 server_id: LanguageServerId,
3247 cx: &mut ModelContext<Self>,
3248 ) -> Option<Task<()>> {
3249 log::info!("beginning to reinstall server");
3250
3251 let existing_server = match self.language_servers.remove(&server_id) {
3252 Some(LanguageServerState::Running { server, .. }) => Some(server),
3253 _ => None,
3254 };
3255
3256 for worktree in &self.worktrees {
3257 if let Some(worktree) = worktree.upgrade() {
3258 let key = (worktree.read(cx).id(), adapter.name.clone());
3259 self.language_server_ids.remove(&key);
3260 }
3261 }
3262
3263 Some(cx.spawn(move |this, mut cx| async move {
3264 if let Some(task) = existing_server.and_then(|server| server.shutdown()) {
3265 log::info!("shutting down existing server");
3266 task.await;
3267 }
3268
3269 // TODO: This is race-safe with regards to preventing new instances from
3270 // starting while deleting, but existing instances in other projects are going
3271 // to be very confused and messed up
3272 let Some(task) = this
3273 .update(&mut cx, |this, cx| {
3274 this.languages.delete_server_container(adapter.clone(), cx)
3275 })
3276 .log_err()
3277 else {
3278 return;
3279 };
3280 task.await;
3281
3282 this.update(&mut cx, |this, cx| {
3283 let worktrees = this.worktrees.clone();
3284 for worktree in worktrees {
3285 if let Some(worktree) = worktree.upgrade() {
3286 this.start_language_server(
3287 &worktree,
3288 adapter.clone(),
3289 language.clone(),
3290 cx,
3291 );
3292 }
3293 }
3294 })
3295 .ok();
3296 }))
3297 }
3298
3299 #[allow(clippy::too_many_arguments)]
3300 async fn setup_and_insert_language_server(
3301 this: WeakModel<Self>,
3302 delegate: Arc<dyn LspAdapterDelegate>,
3303 override_initialization_options: Option<serde_json::Value>,
3304 pending_server: PendingLanguageServer,
3305 adapter: Arc<CachedLspAdapter>,
3306 language: Arc<Language>,
3307 server_id: LanguageServerId,
3308 key: (WorktreeId, LanguageServerName),
3309 cx: &mut AsyncAppContext,
3310 ) -> Result<Option<Arc<LanguageServer>>> {
3311 let language_server = Self::setup_pending_language_server(
3312 this.clone(),
3313 override_initialization_options,
3314 pending_server,
3315 delegate,
3316 adapter.clone(),
3317 server_id,
3318 cx,
3319 )
3320 .await?;
3321
3322 let this = match this.upgrade() {
3323 Some(this) => this,
3324 None => return Err(anyhow!("failed to upgrade project handle")),
3325 };
3326
3327 this.update(cx, |this, cx| {
3328 this.insert_newly_running_language_server(
3329 language,
3330 adapter,
3331 language_server.clone(),
3332 server_id,
3333 key,
3334 cx,
3335 )
3336 })??;
3337
3338 Ok(Some(language_server))
3339 }
3340
3341 async fn setup_pending_language_server(
3342 this: WeakModel<Self>,
3343 override_options: Option<serde_json::Value>,
3344 pending_server: PendingLanguageServer,
3345 delegate: Arc<dyn LspAdapterDelegate>,
3346 adapter: Arc<CachedLspAdapter>,
3347 server_id: LanguageServerId,
3348 cx: &mut AsyncAppContext,
3349 ) -> Result<Arc<LanguageServer>> {
3350 let workspace_config = adapter
3351 .adapter
3352 .clone()
3353 .workspace_configuration(&delegate, cx)
3354 .await?;
3355 let (language_server, mut initialization_options) = pending_server.task.await?;
3356
3357 let name = language_server.name();
3358 language_server
3359 .on_notification::<lsp::notification::PublishDiagnostics, _>({
3360 let adapter = adapter.clone();
3361 let this = this.clone();
3362 move |mut params, mut cx| {
3363 let adapter = adapter.clone();
3364 if let Some(this) = this.upgrade() {
3365 adapter.process_diagnostics(&mut params);
3366 this.update(&mut cx, |this, cx| {
3367 this.update_diagnostics(
3368 server_id,
3369 params,
3370 &adapter.disk_based_diagnostic_sources,
3371 cx,
3372 )
3373 .log_err();
3374 })
3375 .ok();
3376 }
3377 }
3378 })
3379 .detach();
3380
3381 language_server
3382 .on_request::<lsp::request::WorkspaceConfiguration, _, _>({
3383 let adapter = adapter.adapter.clone();
3384 let delegate = delegate.clone();
3385 move |params, mut cx| {
3386 let adapter = adapter.clone();
3387 let delegate = delegate.clone();
3388 async move {
3389 let workspace_config =
3390 adapter.workspace_configuration(&delegate, &mut cx).await?;
3391 Ok(params
3392 .items
3393 .into_iter()
3394 .map(|item| {
3395 if let Some(section) = &item.section {
3396 workspace_config
3397 .get(section)
3398 .cloned()
3399 .unwrap_or(serde_json::Value::Null)
3400 } else {
3401 workspace_config.clone()
3402 }
3403 })
3404 .collect())
3405 }
3406 }
3407 })
3408 .detach();
3409
3410 // Even though we don't have handling for these requests, respond to them to
3411 // avoid stalling any language server like `gopls` which waits for a response
3412 // to these requests when initializing.
3413 language_server
3414 .on_request::<lsp::request::WorkDoneProgressCreate, _, _>({
3415 let this = this.clone();
3416 move |params, mut cx| {
3417 let this = this.clone();
3418 async move {
3419 this.update(&mut cx, |this, _| {
3420 if let Some(status) = this.language_server_statuses.get_mut(&server_id)
3421 {
3422 if let lsp::NumberOrString::String(token) = params.token {
3423 status.progress_tokens.insert(token);
3424 }
3425 }
3426 })?;
3427
3428 Ok(())
3429 }
3430 }
3431 })
3432 .detach();
3433
3434 language_server
3435 .on_request::<lsp::request::RegisterCapability, _, _>({
3436 let this = this.clone();
3437 move |params, mut cx| {
3438 let this = this.clone();
3439 async move {
3440 for reg in params.registrations {
3441 if reg.method == "workspace/didChangeWatchedFiles" {
3442 if let Some(options) = reg.register_options {
3443 let options = serde_json::from_value(options)?;
3444 this.update(&mut cx, |this, cx| {
3445 this.on_lsp_did_change_watched_files(
3446 server_id, options, cx,
3447 );
3448 })?;
3449 }
3450 }
3451 }
3452 Ok(())
3453 }
3454 }
3455 })
3456 .detach();
3457
3458 language_server
3459 .on_request::<lsp::request::ApplyWorkspaceEdit, _, _>({
3460 let adapter = adapter.clone();
3461 let this = this.clone();
3462 move |params, cx| {
3463 Self::on_lsp_workspace_edit(
3464 this.clone(),
3465 params,
3466 server_id,
3467 adapter.clone(),
3468 cx,
3469 )
3470 }
3471 })
3472 .detach();
3473
3474 language_server
3475 .on_request::<lsp::request::InlayHintRefreshRequest, _, _>({
3476 let this = this.clone();
3477 move |(), mut cx| {
3478 let this = this.clone();
3479 async move {
3480 this.update(&mut cx, |project, cx| {
3481 cx.emit(Event::RefreshInlayHints);
3482 project.remote_id().map(|project_id| {
3483 project.client.send(proto::RefreshInlayHints { project_id })
3484 })
3485 })?
3486 .transpose()?;
3487 Ok(())
3488 }
3489 }
3490 })
3491 .detach();
3492
3493 language_server
3494 .on_request::<lsp::request::ShowMessageRequest, _, _>({
3495 let this = this.clone();
3496 let name = name.to_string();
3497 move |params, mut cx| {
3498 let this = this.clone();
3499 let name = name.to_string();
3500 async move {
3501 if let Some(actions) = params.actions {
3502 let (tx, mut rx) = smol::channel::bounded(1);
3503 let request = LanguageServerPromptRequest {
3504 level: match params.typ {
3505 lsp::MessageType::ERROR => PromptLevel::Critical,
3506 lsp::MessageType::WARNING => PromptLevel::Warning,
3507 _ => PromptLevel::Info,
3508 },
3509 message: params.message,
3510 actions,
3511 response_channel: tx,
3512 lsp_name: name.clone(),
3513 };
3514
3515 if let Ok(_) = this.update(&mut cx, |_, cx| {
3516 cx.emit(Event::LanguageServerPrompt(request));
3517 }) {
3518 let response = rx.next().await;
3519
3520 Ok(response)
3521 } else {
3522 Ok(None)
3523 }
3524 } else {
3525 Ok(None)
3526 }
3527 }
3528 }
3529 })
3530 .detach();
3531
3532 let disk_based_diagnostics_progress_token =
3533 adapter.disk_based_diagnostics_progress_token.clone();
3534
3535 language_server
3536 .on_notification::<ServerStatus, _>({
3537 let this = this.clone();
3538 let name = name.to_string();
3539 move |params, mut cx| {
3540 let this = this.clone();
3541 let name = name.to_string();
3542 if let Some(ref message) = params.message {
3543 let message = message.trim();
3544 if !message.is_empty() {
3545 let formatted_message = format!(
3546 "Language server {name} (id {server_id}) status update: {message}"
3547 );
3548 match params.health {
3549 ServerHealthStatus::Ok => log::info!("{}", formatted_message),
3550 ServerHealthStatus::Warning => log::warn!("{}", formatted_message),
3551 ServerHealthStatus::Error => {
3552 log::error!("{}", formatted_message);
3553 let (tx, _rx) = smol::channel::bounded(1);
3554 let request = LanguageServerPromptRequest {
3555 level: PromptLevel::Critical,
3556 message: params.message.unwrap_or_default(),
3557 actions: Vec::new(),
3558 response_channel: tx,
3559 lsp_name: name.clone(),
3560 };
3561 let _ = this
3562 .update(&mut cx, |_, cx| {
3563 cx.emit(Event::LanguageServerPrompt(request));
3564 })
3565 .ok();
3566 }
3567 ServerHealthStatus::Other(status) => {
3568 log::info!(
3569 "Unknown server health: {status}\n{formatted_message}"
3570 )
3571 }
3572 }
3573 }
3574 }
3575 }
3576 })
3577 .detach();
3578
3579 language_server
3580 .on_notification::<lsp::notification::Progress, _>(move |params, mut cx| {
3581 if let Some(this) = this.upgrade() {
3582 this.update(&mut cx, |this, cx| {
3583 this.on_lsp_progress(
3584 params,
3585 server_id,
3586 disk_based_diagnostics_progress_token.clone(),
3587 cx,
3588 );
3589 })
3590 .ok();
3591 }
3592 })
3593 .detach();
3594
3595 match (&mut initialization_options, override_options) {
3596 (Some(initialization_options), Some(override_options)) => {
3597 merge_json_value_into(override_options, initialization_options);
3598 }
3599 (None, override_options) => initialization_options = override_options,
3600 _ => {}
3601 }
3602 let language_server = cx
3603 .update(|cx| language_server.initialize(initialization_options, cx))?
3604 .await?;
3605
3606 language_server
3607 .notify::<lsp::notification::DidChangeConfiguration>(
3608 lsp::DidChangeConfigurationParams {
3609 settings: workspace_config,
3610 },
3611 )
3612 .ok();
3613
3614 Ok(language_server)
3615 }
3616
3617 fn insert_newly_running_language_server(
3618 &mut self,
3619 language: Arc<Language>,
3620 adapter: Arc<CachedLspAdapter>,
3621 language_server: Arc<LanguageServer>,
3622 server_id: LanguageServerId,
3623 key: (WorktreeId, LanguageServerName),
3624 cx: &mut ModelContext<Self>,
3625 ) -> Result<()> {
3626 // If the language server for this key doesn't match the server id, don't store the
3627 // server. Which will cause it to be dropped, killing the process
3628 if self
3629 .language_server_ids
3630 .get(&key)
3631 .map(|id| id != &server_id)
3632 .unwrap_or(false)
3633 {
3634 return Ok(());
3635 }
3636
3637 // Update language_servers collection with Running variant of LanguageServerState
3638 // indicating that the server is up and running and ready
3639 self.language_servers.insert(
3640 server_id,
3641 LanguageServerState::Running {
3642 adapter: adapter.clone(),
3643 language: language.clone(),
3644 server: language_server.clone(),
3645 simulate_disk_based_diagnostics_completion: None,
3646 },
3647 );
3648
3649 self.language_server_statuses.insert(
3650 server_id,
3651 LanguageServerStatus {
3652 name: language_server.name().to_string(),
3653 pending_work: Default::default(),
3654 has_pending_diagnostic_updates: false,
3655 progress_tokens: Default::default(),
3656 },
3657 );
3658
3659 cx.emit(Event::LanguageServerAdded(server_id));
3660
3661 if let Some(project_id) = self.remote_id() {
3662 self.client.send(proto::StartLanguageServer {
3663 project_id,
3664 server: Some(proto::LanguageServer {
3665 id: server_id.0 as u64,
3666 name: language_server.name().to_string(),
3667 }),
3668 })?;
3669 }
3670
3671 // Tell the language server about every open buffer in the worktree that matches the language.
3672 for buffer in self.opened_buffers.values() {
3673 if let Some(buffer_handle) = buffer.upgrade() {
3674 let buffer = buffer_handle.read(cx);
3675 let file = match File::from_dyn(buffer.file()) {
3676 Some(file) => file,
3677 None => continue,
3678 };
3679 let language = match buffer.language() {
3680 Some(language) => language,
3681 None => continue,
3682 };
3683
3684 if file.worktree.read(cx).id() != key.0
3685 || !self
3686 .languages
3687 .lsp_adapters(&language)
3688 .iter()
3689 .any(|a| a.name == key.1)
3690 {
3691 continue;
3692 }
3693
3694 let file = match file.as_local() {
3695 Some(file) => file,
3696 None => continue,
3697 };
3698
3699 let versions = self
3700 .buffer_snapshots
3701 .entry(buffer.remote_id())
3702 .or_default()
3703 .entry(server_id)
3704 .or_insert_with(|| {
3705 vec![LspBufferSnapshot {
3706 version: 0,
3707 snapshot: buffer.text_snapshot(),
3708 }]
3709 });
3710
3711 let snapshot = versions.last().unwrap();
3712 let version = snapshot.version;
3713 let initial_snapshot = &snapshot.snapshot;
3714 let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
3715 language_server.notify::<lsp::notification::DidOpenTextDocument>(
3716 lsp::DidOpenTextDocumentParams {
3717 text_document: lsp::TextDocumentItem::new(
3718 uri,
3719 adapter
3720 .language_ids
3721 .get(language.name().as_ref())
3722 .cloned()
3723 .unwrap_or_default(),
3724 version,
3725 initial_snapshot.text(),
3726 ),
3727 },
3728 )?;
3729
3730 buffer_handle.update(cx, |buffer, cx| {
3731 buffer.set_completion_triggers(
3732 language_server
3733 .capabilities()
3734 .completion_provider
3735 .as_ref()
3736 .and_then(|provider| provider.trigger_characters.clone())
3737 .unwrap_or_default(),
3738 cx,
3739 )
3740 });
3741 }
3742 }
3743
3744 cx.notify();
3745 Ok(())
3746 }
3747
3748 // Returns a list of all of the worktrees which no longer have a language server and the root path
3749 // for the stopped server
3750 fn stop_language_server(
3751 &mut self,
3752 worktree_id: WorktreeId,
3753 adapter_name: LanguageServerName,
3754 cx: &mut ModelContext<Self>,
3755 ) -> Task<Vec<WorktreeId>> {
3756 let key = (worktree_id, adapter_name);
3757 if let Some(server_id) = self.language_server_ids.remove(&key) {
3758 let name = key.1 .0;
3759 log::info!("stopping language server {name}");
3760
3761 // Remove other entries for this language server as well
3762 let mut orphaned_worktrees = vec![worktree_id];
3763 let other_keys = self.language_server_ids.keys().cloned().collect::<Vec<_>>();
3764 for other_key in other_keys {
3765 if self.language_server_ids.get(&other_key) == Some(&server_id) {
3766 self.language_server_ids.remove(&other_key);
3767 orphaned_worktrees.push(other_key.0);
3768 }
3769 }
3770
3771 for buffer in self.opened_buffers.values() {
3772 if let Some(buffer) = buffer.upgrade() {
3773 buffer.update(cx, |buffer, cx| {
3774 buffer.update_diagnostics(server_id, Default::default(), cx);
3775 });
3776 }
3777 }
3778 for worktree in &self.worktrees {
3779 if let Some(worktree) = worktree.upgrade() {
3780 worktree.update(cx, |worktree, cx| {
3781 if let Some(worktree) = worktree.as_local_mut() {
3782 worktree.clear_diagnostics_for_language_server(server_id, cx);
3783 }
3784 });
3785 }
3786 }
3787
3788 self.language_server_watched_paths.remove(&server_id);
3789 self.language_server_statuses.remove(&server_id);
3790 cx.notify();
3791
3792 let server_state = self.language_servers.remove(&server_id);
3793 cx.emit(Event::LanguageServerRemoved(server_id));
3794 cx.spawn(move |_, cx| async move {
3795 Self::shutdown_language_server(server_state, name, cx).await;
3796 orphaned_worktrees
3797 })
3798 } else {
3799 Task::ready(Vec::new())
3800 }
3801 }
3802
3803 async fn shutdown_language_server(
3804 server_state: Option<LanguageServerState>,
3805 name: Arc<str>,
3806 cx: AsyncAppContext,
3807 ) {
3808 let server = match server_state {
3809 Some(LanguageServerState::Starting(task)) => {
3810 let mut timer = cx
3811 .background_executor()
3812 .timer(SERVER_LAUNCHING_BEFORE_SHUTDOWN_TIMEOUT)
3813 .fuse();
3814
3815 select! {
3816 server = task.fuse() => server,
3817 _ = timer => {
3818 log::info!(
3819 "timeout waiting for language server {} to finish launching before stopping",
3820 name
3821 );
3822 None
3823 },
3824 }
3825 }
3826
3827 Some(LanguageServerState::Running { server, .. }) => Some(server),
3828
3829 None => None,
3830 };
3831
3832 if let Some(server) = server {
3833 if let Some(shutdown) = server.shutdown() {
3834 shutdown.await;
3835 }
3836 }
3837 }
3838
3839 pub fn restart_language_servers_for_buffers(
3840 &mut self,
3841 buffers: impl IntoIterator<Item = Model<Buffer>>,
3842 cx: &mut ModelContext<Self>,
3843 ) -> Option<()> {
3844 let language_server_lookup_info: HashSet<(Model<Worktree>, Arc<Language>)> = buffers
3845 .into_iter()
3846 .filter_map(|buffer| {
3847 let buffer = buffer.read(cx);
3848 let file = buffer.file()?;
3849 let worktree = File::from_dyn(Some(file))?.worktree.clone();
3850 let language = self
3851 .languages
3852 .language_for_file(file, Some(buffer.as_rope()), cx)
3853 .now_or_never()?
3854 .ok()?;
3855 Some((worktree, language))
3856 })
3857 .collect();
3858 for (worktree, language) in language_server_lookup_info {
3859 self.restart_language_servers(worktree, language, cx);
3860 }
3861
3862 None
3863 }
3864
3865 fn restart_language_servers(
3866 &mut self,
3867 worktree: Model<Worktree>,
3868 language: Arc<Language>,
3869 cx: &mut ModelContext<Self>,
3870 ) {
3871 let worktree_id = worktree.read(cx).id();
3872
3873 let stop_tasks = self
3874 .languages
3875 .clone()
3876 .lsp_adapters(&language)
3877 .iter()
3878 .map(|adapter| {
3879 let stop_task = self.stop_language_server(worktree_id, adapter.name.clone(), cx);
3880 (stop_task, adapter.name.clone())
3881 })
3882 .collect::<Vec<_>>();
3883 if stop_tasks.is_empty() {
3884 return;
3885 }
3886
3887 cx.spawn(move |this, mut cx| async move {
3888 // For each stopped language server, record all of the worktrees with which
3889 // it was associated.
3890 let mut affected_worktrees = Vec::new();
3891 for (stop_task, language_server_name) in stop_tasks {
3892 for affected_worktree_id in stop_task.await {
3893 affected_worktrees.push((affected_worktree_id, language_server_name.clone()));
3894 }
3895 }
3896
3897 this.update(&mut cx, |this, cx| {
3898 // Restart the language server for the given worktree.
3899 this.start_language_servers(&worktree, language.clone(), cx);
3900
3901 // Lookup new server ids and set them for each of the orphaned worktrees
3902 for (affected_worktree_id, language_server_name) in affected_worktrees {
3903 if let Some(new_server_id) = this
3904 .language_server_ids
3905 .get(&(worktree_id, language_server_name.clone()))
3906 .cloned()
3907 {
3908 this.language_server_ids
3909 .insert((affected_worktree_id, language_server_name), new_server_id);
3910 }
3911 }
3912 })
3913 .ok();
3914 })
3915 .detach();
3916 }
3917
3918 fn check_errored_server(
3919 language: Arc<Language>,
3920 adapter: Arc<CachedLspAdapter>,
3921 server_id: LanguageServerId,
3922 installation_test_binary: Option<LanguageServerBinary>,
3923 cx: &mut ModelContext<Self>,
3924 ) {
3925 if !adapter.can_be_reinstalled() {
3926 log::info!(
3927 "Validation check requested for {:?} but it cannot be reinstalled",
3928 adapter.name.0
3929 );
3930 return;
3931 }
3932
3933 cx.spawn(move |this, mut cx| async move {
3934 log::info!("About to spawn test binary");
3935
3936 // A lack of test binary counts as a failure
3937 let process = installation_test_binary.and_then(|binary| {
3938 smol::process::Command::new(&binary.path)
3939 .current_dir(&binary.path)
3940 .args(binary.arguments)
3941 .stdin(Stdio::piped())
3942 .stdout(Stdio::piped())
3943 .stderr(Stdio::inherit())
3944 .kill_on_drop(true)
3945 .spawn()
3946 .ok()
3947 });
3948
3949 const PROCESS_TIMEOUT: Duration = Duration::from_secs(5);
3950 let mut timeout = cx.background_executor().timer(PROCESS_TIMEOUT).fuse();
3951
3952 let mut errored = false;
3953 if let Some(mut process) = process {
3954 futures::select! {
3955 status = process.status().fuse() => match status {
3956 Ok(status) => errored = !status.success(),
3957 Err(_) => errored = true,
3958 },
3959
3960 _ = timeout => {
3961 log::info!("test binary time-ed out, this counts as a success");
3962 _ = process.kill();
3963 }
3964 }
3965 } else {
3966 log::warn!("test binary failed to launch");
3967 errored = true;
3968 }
3969
3970 if errored {
3971 log::warn!("test binary check failed");
3972 let task = this
3973 .update(&mut cx, move |this, cx| {
3974 this.reinstall_language_server(language, adapter, server_id, cx)
3975 })
3976 .ok()
3977 .flatten();
3978
3979 if let Some(task) = task {
3980 task.await;
3981 }
3982 }
3983 })
3984 .detach();
3985 }
3986
3987 fn enqueue_language_server_progress(
3988 &mut self,
3989 message: BufferOrderedMessage,
3990 cx: &mut ModelContext<Self>,
3991 ) {
3992 self.pending_language_server_update.replace(message);
3993 self.flush_language_server_update.get_or_insert_with(|| {
3994 cx.spawn(|this, mut cx| async move {
3995 cx.background_executor()
3996 .timer(SERVER_PROGRESS_DEBOUNCE_TIMEOUT)
3997 .await;
3998 this.update(&mut cx, |this, _| {
3999 this.flush_language_server_update.take();
4000 if let Some(update) = this.pending_language_server_update.take() {
4001 this.enqueue_buffer_ordered_message(update).ok();
4002 }
4003 })
4004 .ok();
4005 })
4006 });
4007 }
4008
4009 fn enqueue_buffer_ordered_message(&mut self, message: BufferOrderedMessage) -> Result<()> {
4010 if let Some(pending_message) = self.pending_language_server_update.take() {
4011 self.flush_language_server_update.take();
4012 self.buffer_ordered_messages_tx
4013 .unbounded_send(pending_message)
4014 .map_err(|e| anyhow!(e))?;
4015 }
4016 self.buffer_ordered_messages_tx
4017 .unbounded_send(message)
4018 .map_err(|e| anyhow!(e))
4019 }
4020
4021 fn on_lsp_progress(
4022 &mut self,
4023 progress: lsp::ProgressParams,
4024 language_server_id: LanguageServerId,
4025 disk_based_diagnostics_progress_token: Option<String>,
4026 cx: &mut ModelContext<Self>,
4027 ) {
4028 let token = match progress.token {
4029 lsp::NumberOrString::String(token) => token,
4030 lsp::NumberOrString::Number(token) => {
4031 log::info!("skipping numeric progress token {}", token);
4032 return;
4033 }
4034 };
4035 let lsp::ProgressParamsValue::WorkDone(progress) = progress.value;
4036 let language_server_status =
4037 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
4038 status
4039 } else {
4040 return;
4041 };
4042
4043 if !language_server_status.progress_tokens.contains(&token) {
4044 return;
4045 }
4046
4047 let is_disk_based_diagnostics_progress = disk_based_diagnostics_progress_token
4048 .as_ref()
4049 .map_or(false, |disk_based_token| {
4050 token.starts_with(disk_based_token)
4051 });
4052
4053 match progress {
4054 lsp::WorkDoneProgress::Begin(report) => {
4055 if is_disk_based_diagnostics_progress {
4056 self.disk_based_diagnostics_started(language_server_id, cx);
4057 } else {
4058 self.on_lsp_work_start(
4059 language_server_id,
4060 token.clone(),
4061 LanguageServerProgress {
4062 message: report.message.clone(),
4063 percentage: report.percentage.map(|p| p as usize),
4064 last_update_at: Instant::now(),
4065 },
4066 cx,
4067 );
4068 }
4069 }
4070 lsp::WorkDoneProgress::Report(report) => {
4071 if !is_disk_based_diagnostics_progress {
4072 self.on_lsp_work_progress(
4073 language_server_id,
4074 token.clone(),
4075 LanguageServerProgress {
4076 message: report.message.clone(),
4077 percentage: report.percentage.map(|p| p as usize),
4078 last_update_at: Instant::now(),
4079 },
4080 cx,
4081 );
4082 self.enqueue_language_server_progress(
4083 BufferOrderedMessage::LanguageServerUpdate {
4084 language_server_id,
4085 message: proto::update_language_server::Variant::WorkProgress(
4086 proto::LspWorkProgress {
4087 token,
4088 message: report.message,
4089 percentage: report.percentage,
4090 },
4091 ),
4092 },
4093 cx,
4094 );
4095 }
4096 }
4097 lsp::WorkDoneProgress::End(_) => {
4098 language_server_status.progress_tokens.remove(&token);
4099
4100 if is_disk_based_diagnostics_progress {
4101 self.disk_based_diagnostics_finished(language_server_id, cx);
4102 } else {
4103 self.on_lsp_work_end(language_server_id, token.clone(), cx);
4104 }
4105 }
4106 }
4107 }
4108
4109 fn on_lsp_work_start(
4110 &mut self,
4111 language_server_id: LanguageServerId,
4112 token: String,
4113 progress: LanguageServerProgress,
4114 cx: &mut ModelContext<Self>,
4115 ) {
4116 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
4117 status.pending_work.insert(token.clone(), progress.clone());
4118 cx.notify();
4119 }
4120
4121 if self.is_local() {
4122 self.enqueue_buffer_ordered_message(BufferOrderedMessage::LanguageServerUpdate {
4123 language_server_id,
4124 message: proto::update_language_server::Variant::WorkStart(proto::LspWorkStart {
4125 token,
4126 message: progress.message,
4127 percentage: progress.percentage.map(|p| p as u32),
4128 }),
4129 })
4130 .ok();
4131 }
4132 }
4133
4134 fn on_lsp_work_progress(
4135 &mut self,
4136 language_server_id: LanguageServerId,
4137 token: String,
4138 progress: LanguageServerProgress,
4139 cx: &mut ModelContext<Self>,
4140 ) {
4141 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
4142 let entry = status
4143 .pending_work
4144 .entry(token)
4145 .or_insert(LanguageServerProgress {
4146 message: Default::default(),
4147 percentage: Default::default(),
4148 last_update_at: progress.last_update_at,
4149 });
4150 if progress.message.is_some() {
4151 entry.message = progress.message;
4152 }
4153 if progress.percentage.is_some() {
4154 entry.percentage = progress.percentage;
4155 }
4156 entry.last_update_at = progress.last_update_at;
4157 cx.notify();
4158 }
4159 }
4160
4161 fn on_lsp_work_end(
4162 &mut self,
4163 language_server_id: LanguageServerId,
4164 token: String,
4165 cx: &mut ModelContext<Self>,
4166 ) {
4167 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
4168 cx.emit(Event::RefreshInlayHints);
4169 status.pending_work.remove(&token);
4170 cx.notify();
4171 }
4172
4173 if self.is_local() {
4174 self.enqueue_buffer_ordered_message(BufferOrderedMessage::LanguageServerUpdate {
4175 language_server_id,
4176 message: proto::update_language_server::Variant::WorkEnd(proto::LspWorkEnd {
4177 token,
4178 }),
4179 })
4180 .ok();
4181 }
4182 }
4183
4184 fn on_lsp_did_change_watched_files(
4185 &mut self,
4186 language_server_id: LanguageServerId,
4187 params: DidChangeWatchedFilesRegistrationOptions,
4188 cx: &mut ModelContext<Self>,
4189 ) {
4190 let watched_paths = self
4191 .language_server_watched_paths
4192 .entry(language_server_id)
4193 .or_default();
4194
4195 let mut builders = HashMap::default();
4196 for watcher in params.watchers {
4197 for worktree in &self.worktrees {
4198 if let Some(worktree) = worktree.upgrade() {
4199 let glob_is_inside_worktree = worktree.update(cx, |tree, _| {
4200 if let Some(abs_path) = tree.abs_path().to_str() {
4201 let relative_glob_pattern = match &watcher.glob_pattern {
4202 lsp::GlobPattern::String(s) => Some(
4203 s.strip_prefix(abs_path)
4204 .unwrap_or(s)
4205 .strip_prefix(std::path::MAIN_SEPARATOR)
4206 .unwrap_or(s),
4207 ),
4208 lsp::GlobPattern::Relative(rp) => {
4209 let base_uri = match &rp.base_uri {
4210 lsp::OneOf::Left(workspace_folder) => &workspace_folder.uri,
4211 lsp::OneOf::Right(base_uri) => base_uri,
4212 };
4213 base_uri.to_file_path().ok().and_then(|file_path| {
4214 (file_path.to_str() == Some(abs_path))
4215 .then_some(rp.pattern.as_str())
4216 })
4217 }
4218 };
4219 if let Some(relative_glob_pattern) = relative_glob_pattern {
4220 let literal_prefix = glob_literal_prefix(relative_glob_pattern);
4221 tree.as_local_mut()
4222 .unwrap()
4223 .add_path_prefix_to_scan(Path::new(literal_prefix).into());
4224 if let Some(glob) = Glob::new(relative_glob_pattern).log_err() {
4225 builders
4226 .entry(tree.id())
4227 .or_insert_with(|| GlobSetBuilder::new())
4228 .add(glob);
4229 }
4230 return true;
4231 }
4232 }
4233 false
4234 });
4235 if glob_is_inside_worktree {
4236 break;
4237 }
4238 }
4239 }
4240 }
4241
4242 watched_paths.clear();
4243 for (worktree_id, builder) in builders {
4244 if let Ok(globset) = builder.build() {
4245 watched_paths.insert(worktree_id, globset);
4246 }
4247 }
4248
4249 cx.notify();
4250 }
4251
4252 async fn on_lsp_workspace_edit(
4253 this: WeakModel<Self>,
4254 params: lsp::ApplyWorkspaceEditParams,
4255 server_id: LanguageServerId,
4256 adapter: Arc<CachedLspAdapter>,
4257 mut cx: AsyncAppContext,
4258 ) -> Result<lsp::ApplyWorkspaceEditResponse> {
4259 let this = this
4260 .upgrade()
4261 .ok_or_else(|| anyhow!("project project closed"))?;
4262 let language_server = this
4263 .update(&mut cx, |this, _| this.language_server_for_id(server_id))?
4264 .ok_or_else(|| anyhow!("language server not found"))?;
4265 let transaction = Self::deserialize_workspace_edit(
4266 this.clone(),
4267 params.edit,
4268 true,
4269 adapter.clone(),
4270 language_server.clone(),
4271 &mut cx,
4272 )
4273 .await
4274 .log_err();
4275 this.update(&mut cx, |this, _| {
4276 if let Some(transaction) = transaction {
4277 this.last_workspace_edits_by_language_server
4278 .insert(server_id, transaction);
4279 }
4280 })?;
4281 Ok(lsp::ApplyWorkspaceEditResponse {
4282 applied: true,
4283 failed_change: None,
4284 failure_reason: None,
4285 })
4286 }
4287
4288 pub fn language_server_statuses(
4289 &self,
4290 ) -> impl DoubleEndedIterator<Item = &LanguageServerStatus> {
4291 self.language_server_statuses.values()
4292 }
4293
4294 pub fn last_formatting_failure(&self) -> Option<&str> {
4295 self.last_formatting_failure.as_deref()
4296 }
4297
4298 pub fn update_diagnostics(
4299 &mut self,
4300 language_server_id: LanguageServerId,
4301 mut params: lsp::PublishDiagnosticsParams,
4302 disk_based_sources: &[String],
4303 cx: &mut ModelContext<Self>,
4304 ) -> Result<()> {
4305 let abs_path = params
4306 .uri
4307 .to_file_path()
4308 .map_err(|_| anyhow!("URI is not a file"))?;
4309 let mut diagnostics = Vec::default();
4310 let mut primary_diagnostic_group_ids = HashMap::default();
4311 let mut sources_by_group_id = HashMap::default();
4312 let mut supporting_diagnostics = HashMap::default();
4313
4314 // Ensure that primary diagnostics are always the most severe
4315 params.diagnostics.sort_by_key(|item| item.severity);
4316
4317 for diagnostic in ¶ms.diagnostics {
4318 let source = diagnostic.source.as_ref();
4319 let code = diagnostic.code.as_ref().map(|code| match code {
4320 lsp::NumberOrString::Number(code) => code.to_string(),
4321 lsp::NumberOrString::String(code) => code.clone(),
4322 });
4323 let range = range_from_lsp(diagnostic.range);
4324 let is_supporting = diagnostic
4325 .related_information
4326 .as_ref()
4327 .map_or(false, |infos| {
4328 infos.iter().any(|info| {
4329 primary_diagnostic_group_ids.contains_key(&(
4330 source,
4331 code.clone(),
4332 range_from_lsp(info.location.range),
4333 ))
4334 })
4335 });
4336
4337 let is_unnecessary = diagnostic.tags.as_ref().map_or(false, |tags| {
4338 tags.iter().any(|tag| *tag == DiagnosticTag::UNNECESSARY)
4339 });
4340
4341 if is_supporting {
4342 supporting_diagnostics.insert(
4343 (source, code.clone(), range),
4344 (diagnostic.severity, is_unnecessary),
4345 );
4346 } else {
4347 let group_id = post_inc(&mut self.next_diagnostic_group_id);
4348 let is_disk_based =
4349 source.map_or(false, |source| disk_based_sources.contains(source));
4350
4351 sources_by_group_id.insert(group_id, source);
4352 primary_diagnostic_group_ids
4353 .insert((source, code.clone(), range.clone()), group_id);
4354
4355 diagnostics.push(DiagnosticEntry {
4356 range,
4357 diagnostic: Diagnostic {
4358 source: diagnostic.source.clone(),
4359 code: code.clone(),
4360 severity: diagnostic.severity.unwrap_or(DiagnosticSeverity::ERROR),
4361 message: diagnostic.message.trim().to_string(),
4362 group_id,
4363 is_primary: true,
4364 is_disk_based,
4365 is_unnecessary,
4366 },
4367 });
4368 if let Some(infos) = &diagnostic.related_information {
4369 for info in infos {
4370 if info.location.uri == params.uri && !info.message.is_empty() {
4371 let range = range_from_lsp(info.location.range);
4372 diagnostics.push(DiagnosticEntry {
4373 range,
4374 diagnostic: Diagnostic {
4375 source: diagnostic.source.clone(),
4376 code: code.clone(),
4377 severity: DiagnosticSeverity::INFORMATION,
4378 message: info.message.trim().to_string(),
4379 group_id,
4380 is_primary: false,
4381 is_disk_based,
4382 is_unnecessary: false,
4383 },
4384 });
4385 }
4386 }
4387 }
4388 }
4389 }
4390
4391 for entry in &mut diagnostics {
4392 let diagnostic = &mut entry.diagnostic;
4393 if !diagnostic.is_primary {
4394 let source = *sources_by_group_id.get(&diagnostic.group_id).unwrap();
4395 if let Some(&(severity, is_unnecessary)) = supporting_diagnostics.get(&(
4396 source,
4397 diagnostic.code.clone(),
4398 entry.range.clone(),
4399 )) {
4400 if let Some(severity) = severity {
4401 diagnostic.severity = severity;
4402 }
4403 diagnostic.is_unnecessary = is_unnecessary;
4404 }
4405 }
4406 }
4407
4408 self.update_diagnostic_entries(
4409 language_server_id,
4410 abs_path,
4411 params.version,
4412 diagnostics,
4413 cx,
4414 )?;
4415 Ok(())
4416 }
4417
4418 pub fn update_diagnostic_entries(
4419 &mut self,
4420 server_id: LanguageServerId,
4421 abs_path: PathBuf,
4422 version: Option<i32>,
4423 diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
4424 cx: &mut ModelContext<Project>,
4425 ) -> Result<(), anyhow::Error> {
4426 let (worktree, relative_path) = self
4427 .find_local_worktree(&abs_path, cx)
4428 .ok_or_else(|| anyhow!("no worktree found for diagnostics path {abs_path:?}"))?;
4429
4430 let project_path = ProjectPath {
4431 worktree_id: worktree.read(cx).id(),
4432 path: relative_path.into(),
4433 };
4434
4435 if let Some(buffer) = self.get_open_buffer(&project_path, cx) {
4436 self.update_buffer_diagnostics(&buffer, server_id, version, diagnostics.clone(), cx)?;
4437 }
4438
4439 let updated = worktree.update(cx, |worktree, cx| {
4440 worktree
4441 .as_local_mut()
4442 .ok_or_else(|| anyhow!("not a local worktree"))?
4443 .update_diagnostics(server_id, project_path.path.clone(), diagnostics, cx)
4444 })?;
4445 if updated {
4446 cx.emit(Event::DiagnosticsUpdated {
4447 language_server_id: server_id,
4448 path: project_path,
4449 });
4450 }
4451 Ok(())
4452 }
4453
4454 fn update_buffer_diagnostics(
4455 &mut self,
4456 buffer: &Model<Buffer>,
4457 server_id: LanguageServerId,
4458 version: Option<i32>,
4459 mut diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
4460 cx: &mut ModelContext<Self>,
4461 ) -> Result<()> {
4462 fn compare_diagnostics(a: &Diagnostic, b: &Diagnostic) -> Ordering {
4463 Ordering::Equal
4464 .then_with(|| b.is_primary.cmp(&a.is_primary))
4465 .then_with(|| a.is_disk_based.cmp(&b.is_disk_based))
4466 .then_with(|| a.severity.cmp(&b.severity))
4467 .then_with(|| a.message.cmp(&b.message))
4468 }
4469
4470 let snapshot = self.buffer_snapshot_for_lsp_version(buffer, server_id, version, cx)?;
4471
4472 diagnostics.sort_unstable_by(|a, b| {
4473 Ordering::Equal
4474 .then_with(|| a.range.start.cmp(&b.range.start))
4475 .then_with(|| b.range.end.cmp(&a.range.end))
4476 .then_with(|| compare_diagnostics(&a.diagnostic, &b.diagnostic))
4477 });
4478
4479 let mut sanitized_diagnostics = Vec::new();
4480 let edits_since_save = Patch::new(
4481 snapshot
4482 .edits_since::<Unclipped<PointUtf16>>(buffer.read(cx).saved_version())
4483 .collect(),
4484 );
4485 for entry in diagnostics {
4486 let start;
4487 let end;
4488 if entry.diagnostic.is_disk_based {
4489 // Some diagnostics are based on files on disk instead of buffers'
4490 // current contents. Adjust these diagnostics' ranges to reflect
4491 // any unsaved edits.
4492 start = edits_since_save.old_to_new(entry.range.start);
4493 end = edits_since_save.old_to_new(entry.range.end);
4494 } else {
4495 start = entry.range.start;
4496 end = entry.range.end;
4497 }
4498
4499 let mut range = snapshot.clip_point_utf16(start, Bias::Left)
4500 ..snapshot.clip_point_utf16(end, Bias::Right);
4501
4502 // Expand empty ranges by one codepoint
4503 if range.start == range.end {
4504 // This will be go to the next boundary when being clipped
4505 range.end.column += 1;
4506 range.end = snapshot.clip_point_utf16(Unclipped(range.end), Bias::Right);
4507 if range.start == range.end && range.end.column > 0 {
4508 range.start.column -= 1;
4509 range.start = snapshot.clip_point_utf16(Unclipped(range.start), Bias::Left);
4510 }
4511 }
4512
4513 sanitized_diagnostics.push(DiagnosticEntry {
4514 range,
4515 diagnostic: entry.diagnostic,
4516 });
4517 }
4518 drop(edits_since_save);
4519
4520 let set = DiagnosticSet::new(sanitized_diagnostics, &snapshot);
4521 buffer.update(cx, |buffer, cx| {
4522 buffer.update_diagnostics(server_id, set, cx)
4523 });
4524 Ok(())
4525 }
4526
4527 pub fn reload_buffers(
4528 &self,
4529 buffers: HashSet<Model<Buffer>>,
4530 push_to_history: bool,
4531 cx: &mut ModelContext<Self>,
4532 ) -> Task<Result<ProjectTransaction>> {
4533 let mut local_buffers = Vec::new();
4534 let mut remote_buffers = None;
4535 for buffer_handle in buffers {
4536 let buffer = buffer_handle.read(cx);
4537 if buffer.is_dirty() {
4538 if let Some(file) = File::from_dyn(buffer.file()) {
4539 if file.is_local() {
4540 local_buffers.push(buffer_handle);
4541 } else {
4542 remote_buffers.get_or_insert(Vec::new()).push(buffer_handle);
4543 }
4544 }
4545 }
4546 }
4547
4548 let remote_buffers = self.remote_id().zip(remote_buffers);
4549 let client = self.client.clone();
4550
4551 cx.spawn(move |this, mut cx| async move {
4552 let mut project_transaction = ProjectTransaction::default();
4553
4554 if let Some((project_id, remote_buffers)) = remote_buffers {
4555 let response = client
4556 .request(proto::ReloadBuffers {
4557 project_id,
4558 buffer_ids: remote_buffers
4559 .iter()
4560 .filter_map(|buffer| {
4561 buffer
4562 .update(&mut cx, |buffer, _| buffer.remote_id().into())
4563 .ok()
4564 })
4565 .collect(),
4566 })
4567 .await?
4568 .transaction
4569 .ok_or_else(|| anyhow!("missing transaction"))?;
4570 project_transaction = this
4571 .update(&mut cx, |this, cx| {
4572 this.deserialize_project_transaction(response, push_to_history, cx)
4573 })?
4574 .await?;
4575 }
4576
4577 for buffer in local_buffers {
4578 let transaction = buffer
4579 .update(&mut cx, |buffer, cx| buffer.reload(cx))?
4580 .await?;
4581 buffer.update(&mut cx, |buffer, cx| {
4582 if let Some(transaction) = transaction {
4583 if !push_to_history {
4584 buffer.forget_transaction(transaction.id);
4585 }
4586 project_transaction.0.insert(cx.handle(), transaction);
4587 }
4588 })?;
4589 }
4590
4591 Ok(project_transaction)
4592 })
4593 }
4594
4595 pub fn format(
4596 &mut self,
4597 buffers: HashSet<Model<Buffer>>,
4598 push_to_history: bool,
4599 trigger: FormatTrigger,
4600 cx: &mut ModelContext<Project>,
4601 ) -> Task<anyhow::Result<ProjectTransaction>> {
4602 if self.is_local() {
4603 let buffers_with_paths = buffers
4604 .into_iter()
4605 .filter_map(|buffer_handle| {
4606 let buffer = buffer_handle.read(cx);
4607 let file = File::from_dyn(buffer.file())?;
4608 let buffer_abs_path = file.as_local().map(|f| f.abs_path(cx));
4609 Some((buffer_handle, buffer_abs_path))
4610 })
4611 .collect::<Vec<_>>();
4612
4613 cx.spawn(move |project, mut cx| async move {
4614 let result = Self::format_locally(
4615 project.clone(),
4616 buffers_with_paths,
4617 push_to_history,
4618 trigger,
4619 cx.clone(),
4620 )
4621 .await;
4622
4623 project.update(&mut cx, |project, _| match &result {
4624 Ok(_) => project.last_formatting_failure = None,
4625 Err(error) => {
4626 project.last_formatting_failure.replace(error.to_string());
4627 }
4628 })?;
4629
4630 result
4631 })
4632 } else {
4633 let remote_id = self.remote_id();
4634 let client = self.client.clone();
4635 cx.spawn(move |this, mut cx| async move {
4636 let mut project_transaction = ProjectTransaction::default();
4637 if let Some(project_id) = remote_id {
4638 let response = client
4639 .request(proto::FormatBuffers {
4640 project_id,
4641 trigger: trigger as i32,
4642 buffer_ids: buffers
4643 .iter()
4644 .map(|buffer| {
4645 buffer.update(&mut cx, |buffer, _| buffer.remote_id().into())
4646 })
4647 .collect::<Result<_>>()?,
4648 })
4649 .await?
4650 .transaction
4651 .ok_or_else(|| anyhow!("missing transaction"))?;
4652 project_transaction = this
4653 .update(&mut cx, |this, cx| {
4654 this.deserialize_project_transaction(response, push_to_history, cx)
4655 })?
4656 .await?;
4657 }
4658 Ok(project_transaction)
4659 })
4660 }
4661 }
4662
4663 async fn format_locally(
4664 project: WeakModel<Project>,
4665 mut buffers_with_paths: Vec<(Model<Buffer>, Option<PathBuf>)>,
4666 push_to_history: bool,
4667 trigger: FormatTrigger,
4668 mut cx: AsyncAppContext,
4669 ) -> anyhow::Result<ProjectTransaction> {
4670 // Do not allow multiple concurrent formatting requests for the
4671 // same buffer.
4672 project.update(&mut cx, |this, cx| {
4673 buffers_with_paths.retain(|(buffer, _)| {
4674 this.buffers_being_formatted
4675 .insert(buffer.read(cx).remote_id())
4676 });
4677 })?;
4678
4679 let _cleanup = defer({
4680 let this = project.clone();
4681 let mut cx = cx.clone();
4682 let buffers = &buffers_with_paths;
4683 move || {
4684 this.update(&mut cx, |this, cx| {
4685 for (buffer, _) in buffers {
4686 this.buffers_being_formatted
4687 .remove(&buffer.read(cx).remote_id());
4688 }
4689 })
4690 .ok();
4691 }
4692 });
4693
4694 let mut project_transaction = ProjectTransaction::default();
4695 for (buffer, buffer_abs_path) in &buffers_with_paths {
4696 let (primary_adapter_and_server, adapters_and_servers) =
4697 project.update(&mut cx, |project, cx| {
4698 let buffer = buffer.read(cx);
4699
4700 let adapters_and_servers = project
4701 .language_servers_for_buffer(buffer, cx)
4702 .map(|(adapter, lsp)| (adapter.clone(), lsp.clone()))
4703 .collect::<Vec<_>>();
4704
4705 let primary_adapter = project
4706 .primary_language_server_for_buffer(buffer, cx)
4707 .map(|(adapter, lsp)| (adapter.clone(), lsp.clone()));
4708
4709 (primary_adapter, adapters_and_servers)
4710 })?;
4711
4712 let settings = buffer.update(&mut cx, |buffer, cx| {
4713 language_settings(buffer.language(), buffer.file(), cx).clone()
4714 })?;
4715
4716 let remove_trailing_whitespace = settings.remove_trailing_whitespace_on_save;
4717 let ensure_final_newline = settings.ensure_final_newline_on_save;
4718 let tab_size = settings.tab_size;
4719
4720 // First, format buffer's whitespace according to the settings.
4721 let trailing_whitespace_diff = if remove_trailing_whitespace {
4722 Some(
4723 buffer
4724 .update(&mut cx, |b, cx| b.remove_trailing_whitespace(cx))?
4725 .await,
4726 )
4727 } else {
4728 None
4729 };
4730 let whitespace_transaction_id = buffer.update(&mut cx, |buffer, cx| {
4731 buffer.finalize_last_transaction();
4732 buffer.start_transaction();
4733 if let Some(diff) = trailing_whitespace_diff {
4734 buffer.apply_diff(diff, cx);
4735 }
4736 if ensure_final_newline {
4737 buffer.ensure_final_newline(cx);
4738 }
4739 buffer.end_transaction(cx)
4740 })?;
4741
4742 // Apply the `code_actions_on_format` before we run the formatter.
4743 let code_actions = deserialize_code_actions(&settings.code_actions_on_format);
4744 #[allow(clippy::nonminimal_bool)]
4745 if !code_actions.is_empty()
4746 && !(trigger == FormatTrigger::Save && settings.format_on_save == FormatOnSave::Off)
4747 {
4748 Self::execute_code_actions_on_servers(
4749 &project,
4750 &adapters_and_servers,
4751 code_actions,
4752 buffer,
4753 push_to_history,
4754 &mut project_transaction,
4755 &mut cx,
4756 )
4757 .await?;
4758 }
4759
4760 // Apply language-specific formatting using either the primary language server
4761 // or external command.
4762 // Except for code actions, which are applied with all connected language servers.
4763 let primary_language_server =
4764 primary_adapter_and_server.map(|(_adapter, server)| server.clone());
4765 let server_and_buffer = primary_language_server
4766 .as_ref()
4767 .zip(buffer_abs_path.as_ref());
4768
4769 let mut format_operation = None;
4770 match (&settings.formatter, &settings.format_on_save) {
4771 (_, FormatOnSave::Off) if trigger == FormatTrigger::Save => {}
4772
4773 (Formatter::CodeActions(code_actions), FormatOnSave::On | FormatOnSave::Off)
4774 | (_, FormatOnSave::CodeActions(code_actions)) => {
4775 let code_actions = deserialize_code_actions(code_actions);
4776 if !code_actions.is_empty() {
4777 Self::execute_code_actions_on_servers(
4778 &project,
4779 &adapters_and_servers,
4780 code_actions,
4781 buffer,
4782 push_to_history,
4783 &mut project_transaction,
4784 &mut cx,
4785 )
4786 .await?;
4787 }
4788 }
4789 (Formatter::LanguageServer, FormatOnSave::On | FormatOnSave::Off)
4790 | (_, FormatOnSave::LanguageServer) => {
4791 if let Some((language_server, buffer_abs_path)) = server_and_buffer {
4792 format_operation = Some(FormatOperation::Lsp(
4793 Self::format_via_lsp(
4794 &project,
4795 buffer,
4796 buffer_abs_path,
4797 language_server,
4798 tab_size,
4799 &mut cx,
4800 )
4801 .await
4802 .context("failed to format via language server")?,
4803 ));
4804 }
4805 }
4806
4807 (
4808 Formatter::External { command, arguments },
4809 FormatOnSave::On | FormatOnSave::Off,
4810 )
4811 | (_, FormatOnSave::External { command, arguments }) => {
4812 if let Some(buffer_abs_path) = buffer_abs_path {
4813 format_operation = Self::format_via_external_command(
4814 buffer,
4815 buffer_abs_path,
4816 command,
4817 arguments,
4818 &mut cx,
4819 )
4820 .await
4821 .context(format!(
4822 "failed to format via external command {:?}",
4823 command
4824 ))?
4825 .map(FormatOperation::External);
4826 }
4827 }
4828 (Formatter::Auto, FormatOnSave::On | FormatOnSave::Off) => {
4829 let prettier =
4830 prettier_support::format_with_prettier(&project, buffer, &mut cx).await;
4831
4832 if let Some(operation) = prettier {
4833 format_operation = Some(operation?);
4834 } else if let Some((language_server, buffer_abs_path)) = server_and_buffer {
4835 format_operation = Some(FormatOperation::Lsp(
4836 Self::format_via_lsp(
4837 &project,
4838 buffer,
4839 buffer_abs_path,
4840 language_server,
4841 tab_size,
4842 &mut cx,
4843 )
4844 .await
4845 .context("failed to format via language server")?,
4846 ));
4847 }
4848 }
4849 (Formatter::Prettier, FormatOnSave::On | FormatOnSave::Off) => {
4850 let prettier =
4851 prettier_support::format_with_prettier(&project, buffer, &mut cx).await;
4852
4853 if let Some(operation) = prettier {
4854 format_operation = Some(operation?);
4855 }
4856 }
4857 };
4858
4859 buffer.update(&mut cx, |b, cx| {
4860 // If the buffer had its whitespace formatted and was edited while the language-specific
4861 // formatting was being computed, avoid applying the language-specific formatting, because
4862 // it can't be grouped with the whitespace formatting in the undo history.
4863 if let Some(transaction_id) = whitespace_transaction_id {
4864 if b.peek_undo_stack()
4865 .map_or(true, |e| e.transaction_id() != transaction_id)
4866 {
4867 format_operation.take();
4868 }
4869 }
4870
4871 // Apply any language-specific formatting, and group the two formatting operations
4872 // in the buffer's undo history.
4873 if let Some(operation) = format_operation {
4874 match operation {
4875 FormatOperation::Lsp(edits) => {
4876 b.edit(edits, None, cx);
4877 }
4878 FormatOperation::External(diff) => {
4879 b.apply_diff(diff, cx);
4880 }
4881 FormatOperation::Prettier(diff) => {
4882 b.apply_diff(diff, cx);
4883 }
4884 }
4885
4886 if let Some(transaction_id) = whitespace_transaction_id {
4887 b.group_until_transaction(transaction_id);
4888 } else if let Some(transaction) = project_transaction.0.get(buffer) {
4889 b.group_until_transaction(transaction.id)
4890 }
4891 }
4892
4893 if let Some(transaction) = b.finalize_last_transaction().cloned() {
4894 if !push_to_history {
4895 b.forget_transaction(transaction.id);
4896 }
4897 project_transaction.0.insert(buffer.clone(), transaction);
4898 }
4899 })?;
4900 }
4901
4902 Ok(project_transaction)
4903 }
4904
4905 async fn format_via_lsp(
4906 this: &WeakModel<Self>,
4907 buffer: &Model<Buffer>,
4908 abs_path: &Path,
4909 language_server: &Arc<LanguageServer>,
4910 tab_size: NonZeroU32,
4911 cx: &mut AsyncAppContext,
4912 ) -> Result<Vec<(Range<Anchor>, String)>> {
4913 let uri = lsp::Url::from_file_path(abs_path)
4914 .map_err(|_| anyhow!("failed to convert abs path to uri"))?;
4915 let text_document = lsp::TextDocumentIdentifier::new(uri);
4916 let capabilities = &language_server.capabilities();
4917
4918 let formatting_provider = capabilities.document_formatting_provider.as_ref();
4919 let range_formatting_provider = capabilities.document_range_formatting_provider.as_ref();
4920
4921 let lsp_edits = if matches!(formatting_provider, Some(p) if *p != OneOf::Left(false)) {
4922 language_server
4923 .request::<lsp::request::Formatting>(lsp::DocumentFormattingParams {
4924 text_document,
4925 options: lsp_command::lsp_formatting_options(tab_size.get()),
4926 work_done_progress_params: Default::default(),
4927 })
4928 .await?
4929 } else if matches!(range_formatting_provider, Some(p) if *p != OneOf::Left(false)) {
4930 let buffer_start = lsp::Position::new(0, 0);
4931 let buffer_end = buffer.update(cx, |b, _| point_to_lsp(b.max_point_utf16()))?;
4932
4933 language_server
4934 .request::<lsp::request::RangeFormatting>(lsp::DocumentRangeFormattingParams {
4935 text_document,
4936 range: lsp::Range::new(buffer_start, buffer_end),
4937 options: lsp_command::lsp_formatting_options(tab_size.get()),
4938 work_done_progress_params: Default::default(),
4939 })
4940 .await?
4941 } else {
4942 None
4943 };
4944
4945 if let Some(lsp_edits) = lsp_edits {
4946 this.update(cx, |this, cx| {
4947 this.edits_from_lsp(buffer, lsp_edits, language_server.server_id(), None, cx)
4948 })?
4949 .await
4950 } else {
4951 Ok(Vec::new())
4952 }
4953 }
4954
4955 async fn format_via_external_command(
4956 buffer: &Model<Buffer>,
4957 buffer_abs_path: &Path,
4958 command: &str,
4959 arguments: &[String],
4960 cx: &mut AsyncAppContext,
4961 ) -> Result<Option<Diff>> {
4962 let working_dir_path = buffer.update(cx, |buffer, cx| {
4963 let file = File::from_dyn(buffer.file())?;
4964 let worktree = file.worktree.read(cx).as_local()?;
4965 let mut worktree_path = worktree.abs_path().to_path_buf();
4966 if worktree.root_entry()?.is_file() {
4967 worktree_path.pop();
4968 }
4969 Some(worktree_path)
4970 })?;
4971
4972 if let Some(working_dir_path) = working_dir_path {
4973 let mut child =
4974 smol::process::Command::new(command)
4975 .args(arguments.iter().map(|arg| {
4976 arg.replace("{buffer_path}", &buffer_abs_path.to_string_lossy())
4977 }))
4978 .current_dir(&working_dir_path)
4979 .stdin(smol::process::Stdio::piped())
4980 .stdout(smol::process::Stdio::piped())
4981 .stderr(smol::process::Stdio::piped())
4982 .spawn()?;
4983 let stdin = child
4984 .stdin
4985 .as_mut()
4986 .ok_or_else(|| anyhow!("failed to acquire stdin"))?;
4987 let text = buffer.update(cx, |buffer, _| buffer.as_rope().clone())?;
4988 for chunk in text.chunks() {
4989 stdin.write_all(chunk.as_bytes()).await?;
4990 }
4991 stdin.flush().await?;
4992
4993 let output = child.output().await?;
4994 if !output.status.success() {
4995 return Err(anyhow!(
4996 "command failed with exit code {:?}:\nstdout: {}\nstderr: {}",
4997 output.status.code(),
4998 String::from_utf8_lossy(&output.stdout),
4999 String::from_utf8_lossy(&output.stderr),
5000 ));
5001 }
5002
5003 let stdout = String::from_utf8(output.stdout)?;
5004 Ok(Some(
5005 buffer
5006 .update(cx, |buffer, cx| buffer.diff(stdout, cx))?
5007 .await,
5008 ))
5009 } else {
5010 Ok(None)
5011 }
5012 }
5013
5014 #[inline(never)]
5015 fn definition_impl(
5016 &self,
5017 buffer: &Model<Buffer>,
5018 position: PointUtf16,
5019 cx: &mut ModelContext<Self>,
5020 ) -> Task<Result<Vec<LocationLink>>> {
5021 self.request_lsp(
5022 buffer.clone(),
5023 LanguageServerToQuery::Primary,
5024 GetDefinition { position },
5025 cx,
5026 )
5027 }
5028 pub fn 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.definition_impl(buffer, position, cx)
5036 }
5037
5038 fn type_definition_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 GetTypeDefinition { position },
5048 cx,
5049 )
5050 }
5051
5052 pub fn type_definition<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.type_definition_impl(buffer, position, cx)
5060 }
5061
5062 fn implementation_impl(
5063 &self,
5064 buffer: &Model<Buffer>,
5065 position: PointUtf16,
5066 cx: &mut ModelContext<Self>,
5067 ) -> Task<Result<Vec<LocationLink>>> {
5068 self.request_lsp(
5069 buffer.clone(),
5070 LanguageServerToQuery::Primary,
5071 GetImplementation { position },
5072 cx,
5073 )
5074 }
5075
5076 pub fn implementation<T: ToPointUtf16>(
5077 &self,
5078 buffer: &Model<Buffer>,
5079 position: T,
5080 cx: &mut ModelContext<Self>,
5081 ) -> Task<Result<Vec<LocationLink>>> {
5082 let position = position.to_point_utf16(buffer.read(cx));
5083 self.implementation_impl(buffer, position, cx)
5084 }
5085
5086 fn references_impl(
5087 &self,
5088 buffer: &Model<Buffer>,
5089 position: PointUtf16,
5090 cx: &mut ModelContext<Self>,
5091 ) -> Task<Result<Vec<Location>>> {
5092 self.request_lsp(
5093 buffer.clone(),
5094 LanguageServerToQuery::Primary,
5095 GetReferences { position },
5096 cx,
5097 )
5098 }
5099 pub fn references<T: ToPointUtf16>(
5100 &self,
5101 buffer: &Model<Buffer>,
5102 position: T,
5103 cx: &mut ModelContext<Self>,
5104 ) -> Task<Result<Vec<Location>>> {
5105 let position = position.to_point_utf16(buffer.read(cx));
5106 self.references_impl(buffer, position, cx)
5107 }
5108
5109 fn document_highlights_impl(
5110 &self,
5111 buffer: &Model<Buffer>,
5112 position: PointUtf16,
5113 cx: &mut ModelContext<Self>,
5114 ) -> Task<Result<Vec<DocumentHighlight>>> {
5115 self.request_lsp(
5116 buffer.clone(),
5117 LanguageServerToQuery::Primary,
5118 GetDocumentHighlights { position },
5119 cx,
5120 )
5121 }
5122
5123 pub fn document_highlights<T: ToPointUtf16>(
5124 &self,
5125 buffer: &Model<Buffer>,
5126 position: T,
5127 cx: &mut ModelContext<Self>,
5128 ) -> Task<Result<Vec<DocumentHighlight>>> {
5129 let position = position.to_point_utf16(buffer.read(cx));
5130 self.document_highlights_impl(buffer, position, cx)
5131 }
5132
5133 pub fn symbols(&self, query: &str, cx: &mut ModelContext<Self>) -> Task<Result<Vec<Symbol>>> {
5134 let language_registry = self.languages.clone();
5135
5136 if self.is_local() {
5137 let mut requests = Vec::new();
5138 for ((worktree_id, _), server_id) in self.language_server_ids.iter() {
5139 let Some(worktree_handle) = self.worktree_for_id(*worktree_id, cx) else {
5140 continue;
5141 };
5142 let worktree = worktree_handle.read(cx);
5143 if !worktree.is_visible() {
5144 continue;
5145 }
5146 let Some(worktree) = worktree.as_local() else {
5147 continue;
5148 };
5149 let worktree_abs_path = worktree.abs_path().clone();
5150
5151 let (adapter, language, server) = match self.language_servers.get(server_id) {
5152 Some(LanguageServerState::Running {
5153 adapter,
5154 language,
5155 server,
5156 ..
5157 }) => (adapter.clone(), language.clone(), server),
5158
5159 _ => continue,
5160 };
5161
5162 requests.push(
5163 server
5164 .request::<lsp::request::WorkspaceSymbolRequest>(
5165 lsp::WorkspaceSymbolParams {
5166 query: query.to_string(),
5167 ..Default::default()
5168 },
5169 )
5170 .log_err()
5171 .map(move |response| {
5172 let lsp_symbols = response.flatten().map(|symbol_response| match symbol_response {
5173 lsp::WorkspaceSymbolResponse::Flat(flat_responses) => {
5174 flat_responses.into_iter().map(|lsp_symbol| {
5175 (lsp_symbol.name, lsp_symbol.kind, lsp_symbol.location)
5176 }).collect::<Vec<_>>()
5177 }
5178 lsp::WorkspaceSymbolResponse::Nested(nested_responses) => {
5179 nested_responses.into_iter().filter_map(|lsp_symbol| {
5180 let location = match lsp_symbol.location {
5181 OneOf::Left(location) => location,
5182 OneOf::Right(_) => {
5183 error!("Unexpected: client capabilities forbid symbol resolutions in workspace.symbol.resolveSupport");
5184 return None
5185 }
5186 };
5187 Some((lsp_symbol.name, lsp_symbol.kind, location))
5188 }).collect::<Vec<_>>()
5189 }
5190 }).unwrap_or_default();
5191
5192 (
5193 adapter,
5194 language,
5195 worktree_handle.downgrade(),
5196 worktree_abs_path,
5197 lsp_symbols,
5198 )
5199 }),
5200 );
5201 }
5202
5203 cx.spawn(move |this, mut cx| async move {
5204 let responses = futures::future::join_all(requests).await;
5205 let this = match this.upgrade() {
5206 Some(this) => this,
5207 None => return Ok(Vec::new()),
5208 };
5209
5210 let mut symbols = Vec::new();
5211 for (adapter, adapter_language, source_worktree, worktree_abs_path, lsp_symbols) in
5212 responses
5213 {
5214 let core_symbols = this.update(&mut cx, |this, cx| {
5215 lsp_symbols
5216 .into_iter()
5217 .filter_map(|(symbol_name, symbol_kind, symbol_location)| {
5218 let abs_path = symbol_location.uri.to_file_path().ok()?;
5219 let source_worktree = source_worktree.upgrade()?;
5220 let source_worktree_id = source_worktree.read(cx).id();
5221
5222 let path;
5223 let worktree;
5224 if let Some((tree, rel_path)) =
5225 this.find_local_worktree(&abs_path, cx)
5226 {
5227 worktree = tree;
5228 path = rel_path;
5229 } else {
5230 worktree = source_worktree.clone();
5231 path = relativize_path(&worktree_abs_path, &abs_path);
5232 }
5233
5234 let worktree_id = worktree.read(cx).id();
5235 let project_path = ProjectPath {
5236 worktree_id,
5237 path: path.into(),
5238 };
5239 let signature = this.symbol_signature(&project_path);
5240 Some(CoreSymbol {
5241 language_server_name: adapter.name.clone(),
5242 source_worktree_id,
5243 path: project_path,
5244 kind: symbol_kind,
5245 name: symbol_name,
5246 range: range_from_lsp(symbol_location.range),
5247 signature,
5248 })
5249 })
5250 .collect()
5251 })?;
5252
5253 populate_labels_for_symbols(
5254 core_symbols,
5255 &language_registry,
5256 Some(adapter_language),
5257 Some(adapter),
5258 &mut symbols,
5259 )
5260 .await;
5261 }
5262
5263 Ok(symbols)
5264 })
5265 } else if let Some(project_id) = self.remote_id() {
5266 let request = self.client.request(proto::GetProjectSymbols {
5267 project_id,
5268 query: query.to_string(),
5269 });
5270 cx.foreground_executor().spawn(async move {
5271 let response = request.await?;
5272 let mut symbols = Vec::new();
5273 let core_symbols = response
5274 .symbols
5275 .into_iter()
5276 .filter_map(|symbol| Self::deserialize_symbol(symbol).log_err())
5277 .collect::<Vec<_>>();
5278 populate_labels_for_symbols(
5279 core_symbols,
5280 &language_registry,
5281 None,
5282 None,
5283 &mut symbols,
5284 )
5285 .await;
5286 Ok(symbols)
5287 })
5288 } else {
5289 Task::ready(Ok(Default::default()))
5290 }
5291 }
5292
5293 pub fn open_buffer_for_symbol(
5294 &mut self,
5295 symbol: &Symbol,
5296 cx: &mut ModelContext<Self>,
5297 ) -> Task<Result<Model<Buffer>>> {
5298 if self.is_local() {
5299 let language_server_id = if let Some(id) = self.language_server_ids.get(&(
5300 symbol.source_worktree_id,
5301 symbol.language_server_name.clone(),
5302 )) {
5303 *id
5304 } else {
5305 return Task::ready(Err(anyhow!(
5306 "language server for worktree and language not found"
5307 )));
5308 };
5309
5310 let worktree_abs_path = if let Some(worktree_abs_path) = self
5311 .worktree_for_id(symbol.path.worktree_id, cx)
5312 .and_then(|worktree| worktree.read(cx).as_local())
5313 .map(|local_worktree| local_worktree.abs_path())
5314 {
5315 worktree_abs_path
5316 } else {
5317 return Task::ready(Err(anyhow!("worktree not found for symbol")));
5318 };
5319
5320 let symbol_abs_path = resolve_path(worktree_abs_path, &symbol.path.path);
5321 let symbol_uri = if let Ok(uri) = lsp::Url::from_file_path(symbol_abs_path) {
5322 uri
5323 } else {
5324 return Task::ready(Err(anyhow!("invalid symbol path")));
5325 };
5326
5327 self.open_local_buffer_via_lsp(
5328 symbol_uri,
5329 language_server_id,
5330 symbol.language_server_name.clone(),
5331 cx,
5332 )
5333 } else if let Some(project_id) = self.remote_id() {
5334 let request = self.client.request(proto::OpenBufferForSymbol {
5335 project_id,
5336 symbol: Some(serialize_symbol(symbol)),
5337 });
5338 cx.spawn(move |this, mut cx| async move {
5339 let response = request.await?;
5340 let buffer_id = BufferId::new(response.buffer_id)?;
5341 this.update(&mut cx, |this, cx| {
5342 this.wait_for_remote_buffer(buffer_id, cx)
5343 })?
5344 .await
5345 })
5346 } else {
5347 Task::ready(Err(anyhow!("project does not have a remote id")))
5348 }
5349 }
5350
5351 fn hover_impl(
5352 &self,
5353 buffer: &Model<Buffer>,
5354 position: PointUtf16,
5355 cx: &mut ModelContext<Self>,
5356 ) -> Task<Vec<Hover>> {
5357 if self.is_local() {
5358 let all_actions_task = self.request_multiple_lsp_locally(
5359 &buffer,
5360 Some(position),
5361 |server_capabilities| match server_capabilities.hover_provider {
5362 Some(lsp::HoverProviderCapability::Simple(enabled)) => enabled,
5363 Some(lsp::HoverProviderCapability::Options(_)) => true,
5364 None => false,
5365 },
5366 GetHover { position },
5367 cx,
5368 );
5369 cx.spawn(|_, _| async move {
5370 all_actions_task
5371 .await
5372 .into_iter()
5373 .filter_map(|hover| remove_empty_hover_blocks(hover?))
5374 .collect()
5375 })
5376 } else if let Some(project_id) = self.remote_id() {
5377 let request_task = self.client().request(proto::MultiLspQuery {
5378 buffer_id: buffer.read(cx).remote_id().into(),
5379 version: serialize_version(&buffer.read(cx).version()),
5380 project_id,
5381 strategy: Some(proto::multi_lsp_query::Strategy::All(
5382 proto::AllLanguageServers {},
5383 )),
5384 request: Some(proto::multi_lsp_query::Request::GetHover(
5385 GetHover { position }.to_proto(project_id, buffer.read(cx)),
5386 )),
5387 });
5388 let buffer = buffer.clone();
5389 cx.spawn(|weak_project, cx| async move {
5390 let Some(project) = weak_project.upgrade() else {
5391 return Vec::new();
5392 };
5393 join_all(
5394 request_task
5395 .await
5396 .log_err()
5397 .map(|response| response.responses)
5398 .unwrap_or_default()
5399 .into_iter()
5400 .filter_map(|lsp_response| match lsp_response.response? {
5401 proto::lsp_response::Response::GetHoverResponse(response) => {
5402 Some(response)
5403 }
5404 unexpected => {
5405 debug_panic!("Unexpected response: {unexpected:?}");
5406 None
5407 }
5408 })
5409 .map(|hover_response| {
5410 let response = GetHover { position }.response_from_proto(
5411 hover_response,
5412 project.clone(),
5413 buffer.clone(),
5414 cx.clone(),
5415 );
5416 async move {
5417 response
5418 .await
5419 .log_err()
5420 .flatten()
5421 .and_then(remove_empty_hover_blocks)
5422 }
5423 }),
5424 )
5425 .await
5426 .into_iter()
5427 .flatten()
5428 .collect()
5429 })
5430 } else {
5431 log::error!("cannot show hovers: project does not have a remote id");
5432 Task::ready(Vec::new())
5433 }
5434 }
5435
5436 pub fn hover<T: ToPointUtf16>(
5437 &self,
5438 buffer: &Model<Buffer>,
5439 position: T,
5440 cx: &mut ModelContext<Self>,
5441 ) -> Task<Vec<Hover>> {
5442 let position = position.to_point_utf16(buffer.read(cx));
5443 self.hover_impl(buffer, position, cx)
5444 }
5445
5446 #[inline(never)]
5447 fn completions_impl(
5448 &self,
5449 buffer: &Model<Buffer>,
5450 position: PointUtf16,
5451 cx: &mut ModelContext<Self>,
5452 ) -> Task<Result<Vec<Completion>>> {
5453 let language_registry = self.languages.clone();
5454
5455 if self.is_local() {
5456 let snapshot = buffer.read(cx).snapshot();
5457 let offset = position.to_offset(&snapshot);
5458 let scope = snapshot.language_scope_at(offset);
5459 let language = snapshot.language().cloned();
5460
5461 let server_ids: Vec<_> = self
5462 .language_servers_for_buffer(buffer.read(cx), cx)
5463 .filter(|(_, server)| server.capabilities().completion_provider.is_some())
5464 .filter(|(adapter, _)| {
5465 scope
5466 .as_ref()
5467 .map(|scope| scope.language_allowed(&adapter.name))
5468 .unwrap_or(true)
5469 })
5470 .map(|(_, server)| server.server_id())
5471 .collect();
5472
5473 let buffer = buffer.clone();
5474 cx.spawn(move |this, mut cx| async move {
5475 let mut tasks = Vec::with_capacity(server_ids.len());
5476 this.update(&mut cx, |this, cx| {
5477 for server_id in server_ids {
5478 let lsp_adapter = this.language_server_adapter_for_id(server_id);
5479 tasks.push((
5480 lsp_adapter,
5481 this.request_lsp(
5482 buffer.clone(),
5483 LanguageServerToQuery::Other(server_id),
5484 GetCompletions { position },
5485 cx,
5486 ),
5487 ));
5488 }
5489 })?;
5490
5491 let mut completions = Vec::new();
5492 for (lsp_adapter, task) in tasks {
5493 if let Ok(new_completions) = task.await {
5494 populate_labels_for_completions(
5495 new_completions,
5496 &language_registry,
5497 language.clone(),
5498 lsp_adapter,
5499 &mut completions,
5500 )
5501 .await;
5502 }
5503 }
5504
5505 Ok(completions)
5506 })
5507 } else if let Some(project_id) = self.remote_id() {
5508 let task = self.send_lsp_proto_request(
5509 buffer.clone(),
5510 project_id,
5511 GetCompletions { position },
5512 cx,
5513 );
5514 let language = buffer.read(cx).language().cloned();
5515
5516 // In the future, we should provide project guests with the names of LSP adapters,
5517 // so that they can use the correct LSP adapter when computing labels. For now,
5518 // guests just use the first LSP adapter associated with the buffer's language.
5519 let lsp_adapter = language
5520 .as_ref()
5521 .and_then(|language| language_registry.lsp_adapters(language).first().cloned());
5522
5523 cx.foreground_executor().spawn(async move {
5524 let completions = task.await?;
5525 let mut result = Vec::new();
5526 populate_labels_for_completions(
5527 completions,
5528 &language_registry,
5529 language,
5530 lsp_adapter,
5531 &mut result,
5532 )
5533 .await;
5534 Ok(result)
5535 })
5536 } else {
5537 Task::ready(Ok(Default::default()))
5538 }
5539 }
5540
5541 pub fn completions<T: ToOffset + ToPointUtf16>(
5542 &self,
5543 buffer: &Model<Buffer>,
5544 position: T,
5545 cx: &mut ModelContext<Self>,
5546 ) -> Task<Result<Vec<Completion>>> {
5547 let position = position.to_point_utf16(buffer.read(cx));
5548 self.completions_impl(buffer, position, cx)
5549 }
5550
5551 pub fn resolve_completions(
5552 &self,
5553 completion_indices: Vec<usize>,
5554 completions: Arc<RwLock<Box<[Completion]>>>,
5555 cx: &mut ModelContext<Self>,
5556 ) -> Task<Result<bool>> {
5557 let client = self.client();
5558 let language_registry = self.languages().clone();
5559
5560 let is_remote = self.is_remote();
5561 let project_id = self.remote_id();
5562
5563 cx.spawn(move |this, mut cx| async move {
5564 let mut did_resolve = false;
5565 if is_remote {
5566 let project_id =
5567 project_id.ok_or_else(|| anyhow!("Remote project without remote_id"))?;
5568
5569 for completion_index in completion_indices {
5570 let (server_id, completion) = {
5571 let completions_guard = completions.read();
5572 let completion = &completions_guard[completion_index];
5573 if completion.documentation.is_some() {
5574 continue;
5575 }
5576
5577 did_resolve = true;
5578 let server_id = completion.server_id;
5579 let completion = completion.lsp_completion.clone();
5580
5581 (server_id, completion)
5582 };
5583
5584 Self::resolve_completion_documentation_remote(
5585 project_id,
5586 server_id,
5587 completions.clone(),
5588 completion_index,
5589 completion,
5590 client.clone(),
5591 language_registry.clone(),
5592 )
5593 .await;
5594 }
5595 } else {
5596 for completion_index in completion_indices {
5597 let (server_id, completion) = {
5598 let completions_guard = completions.read();
5599 let completion = &completions_guard[completion_index];
5600 if completion.documentation.is_some() {
5601 continue;
5602 }
5603
5604 let server_id = completion.server_id;
5605 let completion = completion.lsp_completion.clone();
5606
5607 (server_id, completion)
5608 };
5609
5610 let server = this
5611 .read_with(&mut cx, |project, _| {
5612 project.language_server_for_id(server_id)
5613 })
5614 .ok()
5615 .flatten();
5616 let Some(server) = server else {
5617 continue;
5618 };
5619
5620 did_resolve = true;
5621 Self::resolve_completion_documentation_local(
5622 server,
5623 completions.clone(),
5624 completion_index,
5625 completion,
5626 language_registry.clone(),
5627 )
5628 .await;
5629 }
5630 }
5631
5632 Ok(did_resolve)
5633 })
5634 }
5635
5636 async fn resolve_completion_documentation_local(
5637 server: Arc<lsp::LanguageServer>,
5638 completions: Arc<RwLock<Box<[Completion]>>>,
5639 completion_index: usize,
5640 completion: lsp::CompletionItem,
5641 language_registry: Arc<LanguageRegistry>,
5642 ) {
5643 let can_resolve = server
5644 .capabilities()
5645 .completion_provider
5646 .as_ref()
5647 .and_then(|options| options.resolve_provider)
5648 .unwrap_or(false);
5649 if !can_resolve {
5650 return;
5651 }
5652
5653 let request = server.request::<lsp::request::ResolveCompletionItem>(completion);
5654 let Some(completion_item) = request.await.log_err() else {
5655 return;
5656 };
5657
5658 if let Some(lsp_documentation) = completion_item.documentation {
5659 let documentation = language::prepare_completion_documentation(
5660 &lsp_documentation,
5661 &language_registry,
5662 None, // TODO: Try to reasonably work out which language the completion is for
5663 )
5664 .await;
5665
5666 let mut completions = completions.write();
5667 let completion = &mut completions[completion_index];
5668 completion.documentation = Some(documentation);
5669 } else {
5670 let mut completions = completions.write();
5671 let completion = &mut completions[completion_index];
5672 completion.documentation = Some(Documentation::Undocumented);
5673 }
5674 }
5675
5676 async fn resolve_completion_documentation_remote(
5677 project_id: u64,
5678 server_id: LanguageServerId,
5679 completions: Arc<RwLock<Box<[Completion]>>>,
5680 completion_index: usize,
5681 completion: lsp::CompletionItem,
5682 client: Arc<Client>,
5683 language_registry: Arc<LanguageRegistry>,
5684 ) {
5685 let request = proto::ResolveCompletionDocumentation {
5686 project_id,
5687 language_server_id: server_id.0 as u64,
5688 lsp_completion: serde_json::to_string(&completion).unwrap().into_bytes(),
5689 };
5690
5691 let Some(response) = client
5692 .request(request)
5693 .await
5694 .context("completion documentation resolve proto request")
5695 .log_err()
5696 else {
5697 return;
5698 };
5699
5700 if response.text.is_empty() {
5701 let mut completions = completions.write();
5702 let completion = &mut completions[completion_index];
5703 completion.documentation = Some(Documentation::Undocumented);
5704 }
5705
5706 let documentation = if response.is_markdown {
5707 Documentation::MultiLineMarkdown(
5708 markdown::parse_markdown(&response.text, &language_registry, None).await,
5709 )
5710 } else if response.text.lines().count() <= 1 {
5711 Documentation::SingleLine(response.text)
5712 } else {
5713 Documentation::MultiLinePlainText(response.text)
5714 };
5715
5716 let mut completions = completions.write();
5717 let completion = &mut completions[completion_index];
5718 completion.documentation = Some(documentation);
5719 }
5720
5721 pub fn apply_additional_edits_for_completion(
5722 &self,
5723 buffer_handle: Model<Buffer>,
5724 completion: Completion,
5725 push_to_history: bool,
5726 cx: &mut ModelContext<Self>,
5727 ) -> Task<Result<Option<Transaction>>> {
5728 let buffer = buffer_handle.read(cx);
5729 let buffer_id = buffer.remote_id();
5730
5731 if self.is_local() {
5732 let server_id = completion.server_id;
5733 let lang_server = match self.language_server_for_buffer(buffer, server_id, cx) {
5734 Some((_, server)) => server.clone(),
5735 _ => return Task::ready(Ok(Default::default())),
5736 };
5737
5738 cx.spawn(move |this, mut cx| async move {
5739 let can_resolve = lang_server
5740 .capabilities()
5741 .completion_provider
5742 .as_ref()
5743 .and_then(|options| options.resolve_provider)
5744 .unwrap_or(false);
5745 let additional_text_edits = if can_resolve {
5746 lang_server
5747 .request::<lsp::request::ResolveCompletionItem>(completion.lsp_completion)
5748 .await?
5749 .additional_text_edits
5750 } else {
5751 completion.lsp_completion.additional_text_edits
5752 };
5753 if let Some(edits) = additional_text_edits {
5754 let edits = this
5755 .update(&mut cx, |this, cx| {
5756 this.edits_from_lsp(
5757 &buffer_handle,
5758 edits,
5759 lang_server.server_id(),
5760 None,
5761 cx,
5762 )
5763 })?
5764 .await?;
5765
5766 buffer_handle.update(&mut cx, |buffer, cx| {
5767 buffer.finalize_last_transaction();
5768 buffer.start_transaction();
5769
5770 for (range, text) in edits {
5771 let primary = &completion.old_range;
5772 let start_within = primary.start.cmp(&range.start, buffer).is_le()
5773 && primary.end.cmp(&range.start, buffer).is_ge();
5774 let end_within = range.start.cmp(&primary.end, buffer).is_le()
5775 && range.end.cmp(&primary.end, buffer).is_ge();
5776
5777 //Skip additional edits which overlap with the primary completion edit
5778 //https://github.com/zed-industries/zed/pull/1871
5779 if !start_within && !end_within {
5780 buffer.edit([(range, text)], None, cx);
5781 }
5782 }
5783
5784 let transaction = if buffer.end_transaction(cx).is_some() {
5785 let transaction = buffer.finalize_last_transaction().unwrap().clone();
5786 if !push_to_history {
5787 buffer.forget_transaction(transaction.id);
5788 }
5789 Some(transaction)
5790 } else {
5791 None
5792 };
5793 Ok(transaction)
5794 })?
5795 } else {
5796 Ok(None)
5797 }
5798 })
5799 } else if let Some(project_id) = self.remote_id() {
5800 let client = self.client.clone();
5801 cx.spawn(move |_, mut cx| async move {
5802 let response = client
5803 .request(proto::ApplyCompletionAdditionalEdits {
5804 project_id,
5805 buffer_id: buffer_id.into(),
5806 completion: Some(Self::serialize_completion(&CoreCompletion {
5807 old_range: completion.old_range,
5808 new_text: completion.new_text,
5809 server_id: completion.server_id,
5810 lsp_completion: completion.lsp_completion,
5811 })),
5812 })
5813 .await?;
5814
5815 if let Some(transaction) = response.transaction {
5816 let transaction = language::proto::deserialize_transaction(transaction)?;
5817 buffer_handle
5818 .update(&mut cx, |buffer, _| {
5819 buffer.wait_for_edits(transaction.edit_ids.iter().copied())
5820 })?
5821 .await?;
5822 if push_to_history {
5823 buffer_handle.update(&mut cx, |buffer, _| {
5824 buffer.push_transaction(transaction.clone(), Instant::now());
5825 })?;
5826 }
5827 Ok(Some(transaction))
5828 } else {
5829 Ok(None)
5830 }
5831 })
5832 } else {
5833 Task::ready(Err(anyhow!("project does not have a remote id")))
5834 }
5835 }
5836
5837 fn code_actions_impl(
5838 &mut self,
5839 buffer_handle: &Model<Buffer>,
5840 range: Range<Anchor>,
5841 cx: &mut ModelContext<Self>,
5842 ) -> Task<Vec<CodeAction>> {
5843 if self.is_local() {
5844 let all_actions_task = self.request_multiple_lsp_locally(
5845 &buffer_handle,
5846 Some(range.start),
5847 GetCodeActions::supports_code_actions,
5848 GetCodeActions {
5849 range: range.clone(),
5850 kinds: None,
5851 },
5852 cx,
5853 );
5854 cx.spawn(|_, _| async move { all_actions_task.await.into_iter().flatten().collect() })
5855 } else if let Some(project_id) = self.remote_id() {
5856 let request_task = self.client().request(proto::MultiLspQuery {
5857 buffer_id: buffer_handle.read(cx).remote_id().into(),
5858 version: serialize_version(&buffer_handle.read(cx).version()),
5859 project_id,
5860 strategy: Some(proto::multi_lsp_query::Strategy::All(
5861 proto::AllLanguageServers {},
5862 )),
5863 request: Some(proto::multi_lsp_query::Request::GetCodeActions(
5864 GetCodeActions {
5865 range: range.clone(),
5866 kinds: None,
5867 }
5868 .to_proto(project_id, buffer_handle.read(cx)),
5869 )),
5870 });
5871 let buffer = buffer_handle.clone();
5872 cx.spawn(|weak_project, cx| async move {
5873 let Some(project) = weak_project.upgrade() else {
5874 return Vec::new();
5875 };
5876 join_all(
5877 request_task
5878 .await
5879 .log_err()
5880 .map(|response| response.responses)
5881 .unwrap_or_default()
5882 .into_iter()
5883 .filter_map(|lsp_response| match lsp_response.response? {
5884 proto::lsp_response::Response::GetCodeActionsResponse(response) => {
5885 Some(response)
5886 }
5887 unexpected => {
5888 debug_panic!("Unexpected response: {unexpected:?}");
5889 None
5890 }
5891 })
5892 .map(|code_actions_response| {
5893 let response = GetCodeActions {
5894 range: range.clone(),
5895 kinds: None,
5896 }
5897 .response_from_proto(
5898 code_actions_response,
5899 project.clone(),
5900 buffer.clone(),
5901 cx.clone(),
5902 );
5903 async move { response.await.log_err().unwrap_or_default() }
5904 }),
5905 )
5906 .await
5907 .into_iter()
5908 .flatten()
5909 .collect()
5910 })
5911 } else {
5912 log::error!("cannot fetch actions: project does not have a remote id");
5913 Task::ready(Vec::new())
5914 }
5915 }
5916
5917 pub fn code_actions<T: Clone + ToOffset>(
5918 &mut self,
5919 buffer_handle: &Model<Buffer>,
5920 range: Range<T>,
5921 cx: &mut ModelContext<Self>,
5922 ) -> Task<Vec<CodeAction>> {
5923 let buffer = buffer_handle.read(cx);
5924 let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
5925 self.code_actions_impl(buffer_handle, range, cx)
5926 }
5927
5928 pub fn apply_code_action(
5929 &self,
5930 buffer_handle: Model<Buffer>,
5931 mut action: CodeAction,
5932 push_to_history: bool,
5933 cx: &mut ModelContext<Self>,
5934 ) -> Task<Result<ProjectTransaction>> {
5935 if self.is_local() {
5936 let buffer = buffer_handle.read(cx);
5937 let (lsp_adapter, lang_server) = if let Some((adapter, server)) =
5938 self.language_server_for_buffer(buffer, action.server_id, cx)
5939 {
5940 (adapter.clone(), server.clone())
5941 } else {
5942 return Task::ready(Ok(Default::default()));
5943 };
5944 cx.spawn(move |this, mut cx| async move {
5945 Self::try_resolve_code_action(&lang_server, &mut action)
5946 .await
5947 .context("resolving a code action")?;
5948 if let Some(edit) = action.lsp_action.edit {
5949 if edit.changes.is_some() || edit.document_changes.is_some() {
5950 return Self::deserialize_workspace_edit(
5951 this.upgrade().ok_or_else(|| anyhow!("no app present"))?,
5952 edit,
5953 push_to_history,
5954 lsp_adapter.clone(),
5955 lang_server.clone(),
5956 &mut cx,
5957 )
5958 .await;
5959 }
5960 }
5961
5962 if let Some(command) = action.lsp_action.command {
5963 this.update(&mut cx, |this, _| {
5964 this.last_workspace_edits_by_language_server
5965 .remove(&lang_server.server_id());
5966 })?;
5967
5968 let result = lang_server
5969 .request::<lsp::request::ExecuteCommand>(lsp::ExecuteCommandParams {
5970 command: command.command,
5971 arguments: command.arguments.unwrap_or_default(),
5972 ..Default::default()
5973 })
5974 .await;
5975
5976 if let Err(err) = result {
5977 // TODO: LSP ERROR
5978 return Err(err);
5979 }
5980
5981 return this.update(&mut cx, |this, _| {
5982 this.last_workspace_edits_by_language_server
5983 .remove(&lang_server.server_id())
5984 .unwrap_or_default()
5985 });
5986 }
5987
5988 Ok(ProjectTransaction::default())
5989 })
5990 } else if let Some(project_id) = self.remote_id() {
5991 let client = self.client.clone();
5992 let request = proto::ApplyCodeAction {
5993 project_id,
5994 buffer_id: buffer_handle.read(cx).remote_id().into(),
5995 action: Some(Self::serialize_code_action(&action)),
5996 };
5997 cx.spawn(move |this, mut cx| async move {
5998 let response = client
5999 .request(request)
6000 .await?
6001 .transaction
6002 .ok_or_else(|| anyhow!("missing transaction"))?;
6003 this.update(&mut cx, |this, cx| {
6004 this.deserialize_project_transaction(response, push_to_history, cx)
6005 })?
6006 .await
6007 })
6008 } else {
6009 Task::ready(Err(anyhow!("project does not have a remote id")))
6010 }
6011 }
6012
6013 fn apply_on_type_formatting(
6014 &self,
6015 buffer: Model<Buffer>,
6016 position: Anchor,
6017 trigger: String,
6018 cx: &mut ModelContext<Self>,
6019 ) -> Task<Result<Option<Transaction>>> {
6020 if self.is_local() {
6021 cx.spawn(move |this, mut cx| async move {
6022 // Do not allow multiple concurrent formatting requests for the
6023 // same buffer.
6024 this.update(&mut cx, |this, cx| {
6025 this.buffers_being_formatted
6026 .insert(buffer.read(cx).remote_id())
6027 })?;
6028
6029 let _cleanup = defer({
6030 let this = this.clone();
6031 let mut cx = cx.clone();
6032 let closure_buffer = buffer.clone();
6033 move || {
6034 this.update(&mut cx, |this, cx| {
6035 this.buffers_being_formatted
6036 .remove(&closure_buffer.read(cx).remote_id());
6037 })
6038 .ok();
6039 }
6040 });
6041
6042 buffer
6043 .update(&mut cx, |buffer, _| {
6044 buffer.wait_for_edits(Some(position.timestamp))
6045 })?
6046 .await?;
6047 this.update(&mut cx, |this, cx| {
6048 let position = position.to_point_utf16(buffer.read(cx));
6049 this.on_type_format(buffer, position, trigger, false, cx)
6050 })?
6051 .await
6052 })
6053 } else if let Some(project_id) = self.remote_id() {
6054 let client = self.client.clone();
6055 let request = proto::OnTypeFormatting {
6056 project_id,
6057 buffer_id: buffer.read(cx).remote_id().into(),
6058 position: Some(serialize_anchor(&position)),
6059 trigger,
6060 version: serialize_version(&buffer.read(cx).version()),
6061 };
6062 cx.spawn(move |_, _| async move {
6063 client
6064 .request(request)
6065 .await?
6066 .transaction
6067 .map(language::proto::deserialize_transaction)
6068 .transpose()
6069 })
6070 } else {
6071 Task::ready(Err(anyhow!("project does not have a remote id")))
6072 }
6073 }
6074
6075 async fn deserialize_edits(
6076 this: Model<Self>,
6077 buffer_to_edit: Model<Buffer>,
6078 edits: Vec<lsp::TextEdit>,
6079 push_to_history: bool,
6080 _: Arc<CachedLspAdapter>,
6081 language_server: Arc<LanguageServer>,
6082 cx: &mut AsyncAppContext,
6083 ) -> Result<Option<Transaction>> {
6084 let edits = this
6085 .update(cx, |this, cx| {
6086 this.edits_from_lsp(
6087 &buffer_to_edit,
6088 edits,
6089 language_server.server_id(),
6090 None,
6091 cx,
6092 )
6093 })?
6094 .await?;
6095
6096 let transaction = buffer_to_edit.update(cx, |buffer, cx| {
6097 buffer.finalize_last_transaction();
6098 buffer.start_transaction();
6099 for (range, text) in edits {
6100 buffer.edit([(range, text)], None, cx);
6101 }
6102
6103 if buffer.end_transaction(cx).is_some() {
6104 let transaction = buffer.finalize_last_transaction().unwrap().clone();
6105 if !push_to_history {
6106 buffer.forget_transaction(transaction.id);
6107 }
6108 Some(transaction)
6109 } else {
6110 None
6111 }
6112 })?;
6113
6114 Ok(transaction)
6115 }
6116
6117 async fn deserialize_workspace_edit(
6118 this: Model<Self>,
6119 edit: lsp::WorkspaceEdit,
6120 push_to_history: bool,
6121 lsp_adapter: Arc<CachedLspAdapter>,
6122 language_server: Arc<LanguageServer>,
6123 cx: &mut AsyncAppContext,
6124 ) -> Result<ProjectTransaction> {
6125 let fs = this.update(cx, |this, _| this.fs.clone())?;
6126 let mut operations = Vec::new();
6127 if let Some(document_changes) = edit.document_changes {
6128 match document_changes {
6129 lsp::DocumentChanges::Edits(edits) => {
6130 operations.extend(edits.into_iter().map(lsp::DocumentChangeOperation::Edit))
6131 }
6132 lsp::DocumentChanges::Operations(ops) => operations = ops,
6133 }
6134 } else if let Some(changes) = edit.changes {
6135 operations.extend(changes.into_iter().map(|(uri, edits)| {
6136 lsp::DocumentChangeOperation::Edit(lsp::TextDocumentEdit {
6137 text_document: lsp::OptionalVersionedTextDocumentIdentifier {
6138 uri,
6139 version: None,
6140 },
6141 edits: edits.into_iter().map(OneOf::Left).collect(),
6142 })
6143 }));
6144 }
6145
6146 let mut project_transaction = ProjectTransaction::default();
6147 for operation in operations {
6148 match operation {
6149 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Create(op)) => {
6150 let abs_path = op
6151 .uri
6152 .to_file_path()
6153 .map_err(|_| anyhow!("can't convert URI to path"))?;
6154
6155 if let Some(parent_path) = abs_path.parent() {
6156 fs.create_dir(parent_path).await?;
6157 }
6158 if abs_path.ends_with("/") {
6159 fs.create_dir(&abs_path).await?;
6160 } else {
6161 fs.create_file(
6162 &abs_path,
6163 op.options
6164 .map(|options| fs::CreateOptions {
6165 overwrite: options.overwrite.unwrap_or(false),
6166 ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
6167 })
6168 .unwrap_or_default(),
6169 )
6170 .await?;
6171 }
6172 }
6173
6174 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Rename(op)) => {
6175 let source_abs_path = op
6176 .old_uri
6177 .to_file_path()
6178 .map_err(|_| anyhow!("can't convert URI to path"))?;
6179 let target_abs_path = op
6180 .new_uri
6181 .to_file_path()
6182 .map_err(|_| anyhow!("can't convert URI to path"))?;
6183 fs.rename(
6184 &source_abs_path,
6185 &target_abs_path,
6186 op.options
6187 .map(|options| fs::RenameOptions {
6188 overwrite: options.overwrite.unwrap_or(false),
6189 ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
6190 })
6191 .unwrap_or_default(),
6192 )
6193 .await?;
6194 }
6195
6196 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Delete(op)) => {
6197 let abs_path = op
6198 .uri
6199 .to_file_path()
6200 .map_err(|_| anyhow!("can't convert URI to path"))?;
6201 let options = op
6202 .options
6203 .map(|options| fs::RemoveOptions {
6204 recursive: options.recursive.unwrap_or(false),
6205 ignore_if_not_exists: options.ignore_if_not_exists.unwrap_or(false),
6206 })
6207 .unwrap_or_default();
6208 if abs_path.ends_with("/") {
6209 fs.remove_dir(&abs_path, options).await?;
6210 } else {
6211 fs.remove_file(&abs_path, options).await?;
6212 }
6213 }
6214
6215 lsp::DocumentChangeOperation::Edit(op) => {
6216 let buffer_to_edit = this
6217 .update(cx, |this, cx| {
6218 this.open_local_buffer_via_lsp(
6219 op.text_document.uri,
6220 language_server.server_id(),
6221 lsp_adapter.name.clone(),
6222 cx,
6223 )
6224 })?
6225 .await?;
6226
6227 let edits = this
6228 .update(cx, |this, cx| {
6229 let edits = op.edits.into_iter().map(|edit| match edit {
6230 OneOf::Left(edit) => edit,
6231 OneOf::Right(edit) => edit.text_edit,
6232 });
6233 this.edits_from_lsp(
6234 &buffer_to_edit,
6235 edits,
6236 language_server.server_id(),
6237 op.text_document.version,
6238 cx,
6239 )
6240 })?
6241 .await?;
6242
6243 let transaction = buffer_to_edit.update(cx, |buffer, cx| {
6244 buffer.finalize_last_transaction();
6245 buffer.start_transaction();
6246 for (range, text) in edits {
6247 buffer.edit([(range, text)], None, cx);
6248 }
6249 let transaction = if buffer.end_transaction(cx).is_some() {
6250 let transaction = buffer.finalize_last_transaction().unwrap().clone();
6251 if !push_to_history {
6252 buffer.forget_transaction(transaction.id);
6253 }
6254 Some(transaction)
6255 } else {
6256 None
6257 };
6258
6259 transaction
6260 })?;
6261 if let Some(transaction) = transaction {
6262 project_transaction.0.insert(buffer_to_edit, transaction);
6263 }
6264 }
6265 }
6266 }
6267
6268 Ok(project_transaction)
6269 }
6270
6271 fn prepare_rename_impl(
6272 &mut self,
6273 buffer: Model<Buffer>,
6274 position: PointUtf16,
6275 cx: &mut ModelContext<Self>,
6276 ) -> Task<Result<Option<Range<Anchor>>>> {
6277 self.request_lsp(
6278 buffer,
6279 LanguageServerToQuery::Primary,
6280 PrepareRename { position },
6281 cx,
6282 )
6283 }
6284 pub fn prepare_rename<T: ToPointUtf16>(
6285 &mut self,
6286 buffer: Model<Buffer>,
6287 position: T,
6288 cx: &mut ModelContext<Self>,
6289 ) -> Task<Result<Option<Range<Anchor>>>> {
6290 let position = position.to_point_utf16(buffer.read(cx));
6291 self.prepare_rename_impl(buffer, position, cx)
6292 }
6293
6294 fn perform_rename_impl(
6295 &mut self,
6296 buffer: Model<Buffer>,
6297 position: PointUtf16,
6298 new_name: String,
6299 push_to_history: bool,
6300 cx: &mut ModelContext<Self>,
6301 ) -> Task<Result<ProjectTransaction>> {
6302 let position = position.to_point_utf16(buffer.read(cx));
6303 self.request_lsp(
6304 buffer,
6305 LanguageServerToQuery::Primary,
6306 PerformRename {
6307 position,
6308 new_name,
6309 push_to_history,
6310 },
6311 cx,
6312 )
6313 }
6314 pub fn perform_rename<T: ToPointUtf16>(
6315 &mut self,
6316 buffer: Model<Buffer>,
6317 position: T,
6318 new_name: String,
6319 push_to_history: bool,
6320 cx: &mut ModelContext<Self>,
6321 ) -> Task<Result<ProjectTransaction>> {
6322 let position = position.to_point_utf16(buffer.read(cx));
6323 self.perform_rename_impl(buffer, position, new_name, push_to_history, cx)
6324 }
6325
6326 pub fn on_type_format_impl(
6327 &mut self,
6328 buffer: Model<Buffer>,
6329 position: PointUtf16,
6330 trigger: String,
6331 push_to_history: bool,
6332 cx: &mut ModelContext<Self>,
6333 ) -> Task<Result<Option<Transaction>>> {
6334 let tab_size = buffer.update(cx, |buffer, cx| {
6335 language_settings(buffer.language_at(position).as_ref(), buffer.file(), cx).tab_size
6336 });
6337 self.request_lsp(
6338 buffer.clone(),
6339 LanguageServerToQuery::Primary,
6340 OnTypeFormatting {
6341 position,
6342 trigger,
6343 options: lsp_command::lsp_formatting_options(tab_size.get()).into(),
6344 push_to_history,
6345 },
6346 cx,
6347 )
6348 }
6349
6350 pub fn on_type_format<T: ToPointUtf16>(
6351 &mut self,
6352 buffer: Model<Buffer>,
6353 position: T,
6354 trigger: String,
6355 push_to_history: bool,
6356 cx: &mut ModelContext<Self>,
6357 ) -> Task<Result<Option<Transaction>>> {
6358 let position = position.to_point_utf16(buffer.read(cx));
6359 self.on_type_format_impl(buffer, position, trigger, push_to_history, cx)
6360 }
6361
6362 pub fn inlay_hints<T: ToOffset>(
6363 &mut self,
6364 buffer_handle: Model<Buffer>,
6365 range: Range<T>,
6366 cx: &mut ModelContext<Self>,
6367 ) -> Task<anyhow::Result<Vec<InlayHint>>> {
6368 let buffer = buffer_handle.read(cx);
6369 let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
6370 self.inlay_hints_impl(buffer_handle, range, cx)
6371 }
6372 fn inlay_hints_impl(
6373 &mut self,
6374 buffer_handle: Model<Buffer>,
6375 range: Range<Anchor>,
6376 cx: &mut ModelContext<Self>,
6377 ) -> Task<anyhow::Result<Vec<InlayHint>>> {
6378 let buffer = buffer_handle.read(cx);
6379 let range_start = range.start;
6380 let range_end = range.end;
6381 let buffer_id = buffer.remote_id().into();
6382 let lsp_request = InlayHints { range };
6383
6384 if self.is_local() {
6385 let lsp_request_task = self.request_lsp(
6386 buffer_handle.clone(),
6387 LanguageServerToQuery::Primary,
6388 lsp_request,
6389 cx,
6390 );
6391 cx.spawn(move |_, mut cx| async move {
6392 buffer_handle
6393 .update(&mut cx, |buffer, _| {
6394 buffer.wait_for_edits(vec![range_start.timestamp, range_end.timestamp])
6395 })?
6396 .await
6397 .context("waiting for inlay hint request range edits")?;
6398 lsp_request_task.await.context("inlay hints LSP request")
6399 })
6400 } else if let Some(project_id) = self.remote_id() {
6401 let client = self.client.clone();
6402 let request = proto::InlayHints {
6403 project_id,
6404 buffer_id,
6405 start: Some(serialize_anchor(&range_start)),
6406 end: Some(serialize_anchor(&range_end)),
6407 version: serialize_version(&buffer_handle.read(cx).version()),
6408 };
6409 cx.spawn(move |project, cx| async move {
6410 let response = client
6411 .request(request)
6412 .await
6413 .context("inlay hints proto request")?;
6414 LspCommand::response_from_proto(
6415 lsp_request,
6416 response,
6417 project.upgrade().ok_or_else(|| anyhow!("No project"))?,
6418 buffer_handle.clone(),
6419 cx.clone(),
6420 )
6421 .await
6422 .context("inlay hints proto response conversion")
6423 })
6424 } else {
6425 Task::ready(Err(anyhow!("project does not have a remote id")))
6426 }
6427 }
6428
6429 pub fn resolve_inlay_hint(
6430 &self,
6431 hint: InlayHint,
6432 buffer_handle: Model<Buffer>,
6433 server_id: LanguageServerId,
6434 cx: &mut ModelContext<Self>,
6435 ) -> Task<anyhow::Result<InlayHint>> {
6436 if self.is_local() {
6437 let buffer = buffer_handle.read(cx);
6438 let (_, lang_server) = if let Some((adapter, server)) =
6439 self.language_server_for_buffer(buffer, server_id, cx)
6440 {
6441 (adapter.clone(), server.clone())
6442 } else {
6443 return Task::ready(Ok(hint));
6444 };
6445 if !InlayHints::can_resolve_inlays(lang_server.capabilities()) {
6446 return Task::ready(Ok(hint));
6447 }
6448
6449 let buffer_snapshot = buffer.snapshot();
6450 cx.spawn(move |_, mut cx| async move {
6451 let resolve_task = lang_server.request::<lsp::request::InlayHintResolveRequest>(
6452 InlayHints::project_to_lsp_hint(hint, &buffer_snapshot),
6453 );
6454 let resolved_hint = resolve_task
6455 .await
6456 .context("inlay hint resolve LSP request")?;
6457 let resolved_hint = InlayHints::lsp_to_project_hint(
6458 resolved_hint,
6459 &buffer_handle,
6460 server_id,
6461 ResolveState::Resolved,
6462 false,
6463 &mut cx,
6464 )
6465 .await?;
6466 Ok(resolved_hint)
6467 })
6468 } else if let Some(project_id) = self.remote_id() {
6469 let client = self.client.clone();
6470 let request = proto::ResolveInlayHint {
6471 project_id,
6472 buffer_id: buffer_handle.read(cx).remote_id().into(),
6473 language_server_id: server_id.0 as u64,
6474 hint: Some(InlayHints::project_to_proto_hint(hint.clone())),
6475 };
6476 cx.spawn(move |_, _| async move {
6477 let response = client
6478 .request(request)
6479 .await
6480 .context("inlay hints proto request")?;
6481 match response.hint {
6482 Some(resolved_hint) => InlayHints::proto_to_project_hint(resolved_hint)
6483 .context("inlay hints proto resolve response conversion"),
6484 None => Ok(hint),
6485 }
6486 })
6487 } else {
6488 Task::ready(Err(anyhow!("project does not have a remote id")))
6489 }
6490 }
6491
6492 #[allow(clippy::type_complexity)]
6493 pub fn search(
6494 &self,
6495 query: SearchQuery,
6496 cx: &mut ModelContext<Self>,
6497 ) -> Receiver<SearchResult> {
6498 if self.is_local() {
6499 self.search_local(query, cx)
6500 } else if let Some(project_id) = self.remote_id() {
6501 let (tx, rx) = smol::channel::unbounded();
6502 let request = self.client.request(query.to_proto(project_id));
6503 cx.spawn(move |this, mut cx| async move {
6504 let response = request.await?;
6505 let mut result = HashMap::default();
6506 for location in response.locations {
6507 let buffer_id = BufferId::new(location.buffer_id)?;
6508 let target_buffer = this
6509 .update(&mut cx, |this, cx| {
6510 this.wait_for_remote_buffer(buffer_id, cx)
6511 })?
6512 .await?;
6513 let start = location
6514 .start
6515 .and_then(deserialize_anchor)
6516 .ok_or_else(|| anyhow!("missing target start"))?;
6517 let end = location
6518 .end
6519 .and_then(deserialize_anchor)
6520 .ok_or_else(|| anyhow!("missing target end"))?;
6521 result
6522 .entry(target_buffer)
6523 .or_insert(Vec::new())
6524 .push(start..end)
6525 }
6526 for (buffer, ranges) in result {
6527 let _ = tx.send(SearchResult::Buffer { buffer, ranges }).await;
6528 }
6529
6530 if response.limit_reached {
6531 let _ = tx.send(SearchResult::LimitReached).await;
6532 }
6533
6534 Result::<(), anyhow::Error>::Ok(())
6535 })
6536 .detach_and_log_err(cx);
6537 rx
6538 } else {
6539 unimplemented!();
6540 }
6541 }
6542
6543 pub fn search_local(
6544 &self,
6545 query: SearchQuery,
6546 cx: &mut ModelContext<Self>,
6547 ) -> Receiver<SearchResult> {
6548 // Local search is split into several phases.
6549 // TL;DR is that we do 2 passes; initial pass to pick files which contain at least one match
6550 // and the second phase that finds positions of all the matches found in the candidate files.
6551 // The Receiver obtained from this function returns matches sorted by buffer path. Files without a buffer path are reported first.
6552 //
6553 // It gets a bit hairy though, because we must account for files that do not have a persistent representation
6554 // on FS. Namely, if you have an untitled buffer or unsaved changes in a buffer, we want to scan that too.
6555 //
6556 // 1. We initialize a queue of match candidates and feed all opened buffers into it (== unsaved files / untitled buffers).
6557 // 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
6558 // of FS version for that file altogether - after all, what we have in memory is more up-to-date than what's in FS.
6559 // 2. At this point, we have a list of all potentially matching buffers/files.
6560 // We sort that list by buffer path - this list is retained for later use.
6561 // We ensure that all buffers are now opened and available in project.
6562 // 3. We run a scan over all the candidate buffers on multiple background threads.
6563 // We cannot assume that there will even be a match - while at least one match
6564 // is guaranteed for files obtained from FS, the buffers we got from memory (unsaved files/unnamed buffers) might not have a match at all.
6565 // There is also an auxiliary background thread responsible for result gathering.
6566 // 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),
6567 // it keeps it around. It reports matches in sorted order, though it accepts them in unsorted order as well.
6568 // 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
6569 // entry - which might already be available thanks to out-of-order processing.
6570 //
6571 // We could also report matches fully out-of-order, without maintaining a sorted list of matching paths.
6572 // 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.
6573 // 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
6574 // in face of constantly updating list of sorted matches.
6575 // Meanwhile, this implementation offers index stability, since the matches are already reported in a sorted order.
6576 let snapshots = self
6577 .visible_worktrees(cx)
6578 .filter_map(|tree| {
6579 let tree = tree.read(cx).as_local()?;
6580 Some(tree.snapshot())
6581 })
6582 .collect::<Vec<_>>();
6583 let include_root = snapshots.len() > 1;
6584
6585 let background = cx.background_executor().clone();
6586 let path_count: usize = snapshots
6587 .iter()
6588 .map(|s| {
6589 if query.include_ignored() {
6590 s.file_count()
6591 } else {
6592 s.visible_file_count()
6593 }
6594 })
6595 .sum();
6596 if path_count == 0 {
6597 let (_, rx) = smol::channel::bounded(1024);
6598 return rx;
6599 }
6600 let workers = background.num_cpus().min(path_count);
6601 let (matching_paths_tx, matching_paths_rx) = smol::channel::bounded(1024);
6602 let mut unnamed_files = vec![];
6603 let opened_buffers = self
6604 .opened_buffers
6605 .iter()
6606 .filter_map(|(_, b)| {
6607 let buffer = b.upgrade()?;
6608 let (is_ignored, snapshot) = buffer.update(cx, |buffer, cx| {
6609 let is_ignored = buffer
6610 .project_path(cx)
6611 .and_then(|path| self.entry_for_path(&path, cx))
6612 .map_or(false, |entry| entry.is_ignored);
6613 (is_ignored, buffer.snapshot())
6614 });
6615 if is_ignored && !query.include_ignored() {
6616 return None;
6617 } else if let Some(file) = snapshot.file() {
6618 let matched_path = if include_root {
6619 query.file_matches(Some(&file.full_path(cx)))
6620 } else {
6621 query.file_matches(Some(file.path()))
6622 };
6623
6624 if matched_path {
6625 Some((file.path().clone(), (buffer, snapshot)))
6626 } else {
6627 None
6628 }
6629 } else {
6630 unnamed_files.push(buffer);
6631 None
6632 }
6633 })
6634 .collect();
6635 cx.background_executor()
6636 .spawn(Self::background_search(
6637 unnamed_files,
6638 opened_buffers,
6639 cx.background_executor().clone(),
6640 self.fs.clone(),
6641 workers,
6642 query.clone(),
6643 include_root,
6644 path_count,
6645 snapshots,
6646 matching_paths_tx,
6647 ))
6648 .detach();
6649
6650 let (result_tx, result_rx) = smol::channel::bounded(1024);
6651
6652 cx.spawn(|this, mut cx| async move {
6653 const MAX_SEARCH_RESULT_FILES: usize = 5_000;
6654 const MAX_SEARCH_RESULT_RANGES: usize = 10_000;
6655
6656 let mut matching_paths = matching_paths_rx
6657 .take(MAX_SEARCH_RESULT_FILES + 1)
6658 .collect::<Vec<_>>()
6659 .await;
6660 let mut limit_reached = if matching_paths.len() > MAX_SEARCH_RESULT_FILES {
6661 matching_paths.pop();
6662 true
6663 } else {
6664 false
6665 };
6666 matching_paths.sort_by_key(|candidate| (candidate.is_ignored(), candidate.path()));
6667
6668 let mut range_count = 0;
6669 let query = Arc::new(query);
6670
6671 // Now that we know what paths match the query, we will load at most
6672 // 64 buffers at a time to avoid overwhelming the main thread. For each
6673 // opened buffer, we will spawn a background task that retrieves all the
6674 // ranges in the buffer matched by the query.
6675 'outer: for matching_paths_chunk in matching_paths.chunks(64) {
6676 let mut chunk_results = Vec::new();
6677 for matching_path in matching_paths_chunk {
6678 let query = query.clone();
6679 let buffer = match matching_path {
6680 SearchMatchCandidate::OpenBuffer { buffer, .. } => {
6681 Task::ready(Ok(buffer.clone()))
6682 }
6683 SearchMatchCandidate::Path {
6684 worktree_id, path, ..
6685 } => this.update(&mut cx, |this, cx| {
6686 this.open_buffer((*worktree_id, path.clone()), cx)
6687 })?,
6688 };
6689
6690 chunk_results.push(cx.spawn(|cx| async move {
6691 let buffer = buffer.await?;
6692 let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot())?;
6693 let ranges = cx
6694 .background_executor()
6695 .spawn(async move {
6696 query
6697 .search(&snapshot, None)
6698 .await
6699 .iter()
6700 .map(|range| {
6701 snapshot.anchor_before(range.start)
6702 ..snapshot.anchor_after(range.end)
6703 })
6704 .collect::<Vec<_>>()
6705 })
6706 .await;
6707 anyhow::Ok((buffer, ranges))
6708 }));
6709 }
6710
6711 let chunk_results = futures::future::join_all(chunk_results).await;
6712 for result in chunk_results {
6713 if let Some((buffer, ranges)) = result.log_err() {
6714 range_count += ranges.len();
6715 result_tx
6716 .send(SearchResult::Buffer { buffer, ranges })
6717 .await?;
6718 if range_count > MAX_SEARCH_RESULT_RANGES {
6719 limit_reached = true;
6720 break 'outer;
6721 }
6722 }
6723 }
6724 }
6725
6726 if limit_reached {
6727 result_tx.send(SearchResult::LimitReached).await?;
6728 }
6729
6730 anyhow::Ok(())
6731 })
6732 .detach();
6733
6734 result_rx
6735 }
6736
6737 /// Pick paths that might potentially contain a match of a given search query.
6738 #[allow(clippy::too_many_arguments)]
6739 async fn background_search(
6740 unnamed_buffers: Vec<Model<Buffer>>,
6741 opened_buffers: HashMap<Arc<Path>, (Model<Buffer>, BufferSnapshot)>,
6742 executor: BackgroundExecutor,
6743 fs: Arc<dyn Fs>,
6744 workers: usize,
6745 query: SearchQuery,
6746 include_root: bool,
6747 path_count: usize,
6748 snapshots: Vec<LocalSnapshot>,
6749 matching_paths_tx: Sender<SearchMatchCandidate>,
6750 ) {
6751 let fs = &fs;
6752 let query = &query;
6753 let matching_paths_tx = &matching_paths_tx;
6754 let snapshots = &snapshots;
6755 for buffer in unnamed_buffers {
6756 matching_paths_tx
6757 .send(SearchMatchCandidate::OpenBuffer {
6758 buffer: buffer.clone(),
6759 path: None,
6760 })
6761 .await
6762 .log_err();
6763 }
6764 for (path, (buffer, _)) in opened_buffers.iter() {
6765 matching_paths_tx
6766 .send(SearchMatchCandidate::OpenBuffer {
6767 buffer: buffer.clone(),
6768 path: Some(path.clone()),
6769 })
6770 .await
6771 .log_err();
6772 }
6773
6774 let paths_per_worker = (path_count + workers - 1) / workers;
6775
6776 executor
6777 .scoped(|scope| {
6778 let max_concurrent_workers = Arc::new(Semaphore::new(workers));
6779
6780 for worker_ix in 0..workers {
6781 let worker_start_ix = worker_ix * paths_per_worker;
6782 let worker_end_ix = worker_start_ix + paths_per_worker;
6783 let opened_buffers = opened_buffers.clone();
6784 let limiter = Arc::clone(&max_concurrent_workers);
6785 scope.spawn({
6786 async move {
6787 let _guard = limiter.acquire().await;
6788 search_snapshots(
6789 snapshots,
6790 worker_start_ix,
6791 worker_end_ix,
6792 query,
6793 matching_paths_tx,
6794 &opened_buffers,
6795 include_root,
6796 fs,
6797 )
6798 .await;
6799 }
6800 });
6801 }
6802
6803 if query.include_ignored() {
6804 for snapshot in snapshots {
6805 for ignored_entry in snapshot.entries(true).filter(|e| e.is_ignored) {
6806 let limiter = Arc::clone(&max_concurrent_workers);
6807 scope.spawn(async move {
6808 let _guard = limiter.acquire().await;
6809 search_ignored_entry(
6810 snapshot,
6811 ignored_entry,
6812 fs,
6813 query,
6814 matching_paths_tx,
6815 )
6816 .await;
6817 });
6818 }
6819 }
6820 }
6821 })
6822 .await;
6823 }
6824
6825 pub fn request_lsp<R: LspCommand>(
6826 &self,
6827 buffer_handle: Model<Buffer>,
6828 server: LanguageServerToQuery,
6829 request: R,
6830 cx: &mut ModelContext<Self>,
6831 ) -> Task<Result<R::Response>>
6832 where
6833 <R::LspRequest as lsp::request::Request>::Result: Send,
6834 <R::LspRequest as lsp::request::Request>::Params: Send,
6835 {
6836 let buffer = buffer_handle.read(cx);
6837 if self.is_local() {
6838 let language_server = match server {
6839 LanguageServerToQuery::Primary => {
6840 match self.primary_language_server_for_buffer(buffer, cx) {
6841 Some((_, server)) => Some(Arc::clone(server)),
6842 None => return Task::ready(Ok(Default::default())),
6843 }
6844 }
6845 LanguageServerToQuery::Other(id) => self
6846 .language_server_for_buffer(buffer, id, cx)
6847 .map(|(_, server)| Arc::clone(server)),
6848 };
6849 let file = File::from_dyn(buffer.file()).and_then(File::as_local);
6850 if let (Some(file), Some(language_server)) = (file, language_server) {
6851 let lsp_params = request.to_lsp(&file.abs_path(cx), buffer, &language_server, cx);
6852 let status = request.status();
6853 return cx.spawn(move |this, cx| async move {
6854 if !request.check_capabilities(language_server.capabilities()) {
6855 return Ok(Default::default());
6856 }
6857
6858 let lsp_request = language_server.request::<R::LspRequest>(lsp_params);
6859
6860 let id = lsp_request.id();
6861 let _cleanup = if status.is_some() {
6862 cx.update(|cx| {
6863 this.update(cx, |this, cx| {
6864 this.on_lsp_work_start(
6865 language_server.server_id(),
6866 id.to_string(),
6867 LanguageServerProgress {
6868 message: status.clone(),
6869 percentage: None,
6870 last_update_at: Instant::now(),
6871 },
6872 cx,
6873 );
6874 })
6875 })
6876 .log_err();
6877
6878 Some(defer(|| {
6879 cx.update(|cx| {
6880 this.update(cx, |this, cx| {
6881 this.on_lsp_work_end(
6882 language_server.server_id(),
6883 id.to_string(),
6884 cx,
6885 );
6886 })
6887 })
6888 .log_err();
6889 }))
6890 } else {
6891 None
6892 };
6893
6894 let result = lsp_request.await;
6895
6896 let response = result.map_err(|err| {
6897 log::warn!(
6898 "Generic lsp request to {} failed: {}",
6899 language_server.name(),
6900 err
6901 );
6902 err
6903 })?;
6904
6905 request
6906 .response_from_lsp(
6907 response,
6908 this.upgrade().ok_or_else(|| anyhow!("no app context"))?,
6909 buffer_handle,
6910 language_server.server_id(),
6911 cx.clone(),
6912 )
6913 .await
6914 });
6915 }
6916 } else if let Some(project_id) = self.remote_id() {
6917 return self.send_lsp_proto_request(buffer_handle, project_id, request, cx);
6918 }
6919
6920 Task::ready(Ok(Default::default()))
6921 }
6922
6923 fn request_multiple_lsp_locally<P, R>(
6924 &self,
6925 buffer: &Model<Buffer>,
6926 position: Option<P>,
6927 server_capabilities_check: fn(&ServerCapabilities) -> bool,
6928 request: R,
6929 cx: &mut ModelContext<'_, Self>,
6930 ) -> Task<Vec<R::Response>>
6931 where
6932 P: ToOffset,
6933 R: LspCommand + Clone,
6934 <R::LspRequest as lsp::request::Request>::Result: Send,
6935 <R::LspRequest as lsp::request::Request>::Params: Send,
6936 {
6937 if !self.is_local() {
6938 debug_panic!("Should not request multiple lsp commands in non-local project");
6939 return Task::ready(Vec::new());
6940 }
6941 let snapshot = buffer.read(cx).snapshot();
6942 let scope = position.and_then(|position| snapshot.language_scope_at(position));
6943 let mut response_results = self
6944 .language_servers_for_buffer(buffer.read(cx), cx)
6945 .filter(|(_, server)| server_capabilities_check(server.capabilities()))
6946 .filter(|(adapter, _)| {
6947 scope
6948 .as_ref()
6949 .map(|scope| scope.language_allowed(&adapter.name))
6950 .unwrap_or(true)
6951 })
6952 .map(|(_, server)| server.server_id())
6953 .map(|server_id| {
6954 self.request_lsp(
6955 buffer.clone(),
6956 LanguageServerToQuery::Other(server_id),
6957 request.clone(),
6958 cx,
6959 )
6960 })
6961 .collect::<FuturesUnordered<_>>();
6962
6963 return cx.spawn(|_, _| async move {
6964 let mut responses = Vec::with_capacity(response_results.len());
6965 while let Some(response_result) = response_results.next().await {
6966 if let Some(response) = response_result.log_err() {
6967 responses.push(response);
6968 }
6969 }
6970 responses
6971 });
6972 }
6973
6974 fn send_lsp_proto_request<R: LspCommand>(
6975 &self,
6976 buffer: Model<Buffer>,
6977 project_id: u64,
6978 request: R,
6979 cx: &mut ModelContext<'_, Project>,
6980 ) -> Task<anyhow::Result<<R as LspCommand>::Response>> {
6981 let rpc = self.client.clone();
6982 let message = request.to_proto(project_id, buffer.read(cx));
6983 cx.spawn(move |this, mut cx| async move {
6984 // Ensure the project is still alive by the time the task
6985 // is scheduled.
6986 this.upgrade().context("project dropped")?;
6987 let response = rpc.request(message).await?;
6988 let this = this.upgrade().context("project dropped")?;
6989 if this.update(&mut cx, |this, _| this.is_disconnected())? {
6990 Err(anyhow!("disconnected before completing request"))
6991 } else {
6992 request
6993 .response_from_proto(response, this, buffer, cx)
6994 .await
6995 }
6996 })
6997 }
6998
6999 pub fn find_or_create_local_worktree(
7000 &mut self,
7001 abs_path: impl AsRef<Path>,
7002 visible: bool,
7003 cx: &mut ModelContext<Self>,
7004 ) -> Task<Result<(Model<Worktree>, PathBuf)>> {
7005 let abs_path = abs_path.as_ref();
7006 if let Some((tree, relative_path)) = self.find_local_worktree(abs_path, cx) {
7007 Task::ready(Ok((tree, relative_path)))
7008 } else {
7009 let worktree = self.create_local_worktree(abs_path, visible, cx);
7010 cx.background_executor()
7011 .spawn(async move { Ok((worktree.await?, PathBuf::new())) })
7012 }
7013 }
7014
7015 pub fn find_local_worktree(
7016 &self,
7017 abs_path: &Path,
7018 cx: &AppContext,
7019 ) -> Option<(Model<Worktree>, PathBuf)> {
7020 for tree in &self.worktrees {
7021 if let Some(tree) = tree.upgrade() {
7022 if let Some(relative_path) = tree
7023 .read(cx)
7024 .as_local()
7025 .and_then(|t| abs_path.strip_prefix(t.abs_path()).ok())
7026 {
7027 return Some((tree.clone(), relative_path.into()));
7028 }
7029 }
7030 }
7031 None
7032 }
7033
7034 pub fn is_shared(&self) -> bool {
7035 match &self.client_state {
7036 ProjectClientState::Shared { .. } => true,
7037 ProjectClientState::Local => false,
7038 ProjectClientState::Remote { in_room, .. } => *in_room,
7039 }
7040 }
7041
7042 fn create_local_worktree(
7043 &mut self,
7044 abs_path: impl AsRef<Path>,
7045 visible: bool,
7046 cx: &mut ModelContext<Self>,
7047 ) -> Task<Result<Model<Worktree>>> {
7048 let fs = self.fs.clone();
7049 let client = self.client.clone();
7050 let next_entry_id = self.next_entry_id.clone();
7051 let path: Arc<Path> = abs_path.as_ref().into();
7052 let task = self
7053 .loading_local_worktrees
7054 .entry(path.clone())
7055 .or_insert_with(|| {
7056 cx.spawn(move |project, mut cx| {
7057 async move {
7058 let worktree = Worktree::local(
7059 client.clone(),
7060 path.clone(),
7061 visible,
7062 fs,
7063 next_entry_id,
7064 &mut cx,
7065 )
7066 .await;
7067
7068 project.update(&mut cx, |project, _| {
7069 project.loading_local_worktrees.remove(&path);
7070 })?;
7071
7072 let worktree = worktree?;
7073 project
7074 .update(&mut cx, |project, cx| project.add_worktree(&worktree, cx))?;
7075
7076 if visible {
7077 cx.update(|cx| {
7078 cx.add_recent_document(&path);
7079 })
7080 .log_err();
7081 }
7082
7083 Ok(worktree)
7084 }
7085 .map_err(Arc::new)
7086 })
7087 .shared()
7088 })
7089 .clone();
7090 cx.background_executor().spawn(async move {
7091 match task.await {
7092 Ok(worktree) => Ok(worktree),
7093 Err(err) => Err(anyhow!("{}", err)),
7094 }
7095 })
7096 }
7097
7098 pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut ModelContext<Self>) {
7099 let mut servers_to_remove = HashMap::default();
7100 let mut servers_to_preserve = HashSet::default();
7101 for ((worktree_id, server_name), &server_id) in &self.language_server_ids {
7102 if worktree_id == &id_to_remove {
7103 servers_to_remove.insert(server_id, server_name.clone());
7104 } else {
7105 servers_to_preserve.insert(server_id);
7106 }
7107 }
7108 servers_to_remove.retain(|server_id, _| !servers_to_preserve.contains(server_id));
7109 for (server_id_to_remove, server_name) in servers_to_remove {
7110 self.language_server_ids
7111 .remove(&(id_to_remove, server_name));
7112 self.language_server_statuses.remove(&server_id_to_remove);
7113 self.language_server_watched_paths
7114 .remove(&server_id_to_remove);
7115 self.last_workspace_edits_by_language_server
7116 .remove(&server_id_to_remove);
7117 self.language_servers.remove(&server_id_to_remove);
7118 cx.emit(Event::LanguageServerRemoved(server_id_to_remove));
7119 }
7120
7121 let mut prettier_instances_to_clean = FuturesUnordered::new();
7122 if let Some(prettier_paths) = self.prettiers_per_worktree.remove(&id_to_remove) {
7123 for path in prettier_paths.iter().flatten() {
7124 if let Some(prettier_instance) = self.prettier_instances.remove(path) {
7125 prettier_instances_to_clean.push(async move {
7126 prettier_instance
7127 .server()
7128 .await
7129 .map(|server| server.server_id())
7130 });
7131 }
7132 }
7133 }
7134 cx.spawn(|project, mut cx| async move {
7135 while let Some(prettier_server_id) = prettier_instances_to_clean.next().await {
7136 if let Some(prettier_server_id) = prettier_server_id {
7137 project
7138 .update(&mut cx, |project, cx| {
7139 project
7140 .supplementary_language_servers
7141 .remove(&prettier_server_id);
7142 cx.emit(Event::LanguageServerRemoved(prettier_server_id));
7143 })
7144 .ok();
7145 }
7146 }
7147 })
7148 .detach();
7149
7150 self.task_inventory().update(cx, |inventory, _| {
7151 inventory.remove_worktree_sources(id_to_remove);
7152 });
7153
7154 self.worktrees.retain(|worktree| {
7155 if let Some(worktree) = worktree.upgrade() {
7156 let id = worktree.read(cx).id();
7157 if id == id_to_remove {
7158 cx.emit(Event::WorktreeRemoved(id));
7159 false
7160 } else {
7161 true
7162 }
7163 } else {
7164 false
7165 }
7166 });
7167 self.metadata_changed(cx);
7168 }
7169
7170 fn add_worktree(&mut self, worktree: &Model<Worktree>, cx: &mut ModelContext<Self>) {
7171 cx.observe(worktree, |_, _, cx| cx.notify()).detach();
7172 cx.subscribe(worktree, |this, worktree, event, cx| {
7173 let is_local = worktree.read(cx).is_local();
7174 match event {
7175 worktree::Event::UpdatedEntries(changes) => {
7176 if is_local {
7177 this.update_local_worktree_buffers(&worktree, changes, cx);
7178 this.update_local_worktree_language_servers(&worktree, changes, cx);
7179 this.update_local_worktree_settings(&worktree, changes, cx);
7180 this.update_prettier_settings(&worktree, changes, cx);
7181 }
7182
7183 cx.emit(Event::WorktreeUpdatedEntries(
7184 worktree.read(cx).id(),
7185 changes.clone(),
7186 ));
7187 }
7188 worktree::Event::UpdatedGitRepositories(updated_repos) => {
7189 if is_local {
7190 this.update_local_worktree_buffers_git_repos(
7191 worktree.clone(),
7192 updated_repos,
7193 cx,
7194 )
7195 }
7196 cx.emit(Event::WorktreeUpdatedGitRepositories);
7197 }
7198 }
7199 })
7200 .detach();
7201
7202 let push_strong_handle = {
7203 let worktree = worktree.read(cx);
7204 self.is_shared() || worktree.is_visible() || worktree.is_remote()
7205 };
7206 if push_strong_handle {
7207 self.worktrees
7208 .push(WorktreeHandle::Strong(worktree.clone()));
7209 } else {
7210 self.worktrees
7211 .push(WorktreeHandle::Weak(worktree.downgrade()));
7212 }
7213
7214 let handle_id = worktree.entity_id();
7215 cx.observe_release(worktree, move |this, worktree, cx| {
7216 let _ = this.remove_worktree(worktree.id(), cx);
7217 cx.update_global::<SettingsStore, _>(|store, cx| {
7218 store
7219 .clear_local_settings(handle_id.as_u64() as usize, cx)
7220 .log_err()
7221 });
7222 })
7223 .detach();
7224
7225 cx.emit(Event::WorktreeAdded);
7226 self.metadata_changed(cx);
7227 }
7228
7229 fn update_local_worktree_buffers(
7230 &mut self,
7231 worktree_handle: &Model<Worktree>,
7232 changes: &[(Arc<Path>, ProjectEntryId, PathChange)],
7233 cx: &mut ModelContext<Self>,
7234 ) {
7235 let snapshot = worktree_handle.read(cx).snapshot();
7236
7237 let mut renamed_buffers = Vec::new();
7238 for (path, entry_id, _) in changes {
7239 let worktree_id = worktree_handle.read(cx).id();
7240 let project_path = ProjectPath {
7241 worktree_id,
7242 path: path.clone(),
7243 };
7244
7245 let buffer_id = match self.local_buffer_ids_by_entry_id.get(entry_id) {
7246 Some(&buffer_id) => buffer_id,
7247 None => match self.local_buffer_ids_by_path.get(&project_path) {
7248 Some(&buffer_id) => buffer_id,
7249 None => {
7250 continue;
7251 }
7252 },
7253 };
7254
7255 let open_buffer = self.opened_buffers.get(&buffer_id);
7256 let buffer = if let Some(buffer) = open_buffer.and_then(|buffer| buffer.upgrade()) {
7257 buffer
7258 } else {
7259 self.opened_buffers.remove(&buffer_id);
7260 self.local_buffer_ids_by_path.remove(&project_path);
7261 self.local_buffer_ids_by_entry_id.remove(entry_id);
7262 continue;
7263 };
7264
7265 buffer.update(cx, |buffer, cx| {
7266 if let Some(old_file) = File::from_dyn(buffer.file()) {
7267 if old_file.worktree != *worktree_handle {
7268 return;
7269 }
7270
7271 let new_file = if let Some(entry) = old_file
7272 .entry_id
7273 .and_then(|entry_id| snapshot.entry_for_id(entry_id))
7274 {
7275 File {
7276 is_local: true,
7277 entry_id: Some(entry.id),
7278 mtime: entry.mtime,
7279 path: entry.path.clone(),
7280 worktree: worktree_handle.clone(),
7281 is_deleted: false,
7282 is_private: entry.is_private,
7283 }
7284 } else if let Some(entry) = snapshot.entry_for_path(old_file.path().as_ref()) {
7285 File {
7286 is_local: true,
7287 entry_id: Some(entry.id),
7288 mtime: entry.mtime,
7289 path: entry.path.clone(),
7290 worktree: worktree_handle.clone(),
7291 is_deleted: false,
7292 is_private: entry.is_private,
7293 }
7294 } else {
7295 File {
7296 is_local: true,
7297 entry_id: old_file.entry_id,
7298 path: old_file.path().clone(),
7299 mtime: old_file.mtime(),
7300 worktree: worktree_handle.clone(),
7301 is_deleted: true,
7302 is_private: old_file.is_private,
7303 }
7304 };
7305
7306 let old_path = old_file.abs_path(cx);
7307 if new_file.abs_path(cx) != old_path {
7308 renamed_buffers.push((cx.handle(), old_file.clone()));
7309 self.local_buffer_ids_by_path.remove(&project_path);
7310 self.local_buffer_ids_by_path.insert(
7311 ProjectPath {
7312 worktree_id,
7313 path: path.clone(),
7314 },
7315 buffer_id,
7316 );
7317 }
7318
7319 if new_file.entry_id != Some(*entry_id) {
7320 self.local_buffer_ids_by_entry_id.remove(entry_id);
7321 if let Some(entry_id) = new_file.entry_id {
7322 self.local_buffer_ids_by_entry_id
7323 .insert(entry_id, buffer_id);
7324 }
7325 }
7326
7327 if new_file != *old_file {
7328 if let Some(project_id) = self.remote_id() {
7329 self.client
7330 .send(proto::UpdateBufferFile {
7331 project_id,
7332 buffer_id: buffer_id.into(),
7333 file: Some(new_file.to_proto()),
7334 })
7335 .log_err();
7336 }
7337
7338 buffer.file_updated(Arc::new(new_file), cx);
7339 }
7340 }
7341 });
7342 }
7343
7344 for (buffer, old_file) in renamed_buffers {
7345 self.unregister_buffer_from_language_servers(&buffer, &old_file, cx);
7346 self.detect_language_for_buffer(&buffer, cx);
7347 self.register_buffer_with_language_servers(&buffer, cx);
7348 }
7349 }
7350
7351 fn update_local_worktree_language_servers(
7352 &mut self,
7353 worktree_handle: &Model<Worktree>,
7354 changes: &[(Arc<Path>, ProjectEntryId, PathChange)],
7355 cx: &mut ModelContext<Self>,
7356 ) {
7357 if changes.is_empty() {
7358 return;
7359 }
7360
7361 let worktree_id = worktree_handle.read(cx).id();
7362 let mut language_server_ids = self
7363 .language_server_ids
7364 .iter()
7365 .filter_map(|((server_worktree_id, _), server_id)| {
7366 (*server_worktree_id == worktree_id).then_some(*server_id)
7367 })
7368 .collect::<Vec<_>>();
7369 language_server_ids.sort();
7370 language_server_ids.dedup();
7371
7372 let abs_path = worktree_handle.read(cx).abs_path();
7373 for server_id in &language_server_ids {
7374 if let Some(LanguageServerState::Running { server, .. }) =
7375 self.language_servers.get(server_id)
7376 {
7377 if let Some(watched_paths) = self
7378 .language_server_watched_paths
7379 .get(&server_id)
7380 .and_then(|paths| paths.get(&worktree_id))
7381 {
7382 let params = lsp::DidChangeWatchedFilesParams {
7383 changes: changes
7384 .iter()
7385 .filter_map(|(path, _, change)| {
7386 if !watched_paths.is_match(&path) {
7387 return None;
7388 }
7389 let typ = match change {
7390 PathChange::Loaded => return None,
7391 PathChange::Added => lsp::FileChangeType::CREATED,
7392 PathChange::Removed => lsp::FileChangeType::DELETED,
7393 PathChange::Updated => lsp::FileChangeType::CHANGED,
7394 PathChange::AddedOrUpdated => lsp::FileChangeType::CHANGED,
7395 };
7396 Some(lsp::FileEvent {
7397 uri: lsp::Url::from_file_path(abs_path.join(path)).unwrap(),
7398 typ,
7399 })
7400 })
7401 .collect(),
7402 };
7403 if !params.changes.is_empty() {
7404 server
7405 .notify::<lsp::notification::DidChangeWatchedFiles>(params)
7406 .log_err();
7407 }
7408 }
7409 }
7410 }
7411 }
7412
7413 fn update_local_worktree_buffers_git_repos(
7414 &mut self,
7415 worktree_handle: Model<Worktree>,
7416 changed_repos: &UpdatedGitRepositoriesSet,
7417 cx: &mut ModelContext<Self>,
7418 ) {
7419 debug_assert!(worktree_handle.read(cx).is_local());
7420
7421 // Identify the loading buffers whose containing repository that has changed.
7422 let future_buffers = self
7423 .loading_buffers_by_path
7424 .iter()
7425 .filter_map(|(project_path, receiver)| {
7426 if project_path.worktree_id != worktree_handle.read(cx).id() {
7427 return None;
7428 }
7429 let path = &project_path.path;
7430 changed_repos
7431 .iter()
7432 .find(|(work_dir, _)| path.starts_with(work_dir))?;
7433 let receiver = receiver.clone();
7434 let path = path.clone();
7435 let abs_path = worktree_handle.read(cx).absolutize(&path).ok()?;
7436 Some(async move {
7437 wait_for_loading_buffer(receiver)
7438 .await
7439 .ok()
7440 .map(|buffer| (buffer, path, abs_path))
7441 })
7442 })
7443 .collect::<FuturesUnordered<_>>();
7444
7445 // Identify the current buffers whose containing repository has changed.
7446 let current_buffers = self
7447 .opened_buffers
7448 .values()
7449 .filter_map(|buffer| {
7450 let buffer = buffer.upgrade()?;
7451 let file = File::from_dyn(buffer.read(cx).file())?;
7452 if file.worktree != worktree_handle {
7453 return None;
7454 }
7455 let path = file.path();
7456 changed_repos
7457 .iter()
7458 .find(|(work_dir, _)| path.starts_with(work_dir))?;
7459 Some((buffer, path.clone(), file.abs_path(cx)))
7460 })
7461 .collect::<Vec<_>>();
7462
7463 if future_buffers.len() + current_buffers.len() == 0 {
7464 return;
7465 }
7466
7467 let remote_id = self.remote_id();
7468 let client = self.client.clone();
7469 let fs = self.fs.clone();
7470 cx.spawn(move |_, mut cx| async move {
7471 // Wait for all of the buffers to load.
7472 let future_buffers = future_buffers.collect::<Vec<_>>().await;
7473
7474 // Reload the diff base for every buffer whose containing git repository has changed.
7475 let snapshot =
7476 worktree_handle.update(&mut cx, |tree, _| tree.as_local().unwrap().snapshot())?;
7477 let diff_bases_by_buffer = cx
7478 .background_executor()
7479 .spawn(async move {
7480 let mut diff_base_tasks = future_buffers
7481 .into_iter()
7482 .flatten()
7483 .chain(current_buffers)
7484 .filter_map(|(buffer, path, abs_path)| {
7485 let (work_directory, repo) =
7486 snapshot.repository_and_work_directory_for_path(&path)?;
7487 let repo_entry = snapshot.get_local_repo(&repo)?;
7488 Some((buffer, path, abs_path, work_directory, repo_entry))
7489 })
7490 .map(|(buffer, path, abs_path, work_directory, repo_entry)| {
7491 let fs = fs.clone();
7492 async move {
7493 let abs_path_metadata = fs
7494 .metadata(&abs_path)
7495 .await
7496 .with_context(|| {
7497 format!("loading file and FS metadata for {path:?}")
7498 })
7499 .log_err()
7500 .flatten()?;
7501 let base_text = if abs_path_metadata.is_dir
7502 || abs_path_metadata.is_symlink
7503 {
7504 None
7505 } else {
7506 let relative_path = path.strip_prefix(&work_directory).ok()?;
7507 repo_entry.repo().lock().load_index_text(relative_path)
7508 };
7509 Some((buffer, base_text))
7510 }
7511 })
7512 .collect::<FuturesUnordered<_>>();
7513
7514 let mut diff_bases = Vec::with_capacity(diff_base_tasks.len());
7515 while let Some(diff_base) = diff_base_tasks.next().await {
7516 if let Some(diff_base) = diff_base {
7517 diff_bases.push(diff_base);
7518 }
7519 }
7520 diff_bases
7521 })
7522 .await;
7523
7524 // Assign the new diff bases on all of the buffers.
7525 for (buffer, diff_base) in diff_bases_by_buffer {
7526 let buffer_id = buffer.update(&mut cx, |buffer, cx| {
7527 buffer.set_diff_base(diff_base.clone(), cx);
7528 buffer.remote_id().into()
7529 })?;
7530 if let Some(project_id) = remote_id {
7531 client
7532 .send(proto::UpdateDiffBase {
7533 project_id,
7534 buffer_id,
7535 diff_base,
7536 })
7537 .log_err();
7538 }
7539 }
7540
7541 anyhow::Ok(())
7542 })
7543 .detach();
7544 }
7545
7546 fn update_local_worktree_settings(
7547 &mut self,
7548 worktree: &Model<Worktree>,
7549 changes: &UpdatedEntriesSet,
7550 cx: &mut ModelContext<Self>,
7551 ) {
7552 if worktree.read(cx).as_local().is_none() {
7553 return;
7554 }
7555 let project_id = self.remote_id();
7556 let worktree_id = worktree.entity_id();
7557 let remote_worktree_id = worktree.read(cx).id();
7558
7559 let mut settings_contents = Vec::new();
7560 for (path, _, change) in changes.iter() {
7561 let removed = change == &PathChange::Removed;
7562 let abs_path = match worktree.read(cx).absolutize(path) {
7563 Ok(abs_path) => abs_path,
7564 Err(e) => {
7565 log::warn!("Cannot absolutize {path:?} received as {change:?} FS change: {e}");
7566 continue;
7567 }
7568 };
7569
7570 if abs_path.ends_with(&*LOCAL_SETTINGS_RELATIVE_PATH) {
7571 let settings_dir = Arc::from(
7572 path.ancestors()
7573 .nth(LOCAL_SETTINGS_RELATIVE_PATH.components().count())
7574 .unwrap(),
7575 );
7576 let fs = self.fs.clone();
7577 settings_contents.push(async move {
7578 (
7579 settings_dir,
7580 if removed {
7581 None
7582 } else {
7583 Some(async move { fs.load(&abs_path).await }.await)
7584 },
7585 )
7586 });
7587 } else if abs_path.ends_with(&*LOCAL_TASKS_RELATIVE_PATH) {
7588 self.task_inventory().update(cx, |task_inventory, cx| {
7589 if removed {
7590 task_inventory.remove_local_static_source(&abs_path);
7591 } else {
7592 let fs = self.fs.clone();
7593 let task_abs_path = abs_path.clone();
7594 task_inventory.add_source(
7595 TaskSourceKind::Worktree {
7596 id: remote_worktree_id,
7597 abs_path,
7598 id_base: "local_tasks_for_worktree",
7599 },
7600 |cx| {
7601 let tasks_file_rx =
7602 watch_config_file(&cx.background_executor(), fs, task_abs_path);
7603 StaticSource::new(TrackedFile::new(tasks_file_rx, cx), cx)
7604 },
7605 cx,
7606 );
7607 }
7608 })
7609 } else if abs_path.ends_with(&*LOCAL_VSCODE_TASKS_RELATIVE_PATH) {
7610 self.task_inventory().update(cx, |task_inventory, cx| {
7611 if removed {
7612 task_inventory.remove_local_static_source(&abs_path);
7613 } else {
7614 let fs = self.fs.clone();
7615 let task_abs_path = abs_path.clone();
7616 task_inventory.add_source(
7617 TaskSourceKind::Worktree {
7618 id: remote_worktree_id,
7619 abs_path,
7620 id_base: "local_vscode_tasks_for_worktree",
7621 },
7622 |cx| {
7623 let tasks_file_rx =
7624 watch_config_file(&cx.background_executor(), fs, task_abs_path);
7625 StaticSource::new(
7626 TrackedFile::new_convertible::<task::VsCodeTaskFile>(
7627 tasks_file_rx,
7628 cx,
7629 ),
7630 cx,
7631 )
7632 },
7633 cx,
7634 );
7635 }
7636 })
7637 }
7638 }
7639
7640 if settings_contents.is_empty() {
7641 return;
7642 }
7643
7644 let client = self.client.clone();
7645 cx.spawn(move |_, cx| async move {
7646 let settings_contents: Vec<(Arc<Path>, _)> =
7647 futures::future::join_all(settings_contents).await;
7648 cx.update(|cx| {
7649 cx.update_global::<SettingsStore, _>(|store, cx| {
7650 for (directory, file_content) in settings_contents {
7651 let file_content = file_content.and_then(|content| content.log_err());
7652 store
7653 .set_local_settings(
7654 worktree_id.as_u64() as usize,
7655 directory.clone(),
7656 file_content.as_deref(),
7657 cx,
7658 )
7659 .log_err();
7660 if let Some(remote_id) = project_id {
7661 client
7662 .send(proto::UpdateWorktreeSettings {
7663 project_id: remote_id,
7664 worktree_id: remote_worktree_id.to_proto(),
7665 path: directory.to_string_lossy().into_owned(),
7666 content: file_content,
7667 })
7668 .log_err();
7669 }
7670 }
7671 });
7672 })
7673 .ok();
7674 })
7675 .detach();
7676 }
7677
7678 pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
7679 let new_active_entry = entry.and_then(|project_path| {
7680 let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
7681 let entry = worktree.read(cx).entry_for_path(project_path.path)?;
7682 Some(entry.id)
7683 });
7684 if new_active_entry != self.active_entry {
7685 self.active_entry = new_active_entry;
7686 cx.emit(Event::ActiveEntryChanged(new_active_entry));
7687 }
7688 }
7689
7690 pub fn language_servers_running_disk_based_diagnostics(
7691 &self,
7692 ) -> impl Iterator<Item = LanguageServerId> + '_ {
7693 self.language_server_statuses
7694 .iter()
7695 .filter_map(|(id, status)| {
7696 if status.has_pending_diagnostic_updates {
7697 Some(*id)
7698 } else {
7699 None
7700 }
7701 })
7702 }
7703
7704 pub fn diagnostic_summary(&self, include_ignored: bool, cx: &AppContext) -> DiagnosticSummary {
7705 let mut summary = DiagnosticSummary::default();
7706 for (_, _, path_summary) in self.diagnostic_summaries(include_ignored, cx) {
7707 summary.error_count += path_summary.error_count;
7708 summary.warning_count += path_summary.warning_count;
7709 }
7710 summary
7711 }
7712
7713 pub fn diagnostic_summaries<'a>(
7714 &'a self,
7715 include_ignored: bool,
7716 cx: &'a AppContext,
7717 ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
7718 self.visible_worktrees(cx).flat_map(move |worktree| {
7719 let worktree = worktree.read(cx);
7720 let worktree_id = worktree.id();
7721 worktree
7722 .diagnostic_summaries()
7723 .filter_map(move |(path, server_id, summary)| {
7724 if include_ignored
7725 || worktree
7726 .entry_for_path(path.as_ref())
7727 .map_or(false, |entry| !entry.is_ignored)
7728 {
7729 Some((ProjectPath { worktree_id, path }, server_id, summary))
7730 } else {
7731 None
7732 }
7733 })
7734 })
7735 }
7736
7737 pub fn disk_based_diagnostics_started(
7738 &mut self,
7739 language_server_id: LanguageServerId,
7740 cx: &mut ModelContext<Self>,
7741 ) {
7742 if let Some(language_server_status) =
7743 self.language_server_statuses.get_mut(&language_server_id)
7744 {
7745 language_server_status.has_pending_diagnostic_updates = true;
7746 }
7747
7748 cx.emit(Event::DiskBasedDiagnosticsStarted { language_server_id });
7749 if self.is_local() {
7750 self.enqueue_buffer_ordered_message(BufferOrderedMessage::LanguageServerUpdate {
7751 language_server_id,
7752 message: proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(
7753 Default::default(),
7754 ),
7755 })
7756 .ok();
7757 }
7758 }
7759
7760 pub fn disk_based_diagnostics_finished(
7761 &mut self,
7762 language_server_id: LanguageServerId,
7763 cx: &mut ModelContext<Self>,
7764 ) {
7765 if let Some(language_server_status) =
7766 self.language_server_statuses.get_mut(&language_server_id)
7767 {
7768 language_server_status.has_pending_diagnostic_updates = false;
7769 }
7770
7771 cx.emit(Event::DiskBasedDiagnosticsFinished { language_server_id });
7772
7773 if self.is_local() {
7774 self.enqueue_buffer_ordered_message(BufferOrderedMessage::LanguageServerUpdate {
7775 language_server_id,
7776 message: proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
7777 Default::default(),
7778 ),
7779 })
7780 .ok();
7781 }
7782 }
7783
7784 pub fn active_entry(&self) -> Option<ProjectEntryId> {
7785 self.active_entry
7786 }
7787
7788 pub fn entry_for_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<Entry> {
7789 self.worktree_for_id(path.worktree_id, cx)?
7790 .read(cx)
7791 .entry_for_path(&path.path)
7792 .cloned()
7793 }
7794
7795 pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &AppContext) -> Option<ProjectPath> {
7796 let worktree = self.worktree_for_entry(entry_id, cx)?;
7797 let worktree = worktree.read(cx);
7798 let worktree_id = worktree.id();
7799 let path = worktree.entry_for_id(entry_id)?.path.clone();
7800 Some(ProjectPath { worktree_id, path })
7801 }
7802
7803 pub fn absolute_path(&self, project_path: &ProjectPath, cx: &AppContext) -> Option<PathBuf> {
7804 let workspace_root = self
7805 .worktree_for_id(project_path.worktree_id, cx)?
7806 .read(cx)
7807 .abs_path();
7808 let project_path = project_path.path.as_ref();
7809
7810 Some(if project_path == Path::new("") {
7811 workspace_root.to_path_buf()
7812 } else {
7813 workspace_root.join(project_path)
7814 })
7815 }
7816
7817 pub fn get_workspace_root(
7818 &self,
7819 project_path: &ProjectPath,
7820 cx: &AppContext,
7821 ) -> Option<PathBuf> {
7822 Some(
7823 self.worktree_for_id(project_path.worktree_id, cx)?
7824 .read(cx)
7825 .abs_path()
7826 .to_path_buf(),
7827 )
7828 }
7829
7830 pub fn get_repo(
7831 &self,
7832 project_path: &ProjectPath,
7833 cx: &AppContext,
7834 ) -> Option<Arc<Mutex<dyn GitRepository>>> {
7835 self.worktree_for_id(project_path.worktree_id, cx)?
7836 .read(cx)
7837 .as_local()?
7838 .snapshot()
7839 .local_git_repo(&project_path.path)
7840 }
7841
7842 pub fn blame_buffer(
7843 &self,
7844 buffer: &Model<Buffer>,
7845 version: Option<clock::Global>,
7846 cx: &AppContext,
7847 ) -> Task<Result<Blame>> {
7848 if self.is_local() {
7849 let blame_params = maybe!({
7850 let buffer = buffer.read(cx);
7851 let buffer_project_path = buffer
7852 .project_path(cx)
7853 .context("failed to get buffer project path")?;
7854
7855 let worktree = self
7856 .worktree_for_id(buffer_project_path.worktree_id, cx)
7857 .context("failed to get worktree")?
7858 .read(cx)
7859 .as_local()
7860 .context("worktree was not local")?
7861 .snapshot();
7862
7863 let (work_directory, repo) = match worktree
7864 .repository_and_work_directory_for_path(&buffer_project_path.path)
7865 {
7866 Some(work_dir_repo) => work_dir_repo,
7867 None => anyhow::bail!(NoRepositoryError {}),
7868 };
7869
7870 let repo_entry = match worktree.get_local_repo(&repo) {
7871 Some(repo_entry) => repo_entry,
7872 None => anyhow::bail!(NoRepositoryError {}),
7873 };
7874
7875 let repo = repo_entry.repo().clone();
7876
7877 let relative_path = buffer_project_path
7878 .path
7879 .strip_prefix(&work_directory)?
7880 .to_path_buf();
7881
7882 let content = match version {
7883 Some(version) => buffer.rope_for_version(&version).clone(),
7884 None => buffer.as_rope().clone(),
7885 };
7886
7887 anyhow::Ok((repo, relative_path, content))
7888 });
7889
7890 cx.background_executor().spawn(async move {
7891 let (repo, relative_path, content) = blame_params?;
7892 let lock = repo.lock();
7893 lock.blame(&relative_path, content)
7894 .with_context(|| format!("Failed to blame {relative_path:?}"))
7895 })
7896 } else {
7897 let project_id = self.remote_id();
7898 let buffer_id = buffer.read(cx).remote_id();
7899 let client = self.client.clone();
7900 let version = buffer.read(cx).version();
7901
7902 cx.spawn(|_| async move {
7903 let project_id = project_id.context("unable to get project id for buffer")?;
7904 let response = client
7905 .request(proto::BlameBuffer {
7906 project_id,
7907 buffer_id: buffer_id.into(),
7908 version: serialize_version(&version),
7909 })
7910 .await?;
7911
7912 Ok(deserialize_blame_buffer_response(response))
7913 })
7914 }
7915 }
7916
7917 // RPC message handlers
7918
7919 async fn handle_blame_buffer(
7920 this: Model<Self>,
7921 envelope: TypedEnvelope<proto::BlameBuffer>,
7922 _: Arc<Client>,
7923 mut cx: AsyncAppContext,
7924 ) -> Result<proto::BlameBufferResponse> {
7925 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
7926 let version = deserialize_version(&envelope.payload.version);
7927
7928 let buffer = this.update(&mut cx, |this, _cx| {
7929 this.opened_buffers
7930 .get(&buffer_id)
7931 .and_then(|buffer| buffer.upgrade())
7932 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
7933 })??;
7934
7935 buffer
7936 .update(&mut cx, |buffer, _| {
7937 buffer.wait_for_version(version.clone())
7938 })?
7939 .await?;
7940
7941 let blame = this
7942 .update(&mut cx, |this, cx| {
7943 this.blame_buffer(&buffer, Some(version), cx)
7944 })?
7945 .await?;
7946
7947 Ok(serialize_blame_buffer_response(blame))
7948 }
7949
7950 async fn handle_multi_lsp_query(
7951 project: Model<Self>,
7952 envelope: TypedEnvelope<proto::MultiLspQuery>,
7953 _: Arc<Client>,
7954 mut cx: AsyncAppContext,
7955 ) -> Result<proto::MultiLspQueryResponse> {
7956 let sender_id = envelope.original_sender_id()?;
7957 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
7958 let version = deserialize_version(&envelope.payload.version);
7959 let buffer = project.update(&mut cx, |project, _cx| {
7960 project
7961 .opened_buffers
7962 .get(&buffer_id)
7963 .and_then(|buffer| buffer.upgrade())
7964 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
7965 })??;
7966 buffer
7967 .update(&mut cx, |buffer, _| {
7968 buffer.wait_for_version(version.clone())
7969 })?
7970 .await?;
7971 let buffer_version = buffer.update(&mut cx, |buffer, _| buffer.version())?;
7972 match envelope
7973 .payload
7974 .strategy
7975 .context("invalid request without the strategy")?
7976 {
7977 proto::multi_lsp_query::Strategy::All(_) => {
7978 // currently, there's only one multiple language servers query strategy,
7979 // so just ensure it's specified correctly
7980 }
7981 }
7982 match envelope.payload.request {
7983 Some(proto::multi_lsp_query::Request::GetHover(get_hover)) => {
7984 let get_hover =
7985 GetHover::from_proto(get_hover, project.clone(), buffer.clone(), cx.clone())
7986 .await?;
7987 let all_hovers = project
7988 .update(&mut cx, |project, cx| {
7989 project.request_multiple_lsp_locally(
7990 &buffer,
7991 Some(get_hover.position),
7992 |server_capabilities| match server_capabilities.hover_provider {
7993 Some(lsp::HoverProviderCapability::Simple(enabled)) => enabled,
7994 Some(lsp::HoverProviderCapability::Options(_)) => true,
7995 None => false,
7996 },
7997 get_hover,
7998 cx,
7999 )
8000 })?
8001 .await
8002 .into_iter()
8003 .filter_map(|hover| remove_empty_hover_blocks(hover?));
8004 project.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
8005 responses: all_hovers
8006 .map(|hover| proto::LspResponse {
8007 response: Some(proto::lsp_response::Response::GetHoverResponse(
8008 GetHover::response_to_proto(
8009 Some(hover),
8010 project,
8011 sender_id,
8012 &buffer_version,
8013 cx,
8014 ),
8015 )),
8016 })
8017 .collect(),
8018 })
8019 }
8020 Some(proto::multi_lsp_query::Request::GetCodeActions(get_code_actions)) => {
8021 let get_code_actions = GetCodeActions::from_proto(
8022 get_code_actions,
8023 project.clone(),
8024 buffer.clone(),
8025 cx.clone(),
8026 )
8027 .await?;
8028
8029 let all_actions = project
8030 .update(&mut cx, |project, cx| {
8031 project.request_multiple_lsp_locally(
8032 &buffer,
8033 Some(get_code_actions.range.start),
8034 GetCodeActions::supports_code_actions,
8035 get_code_actions,
8036 cx,
8037 )
8038 })?
8039 .await
8040 .into_iter();
8041
8042 project.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
8043 responses: all_actions
8044 .map(|code_actions| proto::LspResponse {
8045 response: Some(proto::lsp_response::Response::GetCodeActionsResponse(
8046 GetCodeActions::response_to_proto(
8047 code_actions,
8048 project,
8049 sender_id,
8050 &buffer_version,
8051 cx,
8052 ),
8053 )),
8054 })
8055 .collect(),
8056 })
8057 }
8058 None => anyhow::bail!("empty multi lsp query request"),
8059 }
8060 }
8061
8062 async fn handle_unshare_project(
8063 this: Model<Self>,
8064 _: TypedEnvelope<proto::UnshareProject>,
8065 _: Arc<Client>,
8066 mut cx: AsyncAppContext,
8067 ) -> Result<()> {
8068 this.update(&mut cx, |this, cx| {
8069 if this.is_local() {
8070 this.unshare(cx)?;
8071 } else {
8072 this.disconnected_from_host(cx);
8073 }
8074 Ok(())
8075 })?
8076 }
8077
8078 async fn handle_add_collaborator(
8079 this: Model<Self>,
8080 mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
8081 _: Arc<Client>,
8082 mut cx: AsyncAppContext,
8083 ) -> Result<()> {
8084 let collaborator = envelope
8085 .payload
8086 .collaborator
8087 .take()
8088 .ok_or_else(|| anyhow!("empty collaborator"))?;
8089
8090 let collaborator = Collaborator::from_proto(collaborator)?;
8091 this.update(&mut cx, |this, cx| {
8092 this.shared_buffers.remove(&collaborator.peer_id);
8093 cx.emit(Event::CollaboratorJoined(collaborator.peer_id));
8094 this.collaborators
8095 .insert(collaborator.peer_id, collaborator);
8096 cx.notify();
8097 })?;
8098
8099 Ok(())
8100 }
8101
8102 async fn handle_update_project_collaborator(
8103 this: Model<Self>,
8104 envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
8105 _: Arc<Client>,
8106 mut cx: AsyncAppContext,
8107 ) -> Result<()> {
8108 let old_peer_id = envelope
8109 .payload
8110 .old_peer_id
8111 .ok_or_else(|| anyhow!("missing old peer id"))?;
8112 let new_peer_id = envelope
8113 .payload
8114 .new_peer_id
8115 .ok_or_else(|| anyhow!("missing new peer id"))?;
8116 this.update(&mut cx, |this, cx| {
8117 let collaborator = this
8118 .collaborators
8119 .remove(&old_peer_id)
8120 .ok_or_else(|| anyhow!("received UpdateProjectCollaborator for unknown peer"))?;
8121 let is_host = collaborator.replica_id == 0;
8122 this.collaborators.insert(new_peer_id, collaborator);
8123
8124 let buffers = this.shared_buffers.remove(&old_peer_id);
8125 log::info!(
8126 "peer {} became {}. moving buffers {:?}",
8127 old_peer_id,
8128 new_peer_id,
8129 &buffers
8130 );
8131 if let Some(buffers) = buffers {
8132 this.shared_buffers.insert(new_peer_id, buffers);
8133 }
8134
8135 if is_host {
8136 this.opened_buffers
8137 .retain(|_, buffer| !matches!(buffer, OpenBuffer::Operations(_)));
8138 this.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
8139 .unwrap();
8140 }
8141
8142 cx.emit(Event::CollaboratorUpdated {
8143 old_peer_id,
8144 new_peer_id,
8145 });
8146 cx.notify();
8147 Ok(())
8148 })?
8149 }
8150
8151 async fn handle_remove_collaborator(
8152 this: Model<Self>,
8153 envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
8154 _: Arc<Client>,
8155 mut cx: AsyncAppContext,
8156 ) -> Result<()> {
8157 this.update(&mut cx, |this, cx| {
8158 let peer_id = envelope
8159 .payload
8160 .peer_id
8161 .ok_or_else(|| anyhow!("invalid peer id"))?;
8162 let replica_id = this
8163 .collaborators
8164 .remove(&peer_id)
8165 .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
8166 .replica_id;
8167 for buffer in this.opened_buffers.values() {
8168 if let Some(buffer) = buffer.upgrade() {
8169 buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
8170 }
8171 }
8172 this.shared_buffers.remove(&peer_id);
8173
8174 cx.emit(Event::CollaboratorLeft(peer_id));
8175 cx.notify();
8176 Ok(())
8177 })?
8178 }
8179
8180 async fn handle_update_project(
8181 this: Model<Self>,
8182 envelope: TypedEnvelope<proto::UpdateProject>,
8183 _: Arc<Client>,
8184 mut cx: AsyncAppContext,
8185 ) -> Result<()> {
8186 this.update(&mut cx, |this, cx| {
8187 // Don't handle messages that were sent before the response to us joining the project
8188 if envelope.message_id > this.join_project_response_message_id {
8189 this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
8190 }
8191 Ok(())
8192 })?
8193 }
8194
8195 async fn handle_update_worktree(
8196 this: Model<Self>,
8197 envelope: TypedEnvelope<proto::UpdateWorktree>,
8198 _: Arc<Client>,
8199 mut cx: AsyncAppContext,
8200 ) -> Result<()> {
8201 this.update(&mut cx, |this, cx| {
8202 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
8203 if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
8204 worktree.update(cx, |worktree, _| {
8205 let worktree = worktree.as_remote_mut().unwrap();
8206 worktree.update_from_remote(envelope.payload);
8207 });
8208 }
8209 Ok(())
8210 })?
8211 }
8212
8213 async fn handle_update_worktree_settings(
8214 this: Model<Self>,
8215 envelope: TypedEnvelope<proto::UpdateWorktreeSettings>,
8216 _: Arc<Client>,
8217 mut cx: AsyncAppContext,
8218 ) -> Result<()> {
8219 this.update(&mut cx, |this, cx| {
8220 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
8221 if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
8222 cx.update_global::<SettingsStore, _>(|store, cx| {
8223 store
8224 .set_local_settings(
8225 worktree.entity_id().as_u64() as usize,
8226 PathBuf::from(&envelope.payload.path).into(),
8227 envelope.payload.content.as_deref(),
8228 cx,
8229 )
8230 .log_err();
8231 });
8232 }
8233 Ok(())
8234 })?
8235 }
8236
8237 async fn handle_create_project_entry(
8238 this: Model<Self>,
8239 envelope: TypedEnvelope<proto::CreateProjectEntry>,
8240 _: Arc<Client>,
8241 mut cx: AsyncAppContext,
8242 ) -> Result<proto::ProjectEntryResponse> {
8243 let worktree = this.update(&mut cx, |this, cx| {
8244 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
8245 this.worktree_for_id(worktree_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 worktree = worktree.as_local_mut().unwrap();
8252 let path = PathBuf::from(envelope.payload.path);
8253 worktree.create_entry(path, envelope.payload.is_directory, cx)
8254 })?
8255 .await?;
8256 Ok(proto::ProjectEntryResponse {
8257 entry: entry.as_ref().map(|e| e.into()),
8258 worktree_scan_id: worktree_scan_id as u64,
8259 })
8260 }
8261
8262 async fn handle_rename_project_entry(
8263 this: Model<Self>,
8264 envelope: TypedEnvelope<proto::RenameProjectEntry>,
8265 _: Arc<Client>,
8266 mut cx: AsyncAppContext,
8267 ) -> Result<proto::ProjectEntryResponse> {
8268 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
8269 let worktree = this.update(&mut cx, |this, cx| {
8270 this.worktree_for_entry(entry_id, cx)
8271 .ok_or_else(|| anyhow!("worktree not found"))
8272 })??;
8273 let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())?;
8274 let entry = worktree
8275 .update(&mut cx, |worktree, cx| {
8276 let new_path = PathBuf::from(envelope.payload.new_path);
8277 worktree
8278 .as_local_mut()
8279 .unwrap()
8280 .rename_entry(entry_id, new_path, cx)
8281 })?
8282 .await?;
8283 Ok(proto::ProjectEntryResponse {
8284 entry: entry.as_ref().map(|e| e.into()),
8285 worktree_scan_id: worktree_scan_id as u64,
8286 })
8287 }
8288
8289 async fn handle_copy_project_entry(
8290 this: Model<Self>,
8291 envelope: TypedEnvelope<proto::CopyProjectEntry>,
8292 _: Arc<Client>,
8293 mut cx: AsyncAppContext,
8294 ) -> Result<proto::ProjectEntryResponse> {
8295 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
8296 let worktree = this.update(&mut cx, |this, cx| {
8297 this.worktree_for_entry(entry_id, cx)
8298 .ok_or_else(|| anyhow!("worktree not found"))
8299 })??;
8300 let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())?;
8301 let entry = worktree
8302 .update(&mut cx, |worktree, cx| {
8303 let new_path = PathBuf::from(envelope.payload.new_path);
8304 worktree
8305 .as_local_mut()
8306 .unwrap()
8307 .copy_entry(entry_id, new_path, cx)
8308 })?
8309 .await?;
8310 Ok(proto::ProjectEntryResponse {
8311 entry: entry.as_ref().map(|e| e.into()),
8312 worktree_scan_id: worktree_scan_id as u64,
8313 })
8314 }
8315
8316 async fn handle_delete_project_entry(
8317 this: Model<Self>,
8318 envelope: TypedEnvelope<proto::DeleteProjectEntry>,
8319 _: Arc<Client>,
8320 mut cx: AsyncAppContext,
8321 ) -> Result<proto::ProjectEntryResponse> {
8322 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
8323
8324 this.update(&mut cx, |_, cx| cx.emit(Event::DeletedEntry(entry_id)))?;
8325
8326 let worktree = this.update(&mut cx, |this, cx| {
8327 this.worktree_for_entry(entry_id, cx)
8328 .ok_or_else(|| anyhow!("worktree not found"))
8329 })??;
8330 let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())?;
8331 worktree
8332 .update(&mut cx, |worktree, cx| {
8333 worktree
8334 .as_local_mut()
8335 .unwrap()
8336 .delete_entry(entry_id, cx)
8337 .ok_or_else(|| anyhow!("invalid entry"))
8338 })??
8339 .await?;
8340 Ok(proto::ProjectEntryResponse {
8341 entry: None,
8342 worktree_scan_id: worktree_scan_id as u64,
8343 })
8344 }
8345
8346 async fn handle_expand_project_entry(
8347 this: Model<Self>,
8348 envelope: TypedEnvelope<proto::ExpandProjectEntry>,
8349 _: Arc<Client>,
8350 mut cx: AsyncAppContext,
8351 ) -> Result<proto::ExpandProjectEntryResponse> {
8352 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
8353 let worktree = this
8354 .update(&mut cx, |this, cx| this.worktree_for_entry(entry_id, cx))?
8355 .ok_or_else(|| anyhow!("invalid request"))?;
8356 worktree
8357 .update(&mut cx, |worktree, cx| {
8358 worktree
8359 .as_local_mut()
8360 .unwrap()
8361 .expand_entry(entry_id, cx)
8362 .ok_or_else(|| anyhow!("invalid entry"))
8363 })??
8364 .await?;
8365 let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())? as u64;
8366 Ok(proto::ExpandProjectEntryResponse { worktree_scan_id })
8367 }
8368
8369 async fn handle_update_diagnostic_summary(
8370 this: Model<Self>,
8371 envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
8372 _: Arc<Client>,
8373 mut cx: AsyncAppContext,
8374 ) -> Result<()> {
8375 this.update(&mut cx, |this, cx| {
8376 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
8377 if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
8378 if let Some(summary) = envelope.payload.summary {
8379 let project_path = ProjectPath {
8380 worktree_id,
8381 path: Path::new(&summary.path).into(),
8382 };
8383 worktree.update(cx, |worktree, _| {
8384 worktree
8385 .as_remote_mut()
8386 .unwrap()
8387 .update_diagnostic_summary(project_path.path.clone(), &summary);
8388 });
8389 cx.emit(Event::DiagnosticsUpdated {
8390 language_server_id: LanguageServerId(summary.language_server_id as usize),
8391 path: project_path,
8392 });
8393 }
8394 }
8395 Ok(())
8396 })?
8397 }
8398
8399 async fn handle_start_language_server(
8400 this: Model<Self>,
8401 envelope: TypedEnvelope<proto::StartLanguageServer>,
8402 _: Arc<Client>,
8403 mut cx: AsyncAppContext,
8404 ) -> Result<()> {
8405 let server = envelope
8406 .payload
8407 .server
8408 .ok_or_else(|| anyhow!("invalid server"))?;
8409 this.update(&mut cx, |this, cx| {
8410 this.language_server_statuses.insert(
8411 LanguageServerId(server.id as usize),
8412 LanguageServerStatus {
8413 name: server.name,
8414 pending_work: Default::default(),
8415 has_pending_diagnostic_updates: false,
8416 progress_tokens: Default::default(),
8417 },
8418 );
8419 cx.notify();
8420 })?;
8421 Ok(())
8422 }
8423
8424 async fn handle_update_language_server(
8425 this: Model<Self>,
8426 envelope: TypedEnvelope<proto::UpdateLanguageServer>,
8427 _: Arc<Client>,
8428 mut cx: AsyncAppContext,
8429 ) -> Result<()> {
8430 this.update(&mut cx, |this, cx| {
8431 let language_server_id = LanguageServerId(envelope.payload.language_server_id as usize);
8432
8433 match envelope
8434 .payload
8435 .variant
8436 .ok_or_else(|| anyhow!("invalid variant"))?
8437 {
8438 proto::update_language_server::Variant::WorkStart(payload) => {
8439 this.on_lsp_work_start(
8440 language_server_id,
8441 payload.token,
8442 LanguageServerProgress {
8443 message: payload.message,
8444 percentage: payload.percentage.map(|p| p as usize),
8445 last_update_at: Instant::now(),
8446 },
8447 cx,
8448 );
8449 }
8450
8451 proto::update_language_server::Variant::WorkProgress(payload) => {
8452 this.on_lsp_work_progress(
8453 language_server_id,
8454 payload.token,
8455 LanguageServerProgress {
8456 message: payload.message,
8457 percentage: payload.percentage.map(|p| p as usize),
8458 last_update_at: Instant::now(),
8459 },
8460 cx,
8461 );
8462 }
8463
8464 proto::update_language_server::Variant::WorkEnd(payload) => {
8465 this.on_lsp_work_end(language_server_id, payload.token, cx);
8466 }
8467
8468 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(_) => {
8469 this.disk_based_diagnostics_started(language_server_id, cx);
8470 }
8471
8472 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(_) => {
8473 this.disk_based_diagnostics_finished(language_server_id, cx)
8474 }
8475 }
8476
8477 Ok(())
8478 })?
8479 }
8480
8481 async fn handle_update_buffer(
8482 this: Model<Self>,
8483 envelope: TypedEnvelope<proto::UpdateBuffer>,
8484 _: Arc<Client>,
8485 mut cx: AsyncAppContext,
8486 ) -> Result<proto::Ack> {
8487 this.update(&mut cx, |this, cx| {
8488 let payload = envelope.payload.clone();
8489 let buffer_id = BufferId::new(payload.buffer_id)?;
8490 let ops = payload
8491 .operations
8492 .into_iter()
8493 .map(language::proto::deserialize_operation)
8494 .collect::<Result<Vec<_>, _>>()?;
8495 let is_remote = this.is_remote();
8496 match this.opened_buffers.entry(buffer_id) {
8497 hash_map::Entry::Occupied(mut e) => match e.get_mut() {
8498 OpenBuffer::Strong(buffer) => {
8499 buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx))?;
8500 }
8501 OpenBuffer::Operations(operations) => operations.extend_from_slice(&ops),
8502 OpenBuffer::Weak(_) => {}
8503 },
8504 hash_map::Entry::Vacant(e) => {
8505 assert!(
8506 is_remote,
8507 "received buffer update from {:?}",
8508 envelope.original_sender_id
8509 );
8510 e.insert(OpenBuffer::Operations(ops));
8511 }
8512 }
8513 Ok(proto::Ack {})
8514 })?
8515 }
8516
8517 async fn handle_create_buffer_for_peer(
8518 this: Model<Self>,
8519 envelope: TypedEnvelope<proto::CreateBufferForPeer>,
8520 _: Arc<Client>,
8521 mut cx: AsyncAppContext,
8522 ) -> Result<()> {
8523 this.update(&mut cx, |this, cx| {
8524 match envelope
8525 .payload
8526 .variant
8527 .ok_or_else(|| anyhow!("missing variant"))?
8528 {
8529 proto::create_buffer_for_peer::Variant::State(mut state) => {
8530 let buffer_id = BufferId::new(state.id)?;
8531
8532 let buffer_result = maybe!({
8533 let mut buffer_file = None;
8534 if let Some(file) = state.file.take() {
8535 let worktree_id = WorktreeId::from_proto(file.worktree_id);
8536 let worktree =
8537 this.worktree_for_id(worktree_id, cx).ok_or_else(|| {
8538 anyhow!("no worktree found for id {}", file.worktree_id)
8539 })?;
8540 buffer_file =
8541 Some(Arc::new(File::from_proto(file, worktree.clone(), cx)?)
8542 as Arc<dyn language::File>);
8543 }
8544 Buffer::from_proto(this.replica_id(), this.capability(), state, buffer_file)
8545 });
8546
8547 match buffer_result {
8548 Ok(buffer) => {
8549 let buffer = cx.new_model(|_| buffer);
8550 this.incomplete_remote_buffers.insert(buffer_id, buffer);
8551 }
8552 Err(error) => {
8553 if let Some(listeners) = this.loading_buffers.remove(&buffer_id) {
8554 for listener in listeners {
8555 listener.send(Err(anyhow!(error.cloned()))).ok();
8556 }
8557 }
8558 }
8559 };
8560 }
8561 proto::create_buffer_for_peer::Variant::Chunk(chunk) => {
8562 let buffer_id = BufferId::new(chunk.buffer_id)?;
8563 let buffer = this
8564 .incomplete_remote_buffers
8565 .get(&buffer_id)
8566 .cloned()
8567 .ok_or_else(|| {
8568 anyhow!(
8569 "received chunk for buffer {} without initial state",
8570 chunk.buffer_id
8571 )
8572 })?;
8573
8574 let result = maybe!({
8575 let operations = chunk
8576 .operations
8577 .into_iter()
8578 .map(language::proto::deserialize_operation)
8579 .collect::<Result<Vec<_>>>()?;
8580 buffer.update(cx, |buffer, cx| buffer.apply_ops(operations, cx))
8581 });
8582
8583 if let Err(error) = result {
8584 this.incomplete_remote_buffers.remove(&buffer_id);
8585 if let Some(listeners) = this.loading_buffers.remove(&buffer_id) {
8586 for listener in listeners {
8587 listener.send(Err(error.cloned())).ok();
8588 }
8589 }
8590 } else {
8591 if chunk.is_last {
8592 this.incomplete_remote_buffers.remove(&buffer_id);
8593 this.register_buffer(&buffer, cx)?;
8594 }
8595 }
8596 }
8597 }
8598
8599 Ok(())
8600 })?
8601 }
8602
8603 async fn handle_update_diff_base(
8604 this: Model<Self>,
8605 envelope: TypedEnvelope<proto::UpdateDiffBase>,
8606 _: Arc<Client>,
8607 mut cx: AsyncAppContext,
8608 ) -> Result<()> {
8609 this.update(&mut cx, |this, cx| {
8610 let buffer_id = envelope.payload.buffer_id;
8611 let buffer_id = BufferId::new(buffer_id)?;
8612 let diff_base = envelope.payload.diff_base;
8613 if let Some(buffer) = this
8614 .opened_buffers
8615 .get_mut(&buffer_id)
8616 .and_then(|b| b.upgrade())
8617 .or_else(|| this.incomplete_remote_buffers.get(&buffer_id).cloned())
8618 {
8619 buffer.update(cx, |buffer, cx| buffer.set_diff_base(diff_base, cx));
8620 }
8621 Ok(())
8622 })?
8623 }
8624
8625 async fn handle_update_buffer_file(
8626 this: Model<Self>,
8627 envelope: TypedEnvelope<proto::UpdateBufferFile>,
8628 _: Arc<Client>,
8629 mut cx: AsyncAppContext,
8630 ) -> Result<()> {
8631 let buffer_id = envelope.payload.buffer_id;
8632 let buffer_id = BufferId::new(buffer_id)?;
8633
8634 this.update(&mut cx, |this, cx| {
8635 let payload = envelope.payload.clone();
8636 if let Some(buffer) = this
8637 .opened_buffers
8638 .get(&buffer_id)
8639 .and_then(|b| b.upgrade())
8640 .or_else(|| this.incomplete_remote_buffers.get(&buffer_id).cloned())
8641 {
8642 let file = payload.file.ok_or_else(|| anyhow!("invalid file"))?;
8643 let worktree = this
8644 .worktree_for_id(WorktreeId::from_proto(file.worktree_id), cx)
8645 .ok_or_else(|| anyhow!("no such worktree"))?;
8646 let file = File::from_proto(file, worktree, cx)?;
8647 buffer.update(cx, |buffer, cx| {
8648 buffer.file_updated(Arc::new(file), cx);
8649 });
8650 this.detect_language_for_buffer(&buffer, cx);
8651 }
8652 Ok(())
8653 })?
8654 }
8655
8656 async fn handle_save_buffer(
8657 this: Model<Self>,
8658 envelope: TypedEnvelope<proto::SaveBuffer>,
8659 _: Arc<Client>,
8660 mut cx: AsyncAppContext,
8661 ) -> Result<proto::BufferSaved> {
8662 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
8663 let (project_id, buffer) = this.update(&mut cx, |this, _cx| {
8664 let project_id = this.remote_id().ok_or_else(|| anyhow!("not connected"))?;
8665 let buffer = this
8666 .opened_buffers
8667 .get(&buffer_id)
8668 .and_then(|buffer| buffer.upgrade())
8669 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
8670 anyhow::Ok((project_id, buffer))
8671 })??;
8672 buffer
8673 .update(&mut cx, |buffer, _| {
8674 buffer.wait_for_version(deserialize_version(&envelope.payload.version))
8675 })?
8676 .await?;
8677 let buffer_id = buffer.update(&mut cx, |buffer, _| buffer.remote_id())?;
8678
8679 this.update(&mut cx, |this, cx| this.save_buffer(buffer.clone(), cx))?
8680 .await?;
8681 buffer.update(&mut cx, |buffer, _| proto::BufferSaved {
8682 project_id,
8683 buffer_id: buffer_id.into(),
8684 version: serialize_version(buffer.saved_version()),
8685 mtime: buffer.saved_mtime().map(|time| time.into()),
8686 })
8687 }
8688
8689 async fn handle_reload_buffers(
8690 this: Model<Self>,
8691 envelope: TypedEnvelope<proto::ReloadBuffers>,
8692 _: Arc<Client>,
8693 mut cx: AsyncAppContext,
8694 ) -> Result<proto::ReloadBuffersResponse> {
8695 let sender_id = envelope.original_sender_id()?;
8696 let reload = this.update(&mut cx, |this, cx| {
8697 let mut buffers = HashSet::default();
8698 for buffer_id in &envelope.payload.buffer_ids {
8699 let buffer_id = BufferId::new(*buffer_id)?;
8700 buffers.insert(
8701 this.opened_buffers
8702 .get(&buffer_id)
8703 .and_then(|buffer| buffer.upgrade())
8704 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
8705 );
8706 }
8707 Ok::<_, anyhow::Error>(this.reload_buffers(buffers, false, cx))
8708 })??;
8709
8710 let project_transaction = reload.await?;
8711 let project_transaction = this.update(&mut cx, |this, cx| {
8712 this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
8713 })?;
8714 Ok(proto::ReloadBuffersResponse {
8715 transaction: Some(project_transaction),
8716 })
8717 }
8718
8719 async fn handle_synchronize_buffers(
8720 this: Model<Self>,
8721 envelope: TypedEnvelope<proto::SynchronizeBuffers>,
8722 _: Arc<Client>,
8723 mut cx: AsyncAppContext,
8724 ) -> Result<proto::SynchronizeBuffersResponse> {
8725 let project_id = envelope.payload.project_id;
8726 let mut response = proto::SynchronizeBuffersResponse {
8727 buffers: Default::default(),
8728 };
8729
8730 this.update(&mut cx, |this, cx| {
8731 let Some(guest_id) = envelope.original_sender_id else {
8732 error!("missing original_sender_id on SynchronizeBuffers request");
8733 bail!("missing original_sender_id on SynchronizeBuffers request");
8734 };
8735
8736 this.shared_buffers.entry(guest_id).or_default().clear();
8737 for buffer in envelope.payload.buffers {
8738 let buffer_id = BufferId::new(buffer.id)?;
8739 let remote_version = language::proto::deserialize_version(&buffer.version);
8740 if let Some(buffer) = this.buffer_for_id(buffer_id) {
8741 this.shared_buffers
8742 .entry(guest_id)
8743 .or_default()
8744 .insert(buffer_id);
8745
8746 let buffer = buffer.read(cx);
8747 response.buffers.push(proto::BufferVersion {
8748 id: buffer_id.into(),
8749 version: language::proto::serialize_version(&buffer.version),
8750 });
8751
8752 let operations = buffer.serialize_ops(Some(remote_version), cx);
8753 let client = this.client.clone();
8754 if let Some(file) = buffer.file() {
8755 client
8756 .send(proto::UpdateBufferFile {
8757 project_id,
8758 buffer_id: buffer_id.into(),
8759 file: Some(file.to_proto()),
8760 })
8761 .log_err();
8762 }
8763
8764 client
8765 .send(proto::UpdateDiffBase {
8766 project_id,
8767 buffer_id: buffer_id.into(),
8768 diff_base: buffer.diff_base().map(Into::into),
8769 })
8770 .log_err();
8771
8772 client
8773 .send(proto::BufferReloaded {
8774 project_id,
8775 buffer_id: buffer_id.into(),
8776 version: language::proto::serialize_version(buffer.saved_version()),
8777 mtime: buffer.saved_mtime().map(|time| time.into()),
8778 line_ending: language::proto::serialize_line_ending(
8779 buffer.line_ending(),
8780 ) as i32,
8781 })
8782 .log_err();
8783
8784 cx.background_executor()
8785 .spawn(
8786 async move {
8787 let operations = operations.await;
8788 for chunk in split_operations(operations) {
8789 client
8790 .request(proto::UpdateBuffer {
8791 project_id,
8792 buffer_id: buffer_id.into(),
8793 operations: chunk,
8794 })
8795 .await?;
8796 }
8797 anyhow::Ok(())
8798 }
8799 .log_err(),
8800 )
8801 .detach();
8802 }
8803 }
8804 Ok(())
8805 })??;
8806
8807 Ok(response)
8808 }
8809
8810 async fn handle_format_buffers(
8811 this: Model<Self>,
8812 envelope: TypedEnvelope<proto::FormatBuffers>,
8813 _: Arc<Client>,
8814 mut cx: AsyncAppContext,
8815 ) -> Result<proto::FormatBuffersResponse> {
8816 let sender_id = envelope.original_sender_id()?;
8817 let format = this.update(&mut cx, |this, cx| {
8818 let mut buffers = HashSet::default();
8819 for buffer_id in &envelope.payload.buffer_ids {
8820 let buffer_id = BufferId::new(*buffer_id)?;
8821 buffers.insert(
8822 this.opened_buffers
8823 .get(&buffer_id)
8824 .and_then(|buffer| buffer.upgrade())
8825 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
8826 );
8827 }
8828 let trigger = FormatTrigger::from_proto(envelope.payload.trigger);
8829 Ok::<_, anyhow::Error>(this.format(buffers, false, trigger, cx))
8830 })??;
8831
8832 let project_transaction = format.await?;
8833 let project_transaction = this.update(&mut cx, |this, cx| {
8834 this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
8835 })?;
8836 Ok(proto::FormatBuffersResponse {
8837 transaction: Some(project_transaction),
8838 })
8839 }
8840
8841 async fn handle_apply_additional_edits_for_completion(
8842 this: Model<Self>,
8843 envelope: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
8844 _: Arc<Client>,
8845 mut cx: AsyncAppContext,
8846 ) -> Result<proto::ApplyCompletionAdditionalEditsResponse> {
8847 let (buffer, completion) = this.update(&mut cx, |this, _| {
8848 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
8849 let buffer = this
8850 .opened_buffers
8851 .get(&buffer_id)
8852 .and_then(|buffer| buffer.upgrade())
8853 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
8854 let completion = Self::deserialize_completion(
8855 envelope
8856 .payload
8857 .completion
8858 .ok_or_else(|| anyhow!("invalid completion"))?,
8859 )?;
8860 anyhow::Ok((buffer, completion))
8861 })??;
8862
8863 let apply_additional_edits = this.update(&mut cx, |this, cx| {
8864 this.apply_additional_edits_for_completion(
8865 buffer,
8866 Completion {
8867 old_range: completion.old_range,
8868 new_text: completion.new_text,
8869 lsp_completion: completion.lsp_completion,
8870 server_id: completion.server_id,
8871 documentation: None,
8872 label: CodeLabel {
8873 text: Default::default(),
8874 runs: Default::default(),
8875 filter_range: Default::default(),
8876 },
8877 },
8878 false,
8879 cx,
8880 )
8881 })?;
8882
8883 Ok(proto::ApplyCompletionAdditionalEditsResponse {
8884 transaction: apply_additional_edits
8885 .await?
8886 .as_ref()
8887 .map(language::proto::serialize_transaction),
8888 })
8889 }
8890
8891 async fn handle_resolve_completion_documentation(
8892 this: Model<Self>,
8893 envelope: TypedEnvelope<proto::ResolveCompletionDocumentation>,
8894 _: Arc<Client>,
8895 mut cx: AsyncAppContext,
8896 ) -> Result<proto::ResolveCompletionDocumentationResponse> {
8897 let lsp_completion = serde_json::from_slice(&envelope.payload.lsp_completion)?;
8898
8899 let completion = this
8900 .read_with(&mut cx, |this, _| {
8901 let id = LanguageServerId(envelope.payload.language_server_id as usize);
8902 let Some(server) = this.language_server_for_id(id) else {
8903 return Err(anyhow!("No language server {id}"));
8904 };
8905
8906 Ok(server.request::<lsp::request::ResolveCompletionItem>(lsp_completion))
8907 })??
8908 .await?;
8909
8910 let mut is_markdown = false;
8911 let text = match completion.documentation {
8912 Some(lsp::Documentation::String(text)) => text,
8913
8914 Some(lsp::Documentation::MarkupContent(lsp::MarkupContent { kind, value })) => {
8915 is_markdown = kind == lsp::MarkupKind::Markdown;
8916 value
8917 }
8918
8919 _ => String::new(),
8920 };
8921
8922 Ok(proto::ResolveCompletionDocumentationResponse { text, is_markdown })
8923 }
8924
8925 async fn handle_apply_code_action(
8926 this: Model<Self>,
8927 envelope: TypedEnvelope<proto::ApplyCodeAction>,
8928 _: Arc<Client>,
8929 mut cx: AsyncAppContext,
8930 ) -> Result<proto::ApplyCodeActionResponse> {
8931 let sender_id = envelope.original_sender_id()?;
8932 let action = Self::deserialize_code_action(
8933 envelope
8934 .payload
8935 .action
8936 .ok_or_else(|| anyhow!("invalid action"))?,
8937 )?;
8938 let apply_code_action = this.update(&mut cx, |this, cx| {
8939 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
8940 let buffer = this
8941 .opened_buffers
8942 .get(&buffer_id)
8943 .and_then(|buffer| buffer.upgrade())
8944 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
8945 Ok::<_, anyhow::Error>(this.apply_code_action(buffer, action, false, cx))
8946 })??;
8947
8948 let project_transaction = apply_code_action.await?;
8949 let project_transaction = this.update(&mut cx, |this, cx| {
8950 this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
8951 })?;
8952 Ok(proto::ApplyCodeActionResponse {
8953 transaction: Some(project_transaction),
8954 })
8955 }
8956
8957 async fn handle_on_type_formatting(
8958 this: Model<Self>,
8959 envelope: TypedEnvelope<proto::OnTypeFormatting>,
8960 _: Arc<Client>,
8961 mut cx: AsyncAppContext,
8962 ) -> Result<proto::OnTypeFormattingResponse> {
8963 let on_type_formatting = this.update(&mut cx, |this, cx| {
8964 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
8965 let buffer = this
8966 .opened_buffers
8967 .get(&buffer_id)
8968 .and_then(|buffer| buffer.upgrade())
8969 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
8970 let position = envelope
8971 .payload
8972 .position
8973 .and_then(deserialize_anchor)
8974 .ok_or_else(|| anyhow!("invalid position"))?;
8975 Ok::<_, anyhow::Error>(this.apply_on_type_formatting(
8976 buffer,
8977 position,
8978 envelope.payload.trigger.clone(),
8979 cx,
8980 ))
8981 })??;
8982
8983 let transaction = on_type_formatting
8984 .await?
8985 .as_ref()
8986 .map(language::proto::serialize_transaction);
8987 Ok(proto::OnTypeFormattingResponse { transaction })
8988 }
8989
8990 async fn handle_inlay_hints(
8991 this: Model<Self>,
8992 envelope: TypedEnvelope<proto::InlayHints>,
8993 _: Arc<Client>,
8994 mut cx: AsyncAppContext,
8995 ) -> Result<proto::InlayHintsResponse> {
8996 let sender_id = envelope.original_sender_id()?;
8997 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
8998 let buffer = this.update(&mut cx, |this, _| {
8999 this.opened_buffers
9000 .get(&buffer_id)
9001 .and_then(|buffer| buffer.upgrade())
9002 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
9003 })??;
9004 buffer
9005 .update(&mut cx, |buffer, _| {
9006 buffer.wait_for_version(deserialize_version(&envelope.payload.version))
9007 })?
9008 .await
9009 .with_context(|| format!("waiting for version for buffer {}", buffer.entity_id()))?;
9010
9011 let start = envelope
9012 .payload
9013 .start
9014 .and_then(deserialize_anchor)
9015 .context("missing range start")?;
9016 let end = envelope
9017 .payload
9018 .end
9019 .and_then(deserialize_anchor)
9020 .context("missing range end")?;
9021 let buffer_hints = this
9022 .update(&mut cx, |project, cx| {
9023 project.inlay_hints(buffer.clone(), start..end, cx)
9024 })?
9025 .await
9026 .context("inlay hints fetch")?;
9027
9028 this.update(&mut cx, |project, cx| {
9029 InlayHints::response_to_proto(
9030 buffer_hints,
9031 project,
9032 sender_id,
9033 &buffer.read(cx).version(),
9034 cx,
9035 )
9036 })
9037 }
9038
9039 async fn handle_resolve_inlay_hint(
9040 this: Model<Self>,
9041 envelope: TypedEnvelope<proto::ResolveInlayHint>,
9042 _: Arc<Client>,
9043 mut cx: AsyncAppContext,
9044 ) -> Result<proto::ResolveInlayHintResponse> {
9045 let proto_hint = envelope
9046 .payload
9047 .hint
9048 .expect("incorrect protobuf resolve inlay hint message: missing the inlay hint");
9049 let hint = InlayHints::proto_to_project_hint(proto_hint)
9050 .context("resolved proto inlay hint conversion")?;
9051 let buffer = this.update(&mut cx, |this, _cx| {
9052 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
9053 this.opened_buffers
9054 .get(&buffer_id)
9055 .and_then(|buffer| buffer.upgrade())
9056 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
9057 })??;
9058 let response_hint = this
9059 .update(&mut cx, |project, cx| {
9060 project.resolve_inlay_hint(
9061 hint,
9062 buffer,
9063 LanguageServerId(envelope.payload.language_server_id as usize),
9064 cx,
9065 )
9066 })?
9067 .await
9068 .context("inlay hints fetch")?;
9069 Ok(proto::ResolveInlayHintResponse {
9070 hint: Some(InlayHints::project_to_proto_hint(response_hint)),
9071 })
9072 }
9073
9074 async fn try_resolve_code_action(
9075 lang_server: &LanguageServer,
9076 action: &mut CodeAction,
9077 ) -> anyhow::Result<()> {
9078 if GetCodeActions::can_resolve_actions(&lang_server.capabilities()) {
9079 if action.lsp_action.data.is_some()
9080 && (action.lsp_action.command.is_none() || action.lsp_action.edit.is_none())
9081 {
9082 action.lsp_action = lang_server
9083 .request::<lsp::request::CodeActionResolveRequest>(action.lsp_action.clone())
9084 .await?;
9085 }
9086 }
9087
9088 anyhow::Ok(())
9089 }
9090
9091 async fn execute_code_actions_on_servers(
9092 project: &WeakModel<Project>,
9093 adapters_and_servers: &Vec<(Arc<CachedLspAdapter>, Arc<LanguageServer>)>,
9094 code_actions: Vec<lsp::CodeActionKind>,
9095 buffer: &Model<Buffer>,
9096 push_to_history: bool,
9097 project_transaction: &mut ProjectTransaction,
9098 cx: &mut AsyncAppContext,
9099 ) -> Result<(), anyhow::Error> {
9100 for (lsp_adapter, language_server) in adapters_and_servers.iter() {
9101 let code_actions = code_actions.clone();
9102
9103 let actions = project
9104 .update(cx, move |this, cx| {
9105 let request = GetCodeActions {
9106 range: text::Anchor::MIN..text::Anchor::MAX,
9107 kinds: Some(code_actions),
9108 };
9109 let server = LanguageServerToQuery::Other(language_server.server_id());
9110 this.request_lsp(buffer.clone(), server, request, cx)
9111 })?
9112 .await?;
9113
9114 for mut action in actions {
9115 Self::try_resolve_code_action(&language_server, &mut action)
9116 .await
9117 .context("resolving a formatting code action")?;
9118
9119 if let Some(edit) = action.lsp_action.edit {
9120 if edit.changes.is_none() && edit.document_changes.is_none() {
9121 continue;
9122 }
9123
9124 let new = Self::deserialize_workspace_edit(
9125 project
9126 .upgrade()
9127 .ok_or_else(|| anyhow!("project dropped"))?,
9128 edit,
9129 push_to_history,
9130 lsp_adapter.clone(),
9131 language_server.clone(),
9132 cx,
9133 )
9134 .await?;
9135 project_transaction.0.extend(new.0);
9136 }
9137
9138 if let Some(command) = action.lsp_action.command {
9139 project.update(cx, |this, _| {
9140 this.last_workspace_edits_by_language_server
9141 .remove(&language_server.server_id());
9142 })?;
9143
9144 language_server
9145 .request::<lsp::request::ExecuteCommand>(lsp::ExecuteCommandParams {
9146 command: command.command,
9147 arguments: command.arguments.unwrap_or_default(),
9148 ..Default::default()
9149 })
9150 .await?;
9151
9152 project.update(cx, |this, _| {
9153 project_transaction.0.extend(
9154 this.last_workspace_edits_by_language_server
9155 .remove(&language_server.server_id())
9156 .unwrap_or_default()
9157 .0,
9158 )
9159 })?;
9160 }
9161 }
9162 }
9163
9164 Ok(())
9165 }
9166
9167 async fn handle_refresh_inlay_hints(
9168 this: Model<Self>,
9169 _: TypedEnvelope<proto::RefreshInlayHints>,
9170 _: Arc<Client>,
9171 mut cx: AsyncAppContext,
9172 ) -> Result<proto::Ack> {
9173 this.update(&mut cx, |_, cx| {
9174 cx.emit(Event::RefreshInlayHints);
9175 })?;
9176 Ok(proto::Ack {})
9177 }
9178
9179 async fn handle_lsp_command<T: LspCommand>(
9180 this: Model<Self>,
9181 envelope: TypedEnvelope<T::ProtoRequest>,
9182 _: Arc<Client>,
9183 mut cx: AsyncAppContext,
9184 ) -> Result<<T::ProtoRequest as proto::RequestMessage>::Response>
9185 where
9186 <T::LspRequest as lsp::request::Request>::Params: Send,
9187 <T::LspRequest as lsp::request::Request>::Result: Send,
9188 {
9189 let sender_id = envelope.original_sender_id()?;
9190 let buffer_id = T::buffer_id_from_proto(&envelope.payload)?;
9191 let buffer_handle = this.update(&mut cx, |this, _cx| {
9192 this.opened_buffers
9193 .get(&buffer_id)
9194 .and_then(|buffer| buffer.upgrade())
9195 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
9196 })??;
9197 let request = T::from_proto(
9198 envelope.payload,
9199 this.clone(),
9200 buffer_handle.clone(),
9201 cx.clone(),
9202 )
9203 .await?;
9204 let response = this
9205 .update(&mut cx, |this, cx| {
9206 this.request_lsp(
9207 buffer_handle.clone(),
9208 LanguageServerToQuery::Primary,
9209 request,
9210 cx,
9211 )
9212 })?
9213 .await?;
9214 this.update(&mut cx, |this, cx| {
9215 Ok(T::response_to_proto(
9216 response,
9217 this,
9218 sender_id,
9219 &buffer_handle.read(cx).version(),
9220 cx,
9221 ))
9222 })?
9223 }
9224
9225 async fn handle_get_project_symbols(
9226 this: Model<Self>,
9227 envelope: TypedEnvelope<proto::GetProjectSymbols>,
9228 _: Arc<Client>,
9229 mut cx: AsyncAppContext,
9230 ) -> Result<proto::GetProjectSymbolsResponse> {
9231 let symbols = this
9232 .update(&mut cx, |this, cx| {
9233 this.symbols(&envelope.payload.query, cx)
9234 })?
9235 .await?;
9236
9237 Ok(proto::GetProjectSymbolsResponse {
9238 symbols: symbols.iter().map(serialize_symbol).collect(),
9239 })
9240 }
9241
9242 async fn handle_search_project(
9243 this: Model<Self>,
9244 envelope: TypedEnvelope<proto::SearchProject>,
9245 _: Arc<Client>,
9246 mut cx: AsyncAppContext,
9247 ) -> Result<proto::SearchProjectResponse> {
9248 let peer_id = envelope.original_sender_id()?;
9249 let query = SearchQuery::from_proto(envelope.payload)?;
9250 let mut result = this.update(&mut cx, |this, cx| this.search(query, cx))?;
9251
9252 cx.spawn(move |mut cx| async move {
9253 let mut locations = Vec::new();
9254 let mut limit_reached = false;
9255 while let Some(result) = result.next().await {
9256 match result {
9257 SearchResult::Buffer { buffer, ranges } => {
9258 for range in ranges {
9259 let start = serialize_anchor(&range.start);
9260 let end = serialize_anchor(&range.end);
9261 let buffer_id = this.update(&mut cx, |this, cx| {
9262 this.create_buffer_for_peer(&buffer, peer_id, cx).into()
9263 })?;
9264 locations.push(proto::Location {
9265 buffer_id,
9266 start: Some(start),
9267 end: Some(end),
9268 });
9269 }
9270 }
9271 SearchResult::LimitReached => limit_reached = true,
9272 }
9273 }
9274 Ok(proto::SearchProjectResponse {
9275 locations,
9276 limit_reached,
9277 })
9278 })
9279 .await
9280 }
9281
9282 async fn handle_open_buffer_for_symbol(
9283 this: Model<Self>,
9284 envelope: TypedEnvelope<proto::OpenBufferForSymbol>,
9285 _: Arc<Client>,
9286 mut cx: AsyncAppContext,
9287 ) -> Result<proto::OpenBufferForSymbolResponse> {
9288 let peer_id = envelope.original_sender_id()?;
9289 let symbol = envelope
9290 .payload
9291 .symbol
9292 .ok_or_else(|| anyhow!("invalid symbol"))?;
9293 let symbol = Self::deserialize_symbol(symbol)?;
9294 let symbol = this.update(&mut cx, |this, _| {
9295 let signature = this.symbol_signature(&symbol.path);
9296 if signature == symbol.signature {
9297 Ok(symbol)
9298 } else {
9299 Err(anyhow!("invalid symbol signature"))
9300 }
9301 })??;
9302 let buffer = this
9303 .update(&mut cx, |this, cx| {
9304 this.open_buffer_for_symbol(
9305 &Symbol {
9306 language_server_name: symbol.language_server_name,
9307 source_worktree_id: symbol.source_worktree_id,
9308 path: symbol.path,
9309 name: symbol.name,
9310 kind: symbol.kind,
9311 range: symbol.range,
9312 signature: symbol.signature,
9313 label: CodeLabel {
9314 text: Default::default(),
9315 runs: Default::default(),
9316 filter_range: Default::default(),
9317 },
9318 },
9319 cx,
9320 )
9321 })?
9322 .await?;
9323
9324 this.update(&mut cx, |this, cx| {
9325 let is_private = buffer
9326 .read(cx)
9327 .file()
9328 .map(|f| f.is_private())
9329 .unwrap_or_default();
9330 if is_private {
9331 Err(anyhow!(ErrorCode::UnsharedItem))
9332 } else {
9333 Ok(proto::OpenBufferForSymbolResponse {
9334 buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx).into(),
9335 })
9336 }
9337 })?
9338 }
9339
9340 fn symbol_signature(&self, project_path: &ProjectPath) -> [u8; 32] {
9341 let mut hasher = Sha256::new();
9342 hasher.update(project_path.worktree_id.to_proto().to_be_bytes());
9343 hasher.update(project_path.path.to_string_lossy().as_bytes());
9344 hasher.update(self.nonce.to_be_bytes());
9345 hasher.finalize().as_slice().try_into().unwrap()
9346 }
9347
9348 async fn handle_open_buffer_by_id(
9349 this: Model<Self>,
9350 envelope: TypedEnvelope<proto::OpenBufferById>,
9351 _: Arc<Client>,
9352 mut cx: AsyncAppContext,
9353 ) -> Result<proto::OpenBufferResponse> {
9354 let peer_id = envelope.original_sender_id()?;
9355 let buffer_id = BufferId::new(envelope.payload.id)?;
9356 let buffer = this
9357 .update(&mut cx, |this, cx| this.open_buffer_by_id(buffer_id, cx))?
9358 .await?;
9359 Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
9360 }
9361
9362 async fn handle_open_buffer_by_path(
9363 this: Model<Self>,
9364 envelope: TypedEnvelope<proto::OpenBufferByPath>,
9365 _: Arc<Client>,
9366 mut cx: AsyncAppContext,
9367 ) -> Result<proto::OpenBufferResponse> {
9368 let peer_id = envelope.original_sender_id()?;
9369 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
9370 let open_buffer = this.update(&mut cx, |this, cx| {
9371 this.open_buffer(
9372 ProjectPath {
9373 worktree_id,
9374 path: PathBuf::from(envelope.payload.path).into(),
9375 },
9376 cx,
9377 )
9378 })?;
9379
9380 let buffer = open_buffer.await?;
9381 Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
9382 }
9383
9384 fn respond_to_open_buffer_request(
9385 this: Model<Self>,
9386 buffer: Model<Buffer>,
9387 peer_id: proto::PeerId,
9388 cx: &mut AsyncAppContext,
9389 ) -> Result<proto::OpenBufferResponse> {
9390 this.update(cx, |this, cx| {
9391 let is_private = buffer
9392 .read(cx)
9393 .file()
9394 .map(|f| f.is_private())
9395 .unwrap_or_default();
9396 if is_private {
9397 Err(anyhow!(ErrorCode::UnsharedItem))
9398 } else {
9399 Ok(proto::OpenBufferResponse {
9400 buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx).into(),
9401 })
9402 }
9403 })?
9404 }
9405
9406 fn serialize_project_transaction_for_peer(
9407 &mut self,
9408 project_transaction: ProjectTransaction,
9409 peer_id: proto::PeerId,
9410 cx: &mut AppContext,
9411 ) -> proto::ProjectTransaction {
9412 let mut serialized_transaction = proto::ProjectTransaction {
9413 buffer_ids: Default::default(),
9414 transactions: Default::default(),
9415 };
9416 for (buffer, transaction) in project_transaction.0 {
9417 serialized_transaction
9418 .buffer_ids
9419 .push(self.create_buffer_for_peer(&buffer, peer_id, cx).into());
9420 serialized_transaction
9421 .transactions
9422 .push(language::proto::serialize_transaction(&transaction));
9423 }
9424 serialized_transaction
9425 }
9426
9427 fn deserialize_project_transaction(
9428 &mut self,
9429 message: proto::ProjectTransaction,
9430 push_to_history: bool,
9431 cx: &mut ModelContext<Self>,
9432 ) -> Task<Result<ProjectTransaction>> {
9433 cx.spawn(move |this, mut cx| async move {
9434 let mut project_transaction = ProjectTransaction::default();
9435 for (buffer_id, transaction) in message.buffer_ids.into_iter().zip(message.transactions)
9436 {
9437 let buffer_id = BufferId::new(buffer_id)?;
9438 let buffer = this
9439 .update(&mut cx, |this, cx| {
9440 this.wait_for_remote_buffer(buffer_id, cx)
9441 })?
9442 .await?;
9443 let transaction = language::proto::deserialize_transaction(transaction)?;
9444 project_transaction.0.insert(buffer, transaction);
9445 }
9446
9447 for (buffer, transaction) in &project_transaction.0 {
9448 buffer
9449 .update(&mut cx, |buffer, _| {
9450 buffer.wait_for_edits(transaction.edit_ids.iter().copied())
9451 })?
9452 .await?;
9453
9454 if push_to_history {
9455 buffer.update(&mut cx, |buffer, _| {
9456 buffer.push_transaction(transaction.clone(), Instant::now());
9457 })?;
9458 }
9459 }
9460
9461 Ok(project_transaction)
9462 })
9463 }
9464
9465 fn create_buffer_for_peer(
9466 &mut self,
9467 buffer: &Model<Buffer>,
9468 peer_id: proto::PeerId,
9469 cx: &mut AppContext,
9470 ) -> BufferId {
9471 let buffer_id = buffer.read(cx).remote_id();
9472 if let ProjectClientState::Shared { updates_tx, .. } = &self.client_state {
9473 updates_tx
9474 .unbounded_send(LocalProjectUpdate::CreateBufferForPeer { peer_id, buffer_id })
9475 .ok();
9476 }
9477 buffer_id
9478 }
9479
9480 fn wait_for_remote_buffer(
9481 &mut self,
9482 id: BufferId,
9483 cx: &mut ModelContext<Self>,
9484 ) -> Task<Result<Model<Buffer>>> {
9485 let buffer = self
9486 .opened_buffers
9487 .get(&id)
9488 .and_then(|buffer| buffer.upgrade());
9489
9490 if let Some(buffer) = buffer {
9491 return Task::ready(Ok(buffer));
9492 }
9493
9494 let (tx, rx) = oneshot::channel();
9495 self.loading_buffers.entry(id).or_default().push(tx);
9496
9497 cx.background_executor().spawn(async move { rx.await? })
9498 }
9499
9500 fn synchronize_remote_buffers(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
9501 let project_id = match self.client_state {
9502 ProjectClientState::Remote {
9503 sharing_has_stopped,
9504 remote_id,
9505 ..
9506 } => {
9507 if sharing_has_stopped {
9508 return Task::ready(Err(anyhow!(
9509 "can't synchronize remote buffers on a readonly project"
9510 )));
9511 } else {
9512 remote_id
9513 }
9514 }
9515 ProjectClientState::Shared { .. } | ProjectClientState::Local => {
9516 return Task::ready(Err(anyhow!(
9517 "can't synchronize remote buffers on a local project"
9518 )))
9519 }
9520 };
9521
9522 let client = self.client.clone();
9523 cx.spawn(move |this, mut cx| async move {
9524 let (buffers, incomplete_buffer_ids) = this.update(&mut cx, |this, cx| {
9525 let buffers = this
9526 .opened_buffers
9527 .iter()
9528 .filter_map(|(id, buffer)| {
9529 let buffer = buffer.upgrade()?;
9530 Some(proto::BufferVersion {
9531 id: (*id).into(),
9532 version: language::proto::serialize_version(&buffer.read(cx).version),
9533 })
9534 })
9535 .collect();
9536 let incomplete_buffer_ids = this
9537 .incomplete_remote_buffers
9538 .keys()
9539 .copied()
9540 .collect::<Vec<_>>();
9541
9542 (buffers, incomplete_buffer_ids)
9543 })?;
9544 let response = client
9545 .request(proto::SynchronizeBuffers {
9546 project_id,
9547 buffers,
9548 })
9549 .await?;
9550
9551 let send_updates_for_buffers = this.update(&mut cx, |this, cx| {
9552 response
9553 .buffers
9554 .into_iter()
9555 .map(|buffer| {
9556 let client = client.clone();
9557 let buffer_id = match BufferId::new(buffer.id) {
9558 Ok(id) => id,
9559 Err(e) => {
9560 return Task::ready(Err(e));
9561 }
9562 };
9563 let remote_version = language::proto::deserialize_version(&buffer.version);
9564 if let Some(buffer) = this.buffer_for_id(buffer_id) {
9565 let operations =
9566 buffer.read(cx).serialize_ops(Some(remote_version), cx);
9567 cx.background_executor().spawn(async move {
9568 let operations = operations.await;
9569 for chunk in split_operations(operations) {
9570 client
9571 .request(proto::UpdateBuffer {
9572 project_id,
9573 buffer_id: buffer_id.into(),
9574 operations: chunk,
9575 })
9576 .await?;
9577 }
9578 anyhow::Ok(())
9579 })
9580 } else {
9581 Task::ready(Ok(()))
9582 }
9583 })
9584 .collect::<Vec<_>>()
9585 })?;
9586
9587 // Any incomplete buffers have open requests waiting. Request that the host sends
9588 // creates these buffers for us again to unblock any waiting futures.
9589 for id in incomplete_buffer_ids {
9590 cx.background_executor()
9591 .spawn(client.request(proto::OpenBufferById {
9592 project_id,
9593 id: id.into(),
9594 }))
9595 .detach();
9596 }
9597
9598 futures::future::join_all(send_updates_for_buffers)
9599 .await
9600 .into_iter()
9601 .collect()
9602 })
9603 }
9604
9605 pub fn worktree_metadata_protos(&self, cx: &AppContext) -> Vec<proto::WorktreeMetadata> {
9606 self.worktrees()
9607 .map(|worktree| {
9608 let worktree = worktree.read(cx);
9609 proto::WorktreeMetadata {
9610 id: worktree.id().to_proto(),
9611 root_name: worktree.root_name().into(),
9612 visible: worktree.is_visible(),
9613 abs_path: worktree.abs_path().to_string_lossy().into(),
9614 }
9615 })
9616 .collect()
9617 }
9618
9619 fn set_worktrees_from_proto(
9620 &mut self,
9621 worktrees: Vec<proto::WorktreeMetadata>,
9622 cx: &mut ModelContext<Project>,
9623 ) -> Result<()> {
9624 let replica_id = self.replica_id();
9625 let remote_id = self.remote_id().ok_or_else(|| anyhow!("invalid project"))?;
9626
9627 let mut old_worktrees_by_id = self
9628 .worktrees
9629 .drain(..)
9630 .filter_map(|worktree| {
9631 let worktree = worktree.upgrade()?;
9632 Some((worktree.read(cx).id(), worktree))
9633 })
9634 .collect::<HashMap<_, _>>();
9635
9636 for worktree in worktrees {
9637 if let Some(old_worktree) =
9638 old_worktrees_by_id.remove(&WorktreeId::from_proto(worktree.id))
9639 {
9640 self.worktrees.push(WorktreeHandle::Strong(old_worktree));
9641 } else {
9642 let worktree =
9643 Worktree::remote(remote_id, replica_id, worktree, self.client.clone(), cx);
9644 let _ = self.add_worktree(&worktree, cx);
9645 }
9646 }
9647
9648 self.metadata_changed(cx);
9649 for id in old_worktrees_by_id.keys() {
9650 cx.emit(Event::WorktreeRemoved(*id));
9651 }
9652
9653 Ok(())
9654 }
9655
9656 fn set_collaborators_from_proto(
9657 &mut self,
9658 messages: Vec<proto::Collaborator>,
9659 cx: &mut ModelContext<Self>,
9660 ) -> Result<()> {
9661 let mut collaborators = HashMap::default();
9662 for message in messages {
9663 let collaborator = Collaborator::from_proto(message)?;
9664 collaborators.insert(collaborator.peer_id, collaborator);
9665 }
9666 for old_peer_id in self.collaborators.keys() {
9667 if !collaborators.contains_key(old_peer_id) {
9668 cx.emit(Event::CollaboratorLeft(*old_peer_id));
9669 }
9670 }
9671 self.collaborators = collaborators;
9672 Ok(())
9673 }
9674
9675 fn deserialize_symbol(serialized_symbol: proto::Symbol) -> Result<CoreSymbol> {
9676 let source_worktree_id = WorktreeId::from_proto(serialized_symbol.source_worktree_id);
9677 let worktree_id = WorktreeId::from_proto(serialized_symbol.worktree_id);
9678 let kind = unsafe { mem::transmute(serialized_symbol.kind) };
9679 let path = ProjectPath {
9680 worktree_id,
9681 path: PathBuf::from(serialized_symbol.path).into(),
9682 };
9683
9684 let start = serialized_symbol
9685 .start
9686 .ok_or_else(|| anyhow!("invalid start"))?;
9687 let end = serialized_symbol
9688 .end
9689 .ok_or_else(|| anyhow!("invalid end"))?;
9690 Ok(CoreSymbol {
9691 language_server_name: LanguageServerName(serialized_symbol.language_server_name.into()),
9692 source_worktree_id,
9693 path,
9694 name: serialized_symbol.name,
9695 range: Unclipped(PointUtf16::new(start.row, start.column))
9696 ..Unclipped(PointUtf16::new(end.row, end.column)),
9697 kind,
9698 signature: serialized_symbol
9699 .signature
9700 .try_into()
9701 .map_err(|_| anyhow!("invalid signature"))?,
9702 })
9703 }
9704
9705 fn serialize_completion(completion: &CoreCompletion) -> proto::Completion {
9706 proto::Completion {
9707 old_start: Some(serialize_anchor(&completion.old_range.start)),
9708 old_end: Some(serialize_anchor(&completion.old_range.end)),
9709 new_text: completion.new_text.clone(),
9710 server_id: completion.server_id.0 as u64,
9711 lsp_completion: serde_json::to_vec(&completion.lsp_completion).unwrap(),
9712 }
9713 }
9714
9715 fn deserialize_completion(completion: proto::Completion) -> Result<CoreCompletion> {
9716 let old_start = completion
9717 .old_start
9718 .and_then(deserialize_anchor)
9719 .ok_or_else(|| anyhow!("invalid old start"))?;
9720 let old_end = completion
9721 .old_end
9722 .and_then(deserialize_anchor)
9723 .ok_or_else(|| anyhow!("invalid old end"))?;
9724 let lsp_completion = serde_json::from_slice(&completion.lsp_completion)?;
9725
9726 Ok(CoreCompletion {
9727 old_range: old_start..old_end,
9728 new_text: completion.new_text,
9729 server_id: LanguageServerId(completion.server_id as usize),
9730 lsp_completion,
9731 })
9732 }
9733
9734 fn serialize_code_action(action: &CodeAction) -> proto::CodeAction {
9735 proto::CodeAction {
9736 server_id: action.server_id.0 as u64,
9737 start: Some(serialize_anchor(&action.range.start)),
9738 end: Some(serialize_anchor(&action.range.end)),
9739 lsp_action: serde_json::to_vec(&action.lsp_action).unwrap(),
9740 }
9741 }
9742
9743 fn deserialize_code_action(action: proto::CodeAction) -> Result<CodeAction> {
9744 let start = action
9745 .start
9746 .and_then(deserialize_anchor)
9747 .ok_or_else(|| anyhow!("invalid start"))?;
9748 let end = action
9749 .end
9750 .and_then(deserialize_anchor)
9751 .ok_or_else(|| anyhow!("invalid end"))?;
9752 let lsp_action = serde_json::from_slice(&action.lsp_action)?;
9753 Ok(CodeAction {
9754 server_id: LanguageServerId(action.server_id as usize),
9755 range: start..end,
9756 lsp_action,
9757 })
9758 }
9759
9760 async fn handle_buffer_saved(
9761 this: Model<Self>,
9762 envelope: TypedEnvelope<proto::BufferSaved>,
9763 _: Arc<Client>,
9764 mut cx: AsyncAppContext,
9765 ) -> Result<()> {
9766 let version = deserialize_version(&envelope.payload.version);
9767 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
9768 let mtime = envelope.payload.mtime.map(|time| time.into());
9769
9770 this.update(&mut cx, |this, cx| {
9771 let buffer = this
9772 .opened_buffers
9773 .get(&buffer_id)
9774 .and_then(|buffer| buffer.upgrade())
9775 .or_else(|| this.incomplete_remote_buffers.get(&buffer_id).cloned());
9776 if let Some(buffer) = buffer {
9777 buffer.update(cx, |buffer, cx| {
9778 buffer.did_save(version, mtime, cx);
9779 });
9780 }
9781 Ok(())
9782 })?
9783 }
9784
9785 async fn handle_buffer_reloaded(
9786 this: Model<Self>,
9787 envelope: TypedEnvelope<proto::BufferReloaded>,
9788 _: Arc<Client>,
9789 mut cx: AsyncAppContext,
9790 ) -> Result<()> {
9791 let payload = envelope.payload;
9792 let version = deserialize_version(&payload.version);
9793 let line_ending = deserialize_line_ending(
9794 proto::LineEnding::from_i32(payload.line_ending)
9795 .ok_or_else(|| anyhow!("missing line ending"))?,
9796 );
9797 let mtime = payload.mtime.map(|time| time.into());
9798 let buffer_id = BufferId::new(payload.buffer_id)?;
9799 this.update(&mut cx, |this, cx| {
9800 let buffer = this
9801 .opened_buffers
9802 .get(&buffer_id)
9803 .and_then(|buffer| buffer.upgrade())
9804 .or_else(|| this.incomplete_remote_buffers.get(&buffer_id).cloned());
9805 if let Some(buffer) = buffer {
9806 buffer.update(cx, |buffer, cx| {
9807 buffer.did_reload(version, line_ending, mtime, cx);
9808 });
9809 }
9810 Ok(())
9811 })?
9812 }
9813
9814 #[allow(clippy::type_complexity)]
9815 fn edits_from_lsp(
9816 &mut self,
9817 buffer: &Model<Buffer>,
9818 lsp_edits: impl 'static + Send + IntoIterator<Item = lsp::TextEdit>,
9819 server_id: LanguageServerId,
9820 version: Option<i32>,
9821 cx: &mut ModelContext<Self>,
9822 ) -> Task<Result<Vec<(Range<Anchor>, String)>>> {
9823 let snapshot = self.buffer_snapshot_for_lsp_version(buffer, server_id, version, cx);
9824 cx.background_executor().spawn(async move {
9825 let snapshot = snapshot?;
9826 let mut lsp_edits = lsp_edits
9827 .into_iter()
9828 .map(|edit| (range_from_lsp(edit.range), edit.new_text))
9829 .collect::<Vec<_>>();
9830 lsp_edits.sort_by_key(|(range, _)| range.start);
9831
9832 let mut lsp_edits = lsp_edits.into_iter().peekable();
9833 let mut edits = Vec::new();
9834 while let Some((range, mut new_text)) = lsp_edits.next() {
9835 // Clip invalid ranges provided by the language server.
9836 let mut range = snapshot.clip_point_utf16(range.start, Bias::Left)
9837 ..snapshot.clip_point_utf16(range.end, Bias::Left);
9838
9839 // Combine any LSP edits that are adjacent.
9840 //
9841 // Also, combine LSP edits that are separated from each other by only
9842 // a newline. This is important because for some code actions,
9843 // Rust-analyzer rewrites the entire buffer via a series of edits that
9844 // are separated by unchanged newline characters.
9845 //
9846 // In order for the diffing logic below to work properly, any edits that
9847 // cancel each other out must be combined into one.
9848 while let Some((next_range, next_text)) = lsp_edits.peek() {
9849 if next_range.start.0 > range.end {
9850 if next_range.start.0.row > range.end.row + 1
9851 || next_range.start.0.column > 0
9852 || snapshot.clip_point_utf16(
9853 Unclipped(PointUtf16::new(range.end.row, u32::MAX)),
9854 Bias::Left,
9855 ) > range.end
9856 {
9857 break;
9858 }
9859 new_text.push('\n');
9860 }
9861 range.end = snapshot.clip_point_utf16(next_range.end, Bias::Left);
9862 new_text.push_str(next_text);
9863 lsp_edits.next();
9864 }
9865
9866 // For multiline edits, perform a diff of the old and new text so that
9867 // we can identify the changes more precisely, preserving the locations
9868 // of any anchors positioned in the unchanged regions.
9869 if range.end.row > range.start.row {
9870 let mut offset = range.start.to_offset(&snapshot);
9871 let old_text = snapshot.text_for_range(range).collect::<String>();
9872
9873 let diff = TextDiff::from_lines(old_text.as_str(), &new_text);
9874 let mut moved_since_edit = true;
9875 for change in diff.iter_all_changes() {
9876 let tag = change.tag();
9877 let value = change.value();
9878 match tag {
9879 ChangeTag::Equal => {
9880 offset += value.len();
9881 moved_since_edit = true;
9882 }
9883 ChangeTag::Delete => {
9884 let start = snapshot.anchor_after(offset);
9885 let end = snapshot.anchor_before(offset + value.len());
9886 if moved_since_edit {
9887 edits.push((start..end, String::new()));
9888 } else {
9889 edits.last_mut().unwrap().0.end = end;
9890 }
9891 offset += value.len();
9892 moved_since_edit = false;
9893 }
9894 ChangeTag::Insert => {
9895 if moved_since_edit {
9896 let anchor = snapshot.anchor_after(offset);
9897 edits.push((anchor..anchor, value.to_string()));
9898 } else {
9899 edits.last_mut().unwrap().1.push_str(value);
9900 }
9901 moved_since_edit = false;
9902 }
9903 }
9904 }
9905 } else if range.end == range.start {
9906 let anchor = snapshot.anchor_after(range.start);
9907 edits.push((anchor..anchor, new_text));
9908 } else {
9909 let edit_start = snapshot.anchor_after(range.start);
9910 let edit_end = snapshot.anchor_before(range.end);
9911 edits.push((edit_start..edit_end, new_text));
9912 }
9913 }
9914
9915 Ok(edits)
9916 })
9917 }
9918
9919 fn buffer_snapshot_for_lsp_version(
9920 &mut self,
9921 buffer: &Model<Buffer>,
9922 server_id: LanguageServerId,
9923 version: Option<i32>,
9924 cx: &AppContext,
9925 ) -> Result<TextBufferSnapshot> {
9926 const OLD_VERSIONS_TO_RETAIN: i32 = 10;
9927
9928 if let Some(version) = version {
9929 let buffer_id = buffer.read(cx).remote_id();
9930 let snapshots = self
9931 .buffer_snapshots
9932 .get_mut(&buffer_id)
9933 .and_then(|m| m.get_mut(&server_id))
9934 .ok_or_else(|| {
9935 anyhow!("no snapshots found for buffer {buffer_id} and server {server_id}")
9936 })?;
9937
9938 let found_snapshot = snapshots
9939 .binary_search_by_key(&version, |e| e.version)
9940 .map(|ix| snapshots[ix].snapshot.clone())
9941 .map_err(|_| {
9942 anyhow!("snapshot not found for buffer {buffer_id} server {server_id} at version {version}")
9943 })?;
9944
9945 snapshots.retain(|snapshot| snapshot.version + OLD_VERSIONS_TO_RETAIN >= version);
9946 Ok(found_snapshot)
9947 } else {
9948 Ok((buffer.read(cx)).text_snapshot())
9949 }
9950 }
9951
9952 pub fn language_servers(
9953 &self,
9954 ) -> impl '_ + Iterator<Item = (LanguageServerId, LanguageServerName, WorktreeId)> {
9955 self.language_server_ids
9956 .iter()
9957 .map(|((worktree_id, server_name), server_id)| {
9958 (*server_id, server_name.clone(), *worktree_id)
9959 })
9960 }
9961
9962 pub fn supplementary_language_servers(
9963 &self,
9964 ) -> impl '_
9965 + Iterator<
9966 Item = (
9967 &LanguageServerId,
9968 &(LanguageServerName, Arc<LanguageServer>),
9969 ),
9970 > {
9971 self.supplementary_language_servers.iter()
9972 }
9973
9974 pub fn language_server_adapter_for_id(
9975 &self,
9976 id: LanguageServerId,
9977 ) -> Option<Arc<CachedLspAdapter>> {
9978 if let Some(LanguageServerState::Running { adapter, .. }) = self.language_servers.get(&id) {
9979 Some(adapter.clone())
9980 } else {
9981 None
9982 }
9983 }
9984
9985 pub fn language_server_for_id(&self, id: LanguageServerId) -> Option<Arc<LanguageServer>> {
9986 if let Some(LanguageServerState::Running { server, .. }) = self.language_servers.get(&id) {
9987 Some(server.clone())
9988 } else if let Some((_, server)) = self.supplementary_language_servers.get(&id) {
9989 Some(Arc::clone(server))
9990 } else {
9991 None
9992 }
9993 }
9994
9995 pub fn language_servers_for_buffer(
9996 &self,
9997 buffer: &Buffer,
9998 cx: &AppContext,
9999 ) -> impl Iterator<Item = (&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
10000 self.language_server_ids_for_buffer(buffer, cx)
10001 .into_iter()
10002 .filter_map(|server_id| match self.language_servers.get(&server_id)? {
10003 LanguageServerState::Running {
10004 adapter, server, ..
10005 } => Some((adapter, server)),
10006 _ => None,
10007 })
10008 }
10009
10010 fn primary_language_server_for_buffer(
10011 &self,
10012 buffer: &Buffer,
10013 cx: &AppContext,
10014 ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
10015 self.language_servers_for_buffer(buffer, cx)
10016 .find(|s| s.0.is_primary)
10017 }
10018
10019 pub fn language_server_for_buffer(
10020 &self,
10021 buffer: &Buffer,
10022 server_id: LanguageServerId,
10023 cx: &AppContext,
10024 ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
10025 self.language_servers_for_buffer(buffer, cx)
10026 .find(|(_, s)| s.server_id() == server_id)
10027 }
10028
10029 fn language_server_ids_for_buffer(
10030 &self,
10031 buffer: &Buffer,
10032 cx: &AppContext,
10033 ) -> Vec<LanguageServerId> {
10034 if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language()) {
10035 let worktree_id = file.worktree_id(cx);
10036 self.languages
10037 .lsp_adapters(&language)
10038 .iter()
10039 .flat_map(|adapter| {
10040 let key = (worktree_id, adapter.name.clone());
10041 self.language_server_ids.get(&key).copied()
10042 })
10043 .collect()
10044 } else {
10045 Vec::new()
10046 }
10047 }
10048}
10049
10050async fn populate_labels_for_symbols(
10051 symbols: Vec<CoreSymbol>,
10052 language_registry: &Arc<LanguageRegistry>,
10053 default_language: Option<Arc<Language>>,
10054 lsp_adapter: Option<Arc<CachedLspAdapter>>,
10055 output: &mut Vec<Symbol>,
10056) {
10057 let mut symbols_by_language = HashMap::<Option<Arc<Language>>, Vec<CoreSymbol>>::default();
10058
10059 let mut unknown_path = None;
10060 for symbol in symbols {
10061 let language = language_registry
10062 .language_for_file_path(&symbol.path.path)
10063 .await
10064 .ok()
10065 .or_else(|| {
10066 unknown_path.get_or_insert(symbol.path.path.clone());
10067 default_language.clone()
10068 });
10069 symbols_by_language
10070 .entry(language)
10071 .or_default()
10072 .push(symbol);
10073 }
10074
10075 if let Some(unknown_path) = unknown_path {
10076 log::info!(
10077 "no language found for symbol path {}",
10078 unknown_path.display()
10079 );
10080 }
10081
10082 let mut label_params = Vec::new();
10083 for (language, mut symbols) in symbols_by_language {
10084 label_params.clear();
10085 label_params.extend(
10086 symbols
10087 .iter_mut()
10088 .map(|symbol| (mem::take(&mut symbol.name), symbol.kind)),
10089 );
10090
10091 let mut labels = Vec::new();
10092 if let Some(language) = language {
10093 let lsp_adapter = lsp_adapter
10094 .clone()
10095 .or_else(|| language_registry.lsp_adapters(&language).first().cloned());
10096 if let Some(lsp_adapter) = lsp_adapter {
10097 labels = lsp_adapter
10098 .labels_for_symbols(&label_params, &language)
10099 .await
10100 .log_err()
10101 .unwrap_or_default();
10102 }
10103 }
10104
10105 for ((symbol, (name, _)), label) in symbols
10106 .into_iter()
10107 .zip(label_params.drain(..))
10108 .zip(labels.into_iter().chain(iter::repeat(None)))
10109 {
10110 output.push(Symbol {
10111 language_server_name: symbol.language_server_name,
10112 source_worktree_id: symbol.source_worktree_id,
10113 path: symbol.path,
10114 label: label.unwrap_or_else(|| CodeLabel::plain(name.clone(), None)),
10115 name,
10116 kind: symbol.kind,
10117 range: symbol.range,
10118 signature: symbol.signature,
10119 });
10120 }
10121 }
10122}
10123
10124async fn populate_labels_for_completions(
10125 mut new_completions: Vec<CoreCompletion>,
10126 language_registry: &Arc<LanguageRegistry>,
10127 language: Option<Arc<Language>>,
10128 lsp_adapter: Option<Arc<CachedLspAdapter>>,
10129 completions: &mut Vec<Completion>,
10130) {
10131 let lsp_completions = new_completions
10132 .iter_mut()
10133 .map(|completion| mem::take(&mut completion.lsp_completion))
10134 .collect::<Vec<_>>();
10135
10136 let labels = if let Some((language, lsp_adapter)) = language.as_ref().zip(lsp_adapter) {
10137 lsp_adapter
10138 .labels_for_completions(&lsp_completions, language)
10139 .await
10140 .log_err()
10141 .unwrap_or_default()
10142 } else {
10143 Vec::new()
10144 };
10145
10146 for ((completion, lsp_completion), label) in new_completions
10147 .into_iter()
10148 .zip(lsp_completions)
10149 .zip(labels.into_iter().chain(iter::repeat(None)))
10150 {
10151 let documentation = if let Some(docs) = &lsp_completion.documentation {
10152 Some(prepare_completion_documentation(docs, &language_registry, language.clone()).await)
10153 } else {
10154 None
10155 };
10156
10157 completions.push(Completion {
10158 old_range: completion.old_range,
10159 new_text: completion.new_text,
10160 label: label.unwrap_or_else(|| {
10161 CodeLabel::plain(
10162 lsp_completion.label.clone(),
10163 lsp_completion.filter_text.as_deref(),
10164 )
10165 }),
10166 server_id: completion.server_id,
10167 documentation,
10168 lsp_completion,
10169 })
10170 }
10171}
10172
10173fn deserialize_code_actions(code_actions: &HashMap<String, bool>) -> Vec<lsp::CodeActionKind> {
10174 code_actions
10175 .iter()
10176 .flat_map(|(kind, enabled)| {
10177 if *enabled {
10178 Some(kind.clone().into())
10179 } else {
10180 None
10181 }
10182 })
10183 .collect()
10184}
10185
10186#[allow(clippy::too_many_arguments)]
10187async fn search_snapshots(
10188 snapshots: &Vec<LocalSnapshot>,
10189 worker_start_ix: usize,
10190 worker_end_ix: usize,
10191 query: &SearchQuery,
10192 results_tx: &Sender<SearchMatchCandidate>,
10193 opened_buffers: &HashMap<Arc<Path>, (Model<Buffer>, BufferSnapshot)>,
10194 include_root: bool,
10195 fs: &Arc<dyn Fs>,
10196) {
10197 let mut snapshot_start_ix = 0;
10198 let mut abs_path = PathBuf::new();
10199
10200 for snapshot in snapshots {
10201 let snapshot_end_ix = snapshot_start_ix
10202 + if query.include_ignored() {
10203 snapshot.file_count()
10204 } else {
10205 snapshot.visible_file_count()
10206 };
10207 if worker_end_ix <= snapshot_start_ix {
10208 break;
10209 } else if worker_start_ix > snapshot_end_ix {
10210 snapshot_start_ix = snapshot_end_ix;
10211 continue;
10212 } else {
10213 let start_in_snapshot = worker_start_ix.saturating_sub(snapshot_start_ix);
10214 let end_in_snapshot = cmp::min(worker_end_ix, snapshot_end_ix) - snapshot_start_ix;
10215
10216 for entry in snapshot
10217 .files(false, start_in_snapshot)
10218 .take(end_in_snapshot - start_in_snapshot)
10219 {
10220 if results_tx.is_closed() {
10221 break;
10222 }
10223 if opened_buffers.contains_key(&entry.path) {
10224 continue;
10225 }
10226
10227 let matched_path = if include_root {
10228 let mut full_path = PathBuf::from(snapshot.root_name());
10229 full_path.push(&entry.path);
10230 query.file_matches(Some(&full_path))
10231 } else {
10232 query.file_matches(Some(&entry.path))
10233 };
10234
10235 let matches = if matched_path {
10236 abs_path.clear();
10237 abs_path.push(&snapshot.abs_path());
10238 abs_path.push(&entry.path);
10239 if let Some(file) = fs.open_sync(&abs_path).await.log_err() {
10240 query.detect(file).unwrap_or(false)
10241 } else {
10242 false
10243 }
10244 } else {
10245 false
10246 };
10247
10248 if matches {
10249 let project_path = SearchMatchCandidate::Path {
10250 worktree_id: snapshot.id(),
10251 path: entry.path.clone(),
10252 is_ignored: entry.is_ignored,
10253 };
10254 if results_tx.send(project_path).await.is_err() {
10255 return;
10256 }
10257 }
10258 }
10259
10260 snapshot_start_ix = snapshot_end_ix;
10261 }
10262 }
10263}
10264
10265async fn search_ignored_entry(
10266 snapshot: &LocalSnapshot,
10267 ignored_entry: &Entry,
10268 fs: &Arc<dyn Fs>,
10269 query: &SearchQuery,
10270 counter_tx: &Sender<SearchMatchCandidate>,
10271) {
10272 let mut ignored_paths_to_process =
10273 VecDeque::from([snapshot.abs_path().join(&ignored_entry.path)]);
10274
10275 while let Some(ignored_abs_path) = ignored_paths_to_process.pop_front() {
10276 let metadata = fs
10277 .metadata(&ignored_abs_path)
10278 .await
10279 .with_context(|| format!("fetching fs metadata for {ignored_abs_path:?}"))
10280 .log_err()
10281 .flatten();
10282
10283 if let Some(fs_metadata) = metadata {
10284 if fs_metadata.is_dir {
10285 let files = fs
10286 .read_dir(&ignored_abs_path)
10287 .await
10288 .with_context(|| format!("listing ignored path {ignored_abs_path:?}"))
10289 .log_err();
10290
10291 if let Some(mut subfiles) = files {
10292 while let Some(subfile) = subfiles.next().await {
10293 if let Some(subfile) = subfile.log_err() {
10294 ignored_paths_to_process.push_back(subfile);
10295 }
10296 }
10297 }
10298 } else if !fs_metadata.is_symlink {
10299 if !query.file_matches(Some(&ignored_abs_path))
10300 || snapshot.is_path_excluded(ignored_entry.path.to_path_buf())
10301 {
10302 continue;
10303 }
10304 let matches = if let Some(file) = fs
10305 .open_sync(&ignored_abs_path)
10306 .await
10307 .with_context(|| format!("Opening ignored path {ignored_abs_path:?}"))
10308 .log_err()
10309 {
10310 query.detect(file).unwrap_or(false)
10311 } else {
10312 false
10313 };
10314
10315 if matches {
10316 let project_path = SearchMatchCandidate::Path {
10317 worktree_id: snapshot.id(),
10318 path: Arc::from(
10319 ignored_abs_path
10320 .strip_prefix(snapshot.abs_path())
10321 .expect("scanning worktree-related files"),
10322 ),
10323 is_ignored: true,
10324 };
10325 if counter_tx.send(project_path).await.is_err() {
10326 return;
10327 }
10328 }
10329 }
10330 }
10331 }
10332}
10333
10334fn subscribe_for_copilot_events(
10335 copilot: &Model<Copilot>,
10336 cx: &mut ModelContext<'_, Project>,
10337) -> gpui::Subscription {
10338 cx.subscribe(
10339 copilot,
10340 |project, copilot, copilot_event, cx| match copilot_event {
10341 copilot::Event::CopilotLanguageServerStarted => {
10342 match copilot.read(cx).language_server() {
10343 Some((name, copilot_server)) => {
10344 // Another event wants to re-add the server that was already added and subscribed to, avoid doing it again.
10345 if !copilot_server.has_notification_handler::<copilot::request::LogMessage>() {
10346 let new_server_id = copilot_server.server_id();
10347 let weak_project = cx.weak_model();
10348 let copilot_log_subscription = copilot_server
10349 .on_notification::<copilot::request::LogMessage, _>(
10350 move |params, mut cx| {
10351 weak_project.update(&mut cx, |_, cx| {
10352 cx.emit(Event::LanguageServerLog(
10353 new_server_id,
10354 params.message,
10355 ));
10356 }).ok();
10357 },
10358 );
10359 project.supplementary_language_servers.insert(new_server_id, (name.clone(), Arc::clone(copilot_server)));
10360 project.copilot_log_subscription = Some(copilot_log_subscription);
10361 cx.emit(Event::LanguageServerAdded(new_server_id));
10362 }
10363 }
10364 None => debug_panic!("Received Copilot language server started event, but no language server is running"),
10365 }
10366 }
10367 },
10368 )
10369}
10370
10371fn glob_literal_prefix(glob: &str) -> &str {
10372 let mut literal_end = 0;
10373 for (i, part) in glob.split(path::MAIN_SEPARATOR).enumerate() {
10374 if part.contains(&['*', '?', '{', '}']) {
10375 break;
10376 } else {
10377 if i > 0 {
10378 // Account for separator prior to this part
10379 literal_end += path::MAIN_SEPARATOR.len_utf8();
10380 }
10381 literal_end += part.len();
10382 }
10383 }
10384 &glob[..literal_end]
10385}
10386
10387impl WorktreeHandle {
10388 pub fn upgrade(&self) -> Option<Model<Worktree>> {
10389 match self {
10390 WorktreeHandle::Strong(handle) => Some(handle.clone()),
10391 WorktreeHandle::Weak(handle) => handle.upgrade(),
10392 }
10393 }
10394
10395 pub fn handle_id(&self) -> usize {
10396 match self {
10397 WorktreeHandle::Strong(handle) => handle.entity_id().as_u64() as usize,
10398 WorktreeHandle::Weak(handle) => handle.entity_id().as_u64() as usize,
10399 }
10400 }
10401}
10402
10403impl OpenBuffer {
10404 pub fn upgrade(&self) -> Option<Model<Buffer>> {
10405 match self {
10406 OpenBuffer::Strong(handle) => Some(handle.clone()),
10407 OpenBuffer::Weak(handle) => handle.upgrade(),
10408 OpenBuffer::Operations(_) => None,
10409 }
10410 }
10411}
10412
10413pub struct PathMatchCandidateSet {
10414 pub snapshot: Snapshot,
10415 pub include_ignored: bool,
10416 pub include_root_name: bool,
10417}
10418
10419impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
10420 type Candidates = PathMatchCandidateSetIter<'a>;
10421
10422 fn id(&self) -> usize {
10423 self.snapshot.id().to_usize()
10424 }
10425
10426 fn len(&self) -> usize {
10427 if self.include_ignored {
10428 self.snapshot.file_count()
10429 } else {
10430 self.snapshot.visible_file_count()
10431 }
10432 }
10433
10434 fn prefix(&self) -> Arc<str> {
10435 if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
10436 self.snapshot.root_name().into()
10437 } else if self.include_root_name {
10438 format!("{}/", self.snapshot.root_name()).into()
10439 } else {
10440 "".into()
10441 }
10442 }
10443
10444 fn candidates(&'a self, start: usize) -> Self::Candidates {
10445 PathMatchCandidateSetIter {
10446 traversal: self.snapshot.files(self.include_ignored, start),
10447 }
10448 }
10449}
10450
10451pub struct PathMatchCandidateSetIter<'a> {
10452 traversal: Traversal<'a>,
10453}
10454
10455impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
10456 type Item = fuzzy::PathMatchCandidate<'a>;
10457
10458 fn next(&mut self) -> Option<Self::Item> {
10459 self.traversal.next().map(|entry| {
10460 if let EntryKind::File(char_bag) = entry.kind {
10461 fuzzy::PathMatchCandidate {
10462 path: &entry.path,
10463 char_bag,
10464 }
10465 } else {
10466 unreachable!()
10467 }
10468 })
10469 }
10470}
10471
10472impl EventEmitter<Event> for Project {}
10473
10474impl<'a> Into<SettingsLocation<'a>> for &'a ProjectPath {
10475 fn into(self) -> SettingsLocation<'a> {
10476 SettingsLocation {
10477 worktree_id: self.worktree_id.to_usize(),
10478 path: self.path.as_ref(),
10479 }
10480 }
10481}
10482
10483impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
10484 fn from((worktree_id, path): (WorktreeId, P)) -> Self {
10485 Self {
10486 worktree_id,
10487 path: path.as_ref().into(),
10488 }
10489 }
10490}
10491
10492struct ProjectLspAdapterDelegate {
10493 project: WeakModel<Project>,
10494 worktree: worktree::Snapshot,
10495 fs: Arc<dyn Fs>,
10496 http_client: Arc<dyn HttpClient>,
10497 language_registry: Arc<LanguageRegistry>,
10498 shell_env: Mutex<Option<HashMap<String, String>>>,
10499}
10500
10501impl ProjectLspAdapterDelegate {
10502 fn new(project: &Project, worktree: &Model<Worktree>, cx: &ModelContext<Project>) -> Arc<Self> {
10503 Arc::new(Self {
10504 project: cx.weak_model(),
10505 worktree: worktree.read(cx).snapshot(),
10506 fs: project.fs.clone(),
10507 http_client: project.client.http_client(),
10508 language_registry: project.languages.clone(),
10509 shell_env: Default::default(),
10510 })
10511 }
10512
10513 async fn load_shell_env(&self) {
10514 let worktree_abs_path = self.worktree.abs_path();
10515 let shell_env = load_shell_environment(&worktree_abs_path)
10516 .await
10517 .with_context(|| {
10518 format!("failed to determine load login shell environment in {worktree_abs_path:?}")
10519 })
10520 .log_err()
10521 .unwrap_or_default();
10522 *self.shell_env.lock() = Some(shell_env);
10523 }
10524}
10525
10526#[async_trait]
10527impl LspAdapterDelegate for ProjectLspAdapterDelegate {
10528 fn show_notification(&self, message: &str, cx: &mut AppContext) {
10529 self.project
10530 .update(cx, |_, cx| cx.emit(Event::Notification(message.to_owned())))
10531 .ok();
10532 }
10533
10534 fn http_client(&self) -> Arc<dyn HttpClient> {
10535 self.http_client.clone()
10536 }
10537
10538 fn worktree_id(&self) -> u64 {
10539 self.worktree.id().to_proto()
10540 }
10541
10542 fn worktree_root_path(&self) -> &Path {
10543 self.worktree.abs_path().as_ref()
10544 }
10545
10546 async fn shell_env(&self) -> HashMap<String, String> {
10547 self.load_shell_env().await;
10548 self.shell_env.lock().as_ref().cloned().unwrap_or_default()
10549 }
10550
10551 #[cfg(not(target_os = "windows"))]
10552 async fn which(&self, command: &OsStr) -> Option<PathBuf> {
10553 let worktree_abs_path = self.worktree.abs_path();
10554 self.load_shell_env().await;
10555 let shell_path = self
10556 .shell_env
10557 .lock()
10558 .as_ref()
10559 .and_then(|shell_env| shell_env.get("PATH").cloned());
10560 which::which_in(command, shell_path.as_ref(), &worktree_abs_path).ok()
10561 }
10562
10563 #[cfg(target_os = "windows")]
10564 async fn which(&self, command: &OsStr) -> Option<PathBuf> {
10565 // todo(windows) Getting the shell env variables in a current directory on Windows is more complicated than other platforms
10566 // there isn't a 'default shell' necessarily. The closest would be the default profile on the windows terminal
10567 // SEE: https://learn.microsoft.com/en-us/windows/terminal/customize-settings/startup
10568 which::which(command).ok()
10569 }
10570
10571 fn update_status(
10572 &self,
10573 server_name: LanguageServerName,
10574 status: language::LanguageServerBinaryStatus,
10575 ) {
10576 self.language_registry
10577 .update_lsp_status(server_name, status);
10578 }
10579
10580 async fn read_text_file(&self, path: PathBuf) -> Result<String> {
10581 if self.worktree.entry_for_path(&path).is_none() {
10582 return Err(anyhow!("no such path {path:?}"));
10583 }
10584 let path = self.worktree.absolutize(path.as_ref())?;
10585 let content = self.fs.load(&path).await?;
10586 Ok(content)
10587 }
10588}
10589
10590fn serialize_symbol(symbol: &Symbol) -> proto::Symbol {
10591 proto::Symbol {
10592 language_server_name: symbol.language_server_name.0.to_string(),
10593 source_worktree_id: symbol.source_worktree_id.to_proto(),
10594 worktree_id: symbol.path.worktree_id.to_proto(),
10595 path: symbol.path.path.to_string_lossy().to_string(),
10596 name: symbol.name.clone(),
10597 kind: unsafe { mem::transmute(symbol.kind) },
10598 start: Some(proto::PointUtf16 {
10599 row: symbol.range.start.0.row,
10600 column: symbol.range.start.0.column,
10601 }),
10602 end: Some(proto::PointUtf16 {
10603 row: symbol.range.end.0.row,
10604 column: symbol.range.end.0.column,
10605 }),
10606 signature: symbol.signature.to_vec(),
10607 }
10608}
10609
10610fn relativize_path(base: &Path, path: &Path) -> PathBuf {
10611 let mut path_components = path.components();
10612 let mut base_components = base.components();
10613 let mut components: Vec<Component> = Vec::new();
10614 loop {
10615 match (path_components.next(), base_components.next()) {
10616 (None, None) => break,
10617 (Some(a), None) => {
10618 components.push(a);
10619 components.extend(path_components.by_ref());
10620 break;
10621 }
10622 (None, _) => components.push(Component::ParentDir),
10623 (Some(a), Some(b)) if components.is_empty() && a == b => (),
10624 (Some(a), Some(Component::CurDir)) => components.push(a),
10625 (Some(a), Some(_)) => {
10626 components.push(Component::ParentDir);
10627 for _ in base_components {
10628 components.push(Component::ParentDir);
10629 }
10630 components.push(a);
10631 components.extend(path_components.by_ref());
10632 break;
10633 }
10634 }
10635 }
10636 components.iter().map(|c| c.as_os_str()).collect()
10637}
10638
10639fn resolve_path(base: &Path, path: &Path) -> PathBuf {
10640 let mut result = base.to_path_buf();
10641 for component in path.components() {
10642 match component {
10643 Component::ParentDir => {
10644 result.pop();
10645 }
10646 Component::CurDir => (),
10647 _ => result.push(component),
10648 }
10649 }
10650 result
10651}
10652
10653impl Item for Buffer {
10654 fn try_open(
10655 project: &Model<Project>,
10656 path: &ProjectPath,
10657 cx: &mut AppContext,
10658 ) -> Option<Task<Result<Model<Self>>>> {
10659 Some(project.update(cx, |project, cx| project.open_buffer(path.clone(), cx)))
10660 }
10661
10662 fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
10663 File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
10664 }
10665
10666 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
10667 File::from_dyn(self.file()).map(|file| ProjectPath {
10668 worktree_id: file.worktree_id(cx),
10669 path: file.path().clone(),
10670 })
10671 }
10672}
10673
10674impl Completion {
10675 /// A key that can be used to sort completions when displaying
10676 /// them to the user.
10677 pub fn sort_key(&self) -> (usize, &str) {
10678 let kind_key = match self.lsp_completion.kind {
10679 Some(lsp::CompletionItemKind::KEYWORD) => 0,
10680 Some(lsp::CompletionItemKind::VARIABLE) => 1,
10681 _ => 2,
10682 };
10683 (kind_key, &self.label.text[self.label.filter_range.clone()])
10684 }
10685
10686 /// Whether this completion is a snippet.
10687 pub fn is_snippet(&self) -> bool {
10688 self.lsp_completion.insert_text_format == Some(lsp::InsertTextFormat::SNIPPET)
10689 }
10690}
10691
10692async fn wait_for_loading_buffer(
10693 mut receiver: postage::watch::Receiver<Option<Result<Model<Buffer>, Arc<anyhow::Error>>>>,
10694) -> Result<Model<Buffer>, Arc<anyhow::Error>> {
10695 loop {
10696 if let Some(result) = receiver.borrow().as_ref() {
10697 match result {
10698 Ok(buffer) => return Ok(buffer.to_owned()),
10699 Err(e) => return Err(e.to_owned()),
10700 }
10701 }
10702 receiver.next().await;
10703 }
10704}
10705
10706fn include_text(server: &lsp::LanguageServer) -> bool {
10707 server
10708 .capabilities()
10709 .text_document_sync
10710 .as_ref()
10711 .and_then(|sync| match sync {
10712 lsp::TextDocumentSyncCapability::Kind(_) => None,
10713 lsp::TextDocumentSyncCapability::Options(options) => options.save.as_ref(),
10714 })
10715 .and_then(|save_options| match save_options {
10716 lsp::TextDocumentSyncSaveOptions::Supported(_) => None,
10717 lsp::TextDocumentSyncSaveOptions::SaveOptions(options) => options.include_text,
10718 })
10719 .unwrap_or(false)
10720}
10721
10722async fn load_shell_environment(dir: &Path) -> Result<HashMap<String, String>> {
10723 let marker = "ZED_SHELL_START";
10724 let shell = env::var("SHELL").context(
10725 "SHELL environment variable is not assigned so we can't source login environment variables",
10726 )?;
10727
10728 // What we're doing here is to spawn a shell and then `cd` into
10729 // the project directory to get the env in there as if the user
10730 // `cd`'d into it. We do that because tools like direnv, asdf, ...
10731 // hook into `cd` and only set up the env after that.
10732 //
10733 // In certain shells we need to execute additional_command in order to
10734 // trigger the behavior of direnv, etc.
10735 //
10736 //
10737 // The `exit 0` is the result of hours of debugging, trying to find out
10738 // why running this command here, without `exit 0`, would mess
10739 // up signal process for our process so that `ctrl-c` doesn't work
10740 // anymore.
10741 //
10742 // We still don't know why `$SHELL -l -i -c '/usr/bin/env -0'` would
10743 // do that, but it does, and `exit 0` helps.
10744 let additional_command = PathBuf::from(&shell)
10745 .file_name()
10746 .and_then(|f| f.to_str())
10747 .and_then(|shell| match shell {
10748 "fish" => Some("emit fish_prompt;"),
10749 _ => None,
10750 });
10751
10752 let command = format!(
10753 "cd '{}';{} printf '%s' {marker}; /usr/bin/env; exit 0;",
10754 dir.display(),
10755 additional_command.unwrap_or("")
10756 );
10757
10758 let output = smol::process::Command::new(&shell)
10759 .args(["-i", "-c", &command])
10760 .output()
10761 .await
10762 .context("failed to spawn login shell to source login environment variables")?;
10763
10764 anyhow::ensure!(
10765 output.status.success(),
10766 "login shell exited with error {:?}",
10767 output.status
10768 );
10769
10770 let stdout = String::from_utf8_lossy(&output.stdout);
10771 let env_output_start = stdout.find(marker).ok_or_else(|| {
10772 anyhow!(
10773 "failed to parse output of `env` command in login shell: {}",
10774 stdout
10775 )
10776 })?;
10777
10778 let mut parsed_env = HashMap::default();
10779 let env_output = &stdout[env_output_start + marker.len()..];
10780
10781 parse_env_output(env_output, |key, value| {
10782 parsed_env.insert(key, value);
10783 });
10784
10785 Ok(parsed_env)
10786}
10787
10788fn serialize_blame_buffer_response(blame: git::blame::Blame) -> proto::BlameBufferResponse {
10789 let entries = blame
10790 .entries
10791 .into_iter()
10792 .map(|entry| proto::BlameEntry {
10793 sha: entry.sha.as_bytes().into(),
10794 start_line: entry.range.start,
10795 end_line: entry.range.end,
10796 original_line_number: entry.original_line_number,
10797 author: entry.author.clone(),
10798 author_mail: entry.author_mail.clone(),
10799 author_time: entry.author_time,
10800 author_tz: entry.author_tz.clone(),
10801 committer: entry.committer.clone(),
10802 committer_mail: entry.committer_mail.clone(),
10803 committer_time: entry.committer_time,
10804 committer_tz: entry.committer_tz.clone(),
10805 summary: entry.summary.clone(),
10806 previous: entry.previous.clone(),
10807 filename: entry.filename.clone(),
10808 })
10809 .collect::<Vec<_>>();
10810
10811 let messages = blame
10812 .messages
10813 .into_iter()
10814 .map(|(oid, message)| proto::CommitMessage {
10815 oid: oid.as_bytes().into(),
10816 message,
10817 })
10818 .collect::<Vec<_>>();
10819
10820 let permalinks = blame
10821 .permalinks
10822 .into_iter()
10823 .map(|(oid, url)| proto::CommitPermalink {
10824 oid: oid.as_bytes().into(),
10825 permalink: url.to_string(),
10826 })
10827 .collect::<Vec<_>>();
10828
10829 proto::BlameBufferResponse {
10830 entries,
10831 messages,
10832 permalinks,
10833 remote_url: blame.remote_url,
10834 }
10835}
10836
10837fn deserialize_blame_buffer_response(response: proto::BlameBufferResponse) -> git::blame::Blame {
10838 let entries = response
10839 .entries
10840 .into_iter()
10841 .filter_map(|entry| {
10842 Some(git::blame::BlameEntry {
10843 sha: git::Oid::from_bytes(&entry.sha).ok()?,
10844 range: entry.start_line..entry.end_line,
10845 original_line_number: entry.original_line_number,
10846 committer: entry.committer,
10847 committer_time: entry.committer_time,
10848 committer_tz: entry.committer_tz,
10849 committer_mail: entry.committer_mail,
10850 author: entry.author,
10851 author_mail: entry.author_mail,
10852 author_time: entry.author_time,
10853 author_tz: entry.author_tz,
10854 summary: entry.summary,
10855 previous: entry.previous,
10856 filename: entry.filename,
10857 })
10858 })
10859 .collect::<Vec<_>>();
10860
10861 let messages = response
10862 .messages
10863 .into_iter()
10864 .filter_map(|message| Some((git::Oid::from_bytes(&message.oid).ok()?, message.message)))
10865 .collect::<HashMap<_, _>>();
10866
10867 let permalinks = response
10868 .permalinks
10869 .into_iter()
10870 .filter_map(|permalink| {
10871 Some((
10872 git::Oid::from_bytes(&permalink.oid).ok()?,
10873 Url::from_str(&permalink.permalink).ok()?,
10874 ))
10875 })
10876 .collect::<HashMap<_, _>>();
10877
10878 Blame {
10879 entries,
10880 permalinks,
10881 messages,
10882 remote_url: response.remote_url,
10883 }
10884}
10885
10886fn remove_empty_hover_blocks(mut hover: Hover) -> Option<Hover> {
10887 hover
10888 .contents
10889 .retain(|hover_block| !hover_block.text.trim().is_empty());
10890 if hover.contents.is_empty() {
10891 None
10892 } else {
10893 Some(hover)
10894 }
10895}
10896
10897#[derive(Debug)]
10898pub struct NoRepositoryError {}
10899
10900impl std::fmt::Display for NoRepositoryError {
10901 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
10902 write!(f, "no git repository for worktree found")
10903 }
10904}
10905
10906impl std::error::Error for NoRepositoryError {}