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