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