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