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