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