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