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