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