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