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