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