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