1pub mod debounced_delay;
2mod ignore;
3pub mod lsp_command;
4pub mod lsp_ext_command;
5mod prettier_support;
6pub mod project_settings;
7pub mod search;
8mod task_inventory;
9pub mod terminals;
10pub mod worktree;
11
12#[cfg(test)]
13mod project_tests;
14#[cfg(test)]
15mod worktree_tests;
16
17use anyhow::{anyhow, bail, Context as _, Result};
18use client::{proto, Client, Collaborator, TypedEnvelope, UserStore};
19use clock::ReplicaId;
20use collections::{hash_map, BTreeMap, HashMap, HashSet, VecDeque};
21use copilot::Copilot;
22use debounced_delay::DebouncedDelay;
23use futures::{
24 channel::mpsc::{self, UnboundedReceiver},
25 future::{try_join_all, Shared},
26 select,
27 stream::FuturesUnordered,
28 AsyncWriteExt, Future, FutureExt, StreamExt, TryFutureExt,
29};
30use globset::{Glob, GlobSet, GlobSetBuilder};
31use gpui::{
32 AnyModel, AppContext, AsyncAppContext, BackgroundExecutor, Context, Entity, EventEmitter,
33 Model, ModelContext, PromptLevel, Task, WeakModel,
34};
35use itertools::Itertools;
36use language::{
37 language_settings::{language_settings, FormatOnSave, Formatter, InlayHintKind},
38 markdown, point_to_lsp,
39 proto::{
40 deserialize_anchor, deserialize_fingerprint, deserialize_line_ending, deserialize_version,
41 serialize_anchor, serialize_version, split_operations,
42 },
43 range_from_lsp, range_to_lsp, Bias, Buffer, BufferSnapshot, CachedLspAdapter, Capability,
44 CodeAction, CodeLabel, Completion, Diagnostic, DiagnosticEntry, DiagnosticSet, Diff,
45 Documentation, Event as BufferEvent, File as _, Language, LanguageRegistry, LanguageServerName,
46 LocalFile, LspAdapterDelegate, OffsetRangeExt, Operation, Patch, PendingLanguageServer,
47 PointUtf16, TextBufferSnapshot, ToOffset, ToPointUtf16, Transaction, Unclipped,
48};
49use log::error;
50use lsp::{
51 DiagnosticSeverity, DiagnosticTag, DidChangeWatchedFilesRegistrationOptions,
52 DocumentHighlightKind, LanguageServer, LanguageServerBinary, LanguageServerId,
53 MessageActionItem, OneOf,
54};
55use lsp_command::*;
56use node_runtime::NodeRuntime;
57use parking_lot::{Mutex, RwLock};
58use postage::watch;
59use prettier_support::{DefaultPrettier, PrettierInstance};
60use project_settings::{LspSettings, ProjectSettings};
61use rand::prelude::*;
62
63use rpc::{ErrorCode, ErrorExt as _};
64use search::SearchQuery;
65use serde::Serialize;
66use settings::{Settings, SettingsStore};
67use sha2::{Digest, Sha256};
68use similar::{ChangeTag, TextDiff};
69use smol::channel::{Receiver, Sender};
70use smol::lock::Semaphore;
71use std::{
72 cmp::{self, Ordering},
73 convert::TryInto,
74 env,
75 ffi::OsString,
76 hash::Hash,
77 mem,
78 num::NonZeroU32,
79 ops::Range,
80 path::{self, Component, Path, PathBuf},
81 process::Stdio,
82 str,
83 sync::{
84 atomic::{AtomicUsize, Ordering::SeqCst},
85 Arc,
86 },
87 time::{Duration, Instant},
88};
89use terminals::Terminals;
90use text::{Anchor, BufferId};
91use util::{
92 debug_panic, defer, http::HttpClient, merge_json_value_into,
93 paths::LOCAL_SETTINGS_RELATIVE_PATH, post_inc, ResultExt, TryFutureExt as _,
94};
95
96pub use fs::*;
97#[cfg(any(test, feature = "test-support"))]
98pub use prettier::FORMAT_SUFFIX as TEST_PRETTIER_FORMAT_SUFFIX;
99pub use task_inventory::Inventory;
100pub use worktree::*;
101
102const MAX_SERVER_REINSTALL_ATTEMPT_COUNT: u64 = 4;
103const SERVER_REINSTALL_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
104const SERVER_LAUNCHING_BEFORE_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(5);
105
106pub trait Item {
107 fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId>;
108 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath>;
109}
110
111pub struct Project {
112 worktrees: Vec<WorktreeHandle>,
113 active_entry: Option<ProjectEntryId>,
114 buffer_ordered_messages_tx: mpsc::UnboundedSender<BufferOrderedMessage>,
115 languages: Arc<LanguageRegistry>,
116 supplementary_language_servers:
117 HashMap<LanguageServerId, (LanguageServerName, Arc<LanguageServer>)>,
118 language_servers: HashMap<LanguageServerId, LanguageServerState>,
119 language_server_ids: HashMap<(WorktreeId, LanguageServerName), LanguageServerId>,
120 language_server_statuses: BTreeMap<LanguageServerId, LanguageServerStatus>,
121 last_workspace_edits_by_language_server: HashMap<LanguageServerId, ProjectTransaction>,
122 client: Arc<client::Client>,
123 next_entry_id: Arc<AtomicUsize>,
124 join_project_response_message_id: u32,
125 next_diagnostic_group_id: usize,
126 user_store: Model<UserStore>,
127 fs: Arc<dyn Fs>,
128 client_state: ProjectClientState,
129 collaborators: HashMap<proto::PeerId, Collaborator>,
130 client_subscriptions: Vec<client::Subscription>,
131 _subscriptions: Vec<gpui::Subscription>,
132 next_buffer_id: BufferId,
133 opened_buffer: (watch::Sender<()>, watch::Receiver<()>),
134 shared_buffers: HashMap<proto::PeerId, HashSet<BufferId>>,
135 #[allow(clippy::type_complexity)]
136 loading_buffers_by_path: HashMap<
137 ProjectPath,
138 postage::watch::Receiver<Option<Result<Model<Buffer>, Arc<anyhow::Error>>>>,
139 >,
140 #[allow(clippy::type_complexity)]
141 loading_local_worktrees:
142 HashMap<Arc<Path>, Shared<Task<Result<Model<Worktree>, Arc<anyhow::Error>>>>>,
143 opened_buffers: HashMap<BufferId, OpenBuffer>,
144 local_buffer_ids_by_path: HashMap<ProjectPath, BufferId>,
145 local_buffer_ids_by_entry_id: HashMap<ProjectEntryId, BufferId>,
146 /// A mapping from a buffer ID to None means that we've started waiting for an ID but haven't finished loading it.
147 /// Used for re-issuing buffer requests when peers temporarily disconnect
148 incomplete_remote_buffers: HashMap<BufferId, Option<Model<Buffer>>>,
149 buffer_snapshots: HashMap<BufferId, HashMap<LanguageServerId, Vec<LspBufferSnapshot>>>, // buffer_id -> server_id -> vec of snapshots
150 buffers_being_formatted: HashSet<BufferId>,
151 buffers_needing_diff: HashSet<WeakModel<Buffer>>,
152 git_diff_debouncer: DebouncedDelay,
153 nonce: u128,
154 _maintain_buffer_languages: Task<()>,
155 _maintain_workspace_config: Task<Result<()>>,
156 terminals: Terminals,
157 copilot_lsp_subscription: Option<gpui::Subscription>,
158 copilot_log_subscription: Option<lsp::Subscription>,
159 current_lsp_settings: HashMap<Arc<str>, LspSettings>,
160 node: Option<Arc<dyn NodeRuntime>>,
161 default_prettier: DefaultPrettier,
162 prettiers_per_worktree: HashMap<WorktreeId, HashSet<Option<PathBuf>>>,
163 prettier_instances: HashMap<PathBuf, PrettierInstance>,
164 tasks: Model<Inventory>,
165}
166
167pub enum LanguageServerToQuery {
168 Primary,
169 Other(LanguageServerId),
170}
171
172struct LspBufferSnapshot {
173 version: i32,
174 snapshot: TextBufferSnapshot,
175}
176
177/// Message ordered with respect to buffer operations
178enum BufferOrderedMessage {
179 Operation {
180 buffer_id: BufferId,
181 operation: proto::Operation,
182 },
183 LanguageServerUpdate {
184 language_server_id: LanguageServerId,
185 message: proto::update_language_server::Variant,
186 },
187 Resync,
188}
189
190enum LocalProjectUpdate {
191 WorktreesChanged,
192 CreateBufferForPeer {
193 peer_id: proto::PeerId,
194 buffer_id: BufferId,
195 },
196}
197
198enum OpenBuffer {
199 Strong(Model<Buffer>),
200 Weak(WeakModel<Buffer>),
201 Operations(Vec<Operation>),
202}
203
204#[derive(Clone)]
205enum WorktreeHandle {
206 Strong(Model<Worktree>),
207 Weak(WeakModel<Worktree>),
208}
209
210#[derive(Debug)]
211enum ProjectClientState {
212 Local,
213 Shared {
214 remote_id: u64,
215 updates_tx: mpsc::UnboundedSender<LocalProjectUpdate>,
216 _send_updates: Task<Result<()>>,
217 },
218 Remote {
219 sharing_has_stopped: bool,
220 capability: Capability,
221 remote_id: u64,
222 replica_id: ReplicaId,
223 },
224}
225
226/// A prompt requested by LSP server.
227#[derive(Clone, Debug)]
228pub struct LanguageServerPromptRequest {
229 pub level: PromptLevel,
230 pub message: String,
231 pub actions: Vec<MessageActionItem>,
232 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 log::info!(
2882 "retrying installation of language server {server_name:?} in {}s",
2883 SERVER_REINSTALL_DEBOUNCE_TIMEOUT.as_secs()
2884 );
2885 cx.background_executor()
2886 .timer(SERVER_REINSTALL_DEBOUNCE_TIMEOUT)
2887 .await;
2888
2889 let installation_test_binary = adapter
2890 .installation_test_binary(container_dir.to_path_buf())
2891 .await;
2892
2893 this.update(&mut cx, |_, cx| {
2894 Self::check_errored_server(
2895 language,
2896 adapter,
2897 server_id,
2898 installation_test_binary,
2899 cx,
2900 )
2901 })
2902 .ok();
2903
2904 None
2905 }
2906 }
2907 })
2908 });
2909
2910 self.language_servers.insert(server_id, state);
2911 self.language_server_ids.insert(key, server_id);
2912 }
2913
2914 fn reinstall_language_server(
2915 &mut self,
2916 language: Arc<Language>,
2917 adapter: Arc<CachedLspAdapter>,
2918 server_id: LanguageServerId,
2919 cx: &mut ModelContext<Self>,
2920 ) -> Option<Task<()>> {
2921 log::info!("beginning to reinstall server");
2922
2923 let existing_server = match self.language_servers.remove(&server_id) {
2924 Some(LanguageServerState::Running { server, .. }) => Some(server),
2925 _ => None,
2926 };
2927
2928 for worktree in &self.worktrees {
2929 if let Some(worktree) = worktree.upgrade() {
2930 let key = (worktree.read(cx).id(), adapter.name.clone());
2931 self.language_server_ids.remove(&key);
2932 }
2933 }
2934
2935 Some(cx.spawn(move |this, mut cx| async move {
2936 if let Some(task) = existing_server.and_then(|server| server.shutdown()) {
2937 log::info!("shutting down existing server");
2938 task.await;
2939 }
2940
2941 // TODO: This is race-safe with regards to preventing new instances from
2942 // starting while deleting, but existing instances in other projects are going
2943 // to be very confused and messed up
2944 let Some(task) = this
2945 .update(&mut cx, |this, cx| {
2946 this.languages.delete_server_container(adapter.clone(), cx)
2947 })
2948 .log_err()
2949 else {
2950 return;
2951 };
2952 task.await;
2953
2954 this.update(&mut cx, |this, cx| {
2955 let worktrees = this.worktrees.clone();
2956 for worktree in worktrees {
2957 if let Some(worktree) = worktree.upgrade() {
2958 this.start_language_server(
2959 &worktree,
2960 adapter.clone(),
2961 language.clone(),
2962 cx,
2963 );
2964 }
2965 }
2966 })
2967 .ok();
2968 }))
2969 }
2970
2971 async fn setup_and_insert_language_server(
2972 this: WeakModel<Self>,
2973 worktree_path: &Path,
2974 override_initialization_options: Option<serde_json::Value>,
2975 pending_server: PendingLanguageServer,
2976 adapter: Arc<CachedLspAdapter>,
2977 language: Arc<Language>,
2978 server_id: LanguageServerId,
2979 key: (WorktreeId, LanguageServerName),
2980 cx: &mut AsyncAppContext,
2981 ) -> Result<Option<Arc<LanguageServer>>> {
2982 let language_server = Self::setup_pending_language_server(
2983 this.clone(),
2984 override_initialization_options,
2985 pending_server,
2986 worktree_path,
2987 adapter.clone(),
2988 server_id,
2989 cx,
2990 )
2991 .await?;
2992
2993 let this = match this.upgrade() {
2994 Some(this) => this,
2995 None => return Err(anyhow!("failed to upgrade project handle")),
2996 };
2997
2998 this.update(cx, |this, cx| {
2999 this.insert_newly_running_language_server(
3000 language,
3001 adapter,
3002 language_server.clone(),
3003 server_id,
3004 key,
3005 cx,
3006 )
3007 })??;
3008
3009 Ok(Some(language_server))
3010 }
3011
3012 async fn setup_pending_language_server(
3013 this: WeakModel<Self>,
3014 override_options: Option<serde_json::Value>,
3015 pending_server: PendingLanguageServer,
3016 worktree_path: &Path,
3017 adapter: Arc<CachedLspAdapter>,
3018 server_id: LanguageServerId,
3019 cx: &mut AsyncAppContext,
3020 ) -> Result<Arc<LanguageServer>> {
3021 let workspace_config =
3022 cx.update(|cx| adapter.workspace_configuration(worktree_path, cx))?;
3023 let language_server = pending_server.task.await?;
3024
3025 language_server
3026 .on_notification::<lsp::notification::PublishDiagnostics, _>({
3027 let adapter = adapter.clone();
3028 let this = this.clone();
3029 move |mut params, mut cx| {
3030 let adapter = adapter.clone();
3031 if let Some(this) = this.upgrade() {
3032 adapter.process_diagnostics(&mut params);
3033 this.update(&mut cx, |this, cx| {
3034 this.update_diagnostics(
3035 server_id,
3036 params,
3037 &adapter.disk_based_diagnostic_sources,
3038 cx,
3039 )
3040 .log_err();
3041 })
3042 .ok();
3043 }
3044 }
3045 })
3046 .detach();
3047
3048 language_server
3049 .on_request::<lsp::request::WorkspaceConfiguration, _, _>({
3050 let adapter = adapter.clone();
3051 let worktree_path = worktree_path.to_path_buf();
3052 move |params, cx| {
3053 let adapter = adapter.clone();
3054 let worktree_path = worktree_path.clone();
3055 async move {
3056 let workspace_config =
3057 cx.update(|cx| adapter.workspace_configuration(&worktree_path, cx))?;
3058 Ok(params
3059 .items
3060 .into_iter()
3061 .map(|item| {
3062 if let Some(section) = &item.section {
3063 workspace_config
3064 .get(section)
3065 .cloned()
3066 .unwrap_or(serde_json::Value::Null)
3067 } else {
3068 workspace_config.clone()
3069 }
3070 })
3071 .collect())
3072 }
3073 }
3074 })
3075 .detach();
3076
3077 // Even though we don't have handling for these requests, respond to them to
3078 // avoid stalling any language server like `gopls` which waits for a response
3079 // to these requests when initializing.
3080 language_server
3081 .on_request::<lsp::request::WorkDoneProgressCreate, _, _>({
3082 let this = this.clone();
3083 move |params, mut cx| {
3084 let this = this.clone();
3085 async move {
3086 this.update(&mut cx, |this, _| {
3087 if let Some(status) = this.language_server_statuses.get_mut(&server_id)
3088 {
3089 if let lsp::NumberOrString::String(token) = params.token {
3090 status.progress_tokens.insert(token);
3091 }
3092 }
3093 })?;
3094
3095 Ok(())
3096 }
3097 }
3098 })
3099 .detach();
3100
3101 language_server
3102 .on_request::<lsp::request::RegisterCapability, _, _>({
3103 let this = this.clone();
3104 move |params, mut cx| {
3105 let this = this.clone();
3106 async move {
3107 for reg in params.registrations {
3108 if reg.method == "workspace/didChangeWatchedFiles" {
3109 if let Some(options) = reg.register_options {
3110 let options = serde_json::from_value(options)?;
3111 this.update(&mut cx, |this, cx| {
3112 this.on_lsp_did_change_watched_files(
3113 server_id, options, cx,
3114 );
3115 })?;
3116 }
3117 }
3118 }
3119 Ok(())
3120 }
3121 }
3122 })
3123 .detach();
3124
3125 language_server
3126 .on_request::<lsp::request::ApplyWorkspaceEdit, _, _>({
3127 let adapter = adapter.clone();
3128 let this = this.clone();
3129 move |params, cx| {
3130 Self::on_lsp_workspace_edit(
3131 this.clone(),
3132 params,
3133 server_id,
3134 adapter.clone(),
3135 cx,
3136 )
3137 }
3138 })
3139 .detach();
3140
3141 language_server
3142 .on_request::<lsp::request::InlayHintRefreshRequest, _, _>({
3143 let this = this.clone();
3144 move |(), mut cx| {
3145 let this = this.clone();
3146 async move {
3147 this.update(&mut cx, |project, cx| {
3148 cx.emit(Event::RefreshInlayHints);
3149 project.remote_id().map(|project_id| {
3150 project.client.send(proto::RefreshInlayHints { project_id })
3151 })
3152 })?
3153 .transpose()?;
3154 Ok(())
3155 }
3156 }
3157 })
3158 .detach();
3159
3160 language_server
3161 .on_request::<lsp::request::ShowMessageRequest, _, _>({
3162 let this = this.clone();
3163 move |params, mut cx| {
3164 let this = this.clone();
3165 async move {
3166 if let Some(actions) = params.actions {
3167 let (tx, mut rx) = smol::channel::bounded(1);
3168 let request = LanguageServerPromptRequest {
3169 level: match params.typ {
3170 lsp::MessageType::ERROR => PromptLevel::Critical,
3171 lsp::MessageType::WARNING => PromptLevel::Warning,
3172 _ => PromptLevel::Info,
3173 },
3174 message: params.message,
3175 actions,
3176 response_channel: tx,
3177 };
3178
3179 if let Ok(_) = this.update(&mut cx, |_, cx| {
3180 cx.emit(Event::LanguageServerPrompt(request));
3181 }) {
3182 let response = rx.next().await;
3183
3184 Ok(response)
3185 } else {
3186 Ok(None)
3187 }
3188 } else {
3189 Ok(None)
3190 }
3191 }
3192 }
3193 })
3194 .detach();
3195
3196 let disk_based_diagnostics_progress_token =
3197 adapter.disk_based_diagnostics_progress_token.clone();
3198
3199 language_server
3200 .on_notification::<lsp::notification::Progress, _>(move |params, mut cx| {
3201 if let Some(this) = this.upgrade() {
3202 this.update(&mut cx, |this, cx| {
3203 this.on_lsp_progress(
3204 params,
3205 server_id,
3206 disk_based_diagnostics_progress_token.clone(),
3207 cx,
3208 );
3209 })
3210 .ok();
3211 }
3212 })
3213 .detach();
3214 let mut initialization_options = adapter.adapter.initialization_options();
3215 match (&mut initialization_options, override_options) {
3216 (Some(initialization_options), Some(override_options)) => {
3217 merge_json_value_into(override_options, initialization_options);
3218 }
3219 (None, override_options) => initialization_options = override_options,
3220 _ => {}
3221 }
3222 let language_server = cx
3223 .update(|cx| language_server.initialize(initialization_options, cx))?
3224 .await?;
3225
3226 language_server
3227 .notify::<lsp::notification::DidChangeConfiguration>(
3228 lsp::DidChangeConfigurationParams {
3229 settings: workspace_config,
3230 },
3231 )
3232 .ok();
3233
3234 Ok(language_server)
3235 }
3236
3237 fn insert_newly_running_language_server(
3238 &mut self,
3239 language: Arc<Language>,
3240 adapter: Arc<CachedLspAdapter>,
3241 language_server: Arc<LanguageServer>,
3242 server_id: LanguageServerId,
3243 key: (WorktreeId, LanguageServerName),
3244 cx: &mut ModelContext<Self>,
3245 ) -> Result<()> {
3246 // If the language server for this key doesn't match the server id, don't store the
3247 // server. Which will cause it to be dropped, killing the process
3248 if self
3249 .language_server_ids
3250 .get(&key)
3251 .map(|id| id != &server_id)
3252 .unwrap_or(false)
3253 {
3254 return Ok(());
3255 }
3256
3257 // Update language_servers collection with Running variant of LanguageServerState
3258 // indicating that the server is up and running and ready
3259 self.language_servers.insert(
3260 server_id,
3261 LanguageServerState::Running {
3262 adapter: adapter.clone(),
3263 language: language.clone(),
3264 watched_paths: Default::default(),
3265 server: language_server.clone(),
3266 simulate_disk_based_diagnostics_completion: None,
3267 },
3268 );
3269
3270 self.language_server_statuses.insert(
3271 server_id,
3272 LanguageServerStatus {
3273 name: language_server.name().to_string(),
3274 pending_work: Default::default(),
3275 has_pending_diagnostic_updates: false,
3276 progress_tokens: Default::default(),
3277 },
3278 );
3279
3280 cx.emit(Event::LanguageServerAdded(server_id));
3281
3282 if let Some(project_id) = self.remote_id() {
3283 self.client.send(proto::StartLanguageServer {
3284 project_id,
3285 server: Some(proto::LanguageServer {
3286 id: server_id.0 as u64,
3287 name: language_server.name().to_string(),
3288 }),
3289 })?;
3290 }
3291
3292 // Tell the language server about every open buffer in the worktree that matches the language.
3293 for buffer in self.opened_buffers.values() {
3294 if let Some(buffer_handle) = buffer.upgrade() {
3295 let buffer = buffer_handle.read(cx);
3296 let file = match File::from_dyn(buffer.file()) {
3297 Some(file) => file,
3298 None => continue,
3299 };
3300 let language = match buffer.language() {
3301 Some(language) => language,
3302 None => continue,
3303 };
3304
3305 if file.worktree.read(cx).id() != key.0
3306 || !language.lsp_adapters().iter().any(|a| a.name == key.1)
3307 {
3308 continue;
3309 }
3310
3311 let file = match file.as_local() {
3312 Some(file) => file,
3313 None => continue,
3314 };
3315
3316 let versions = self
3317 .buffer_snapshots
3318 .entry(buffer.remote_id())
3319 .or_default()
3320 .entry(server_id)
3321 .or_insert_with(|| {
3322 vec![LspBufferSnapshot {
3323 version: 0,
3324 snapshot: buffer.text_snapshot(),
3325 }]
3326 });
3327
3328 let snapshot = versions.last().unwrap();
3329 let version = snapshot.version;
3330 let initial_snapshot = &snapshot.snapshot;
3331 let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
3332 language_server.notify::<lsp::notification::DidOpenTextDocument>(
3333 lsp::DidOpenTextDocumentParams {
3334 text_document: lsp::TextDocumentItem::new(
3335 uri,
3336 adapter
3337 .language_ids
3338 .get(language.name().as_ref())
3339 .cloned()
3340 .unwrap_or_default(),
3341 version,
3342 initial_snapshot.text(),
3343 ),
3344 },
3345 )?;
3346
3347 buffer_handle.update(cx, |buffer, cx| {
3348 buffer.set_completion_triggers(
3349 language_server
3350 .capabilities()
3351 .completion_provider
3352 .as_ref()
3353 .and_then(|provider| provider.trigger_characters.clone())
3354 .unwrap_or_default(),
3355 cx,
3356 )
3357 });
3358 }
3359 }
3360
3361 cx.notify();
3362 Ok(())
3363 }
3364
3365 // Returns a list of all of the worktrees which no longer have a language server and the root path
3366 // for the stopped server
3367 fn stop_language_server(
3368 &mut self,
3369 worktree_id: WorktreeId,
3370 adapter_name: LanguageServerName,
3371 cx: &mut ModelContext<Self>,
3372 ) -> Task<Vec<WorktreeId>> {
3373 let key = (worktree_id, adapter_name);
3374 if let Some(server_id) = self.language_server_ids.remove(&key) {
3375 let name = key.1 .0;
3376 log::info!("stopping language server {name}");
3377
3378 // Remove other entries for this language server as well
3379 let mut orphaned_worktrees = vec![worktree_id];
3380 let other_keys = self.language_server_ids.keys().cloned().collect::<Vec<_>>();
3381 for other_key in other_keys {
3382 if self.language_server_ids.get(&other_key) == Some(&server_id) {
3383 self.language_server_ids.remove(&other_key);
3384 orphaned_worktrees.push(other_key.0);
3385 }
3386 }
3387
3388 for buffer in self.opened_buffers.values() {
3389 if let Some(buffer) = buffer.upgrade() {
3390 buffer.update(cx, |buffer, cx| {
3391 buffer.update_diagnostics(server_id, Default::default(), cx);
3392 });
3393 }
3394 }
3395 for worktree in &self.worktrees {
3396 if let Some(worktree) = worktree.upgrade() {
3397 worktree.update(cx, |worktree, cx| {
3398 if let Some(worktree) = worktree.as_local_mut() {
3399 worktree.clear_diagnostics_for_language_server(server_id, cx);
3400 }
3401 });
3402 }
3403 }
3404
3405 self.language_server_statuses.remove(&server_id);
3406 cx.notify();
3407
3408 let server_state = self.language_servers.remove(&server_id);
3409 cx.emit(Event::LanguageServerRemoved(server_id));
3410 cx.spawn(move |this, cx| async move {
3411 Self::shutdown_language_server(this, server_state, name, server_id, cx).await;
3412 orphaned_worktrees
3413 })
3414 } else {
3415 Task::ready(Vec::new())
3416 }
3417 }
3418
3419 async fn shutdown_language_server(
3420 this: WeakModel<Project>,
3421 server_state: Option<LanguageServerState>,
3422 name: Arc<str>,
3423 server_id: LanguageServerId,
3424 mut cx: AsyncAppContext,
3425 ) {
3426 let server = match server_state {
3427 Some(LanguageServerState::Starting(task)) => {
3428 let mut timer = cx
3429 .background_executor()
3430 .timer(SERVER_LAUNCHING_BEFORE_SHUTDOWN_TIMEOUT)
3431 .fuse();
3432
3433 select! {
3434 server = task.fuse() => server,
3435 _ = timer => {
3436 log::info!(
3437 "timeout waiting for language server {} to finish launching before stopping",
3438 name
3439 );
3440 None
3441 },
3442 }
3443 }
3444
3445 Some(LanguageServerState::Running { server, .. }) => Some(server),
3446
3447 None => None,
3448 };
3449
3450 if let Some(server) = server {
3451 if let Some(shutdown) = server.shutdown() {
3452 shutdown.await;
3453 }
3454 }
3455
3456 if let Some(this) = this.upgrade() {
3457 this.update(&mut cx, |this, cx| {
3458 this.language_server_statuses.remove(&server_id);
3459 cx.notify();
3460 })
3461 .ok();
3462 }
3463 }
3464
3465 pub fn restart_language_servers_for_buffers(
3466 &mut self,
3467 buffers: impl IntoIterator<Item = Model<Buffer>>,
3468 cx: &mut ModelContext<Self>,
3469 ) -> Option<()> {
3470 let language_server_lookup_info: HashSet<(Model<Worktree>, Arc<Language>)> = buffers
3471 .into_iter()
3472 .filter_map(|buffer| {
3473 let buffer = buffer.read(cx);
3474 let file = File::from_dyn(buffer.file())?;
3475 let full_path = file.full_path(cx);
3476 let language = self
3477 .languages
3478 .language_for_file(&full_path, Some(buffer.as_rope()))
3479 .now_or_never()?
3480 .ok()?;
3481 Some((file.worktree.clone(), language))
3482 })
3483 .collect();
3484 for (worktree, language) in language_server_lookup_info {
3485 self.restart_language_servers(worktree, language, cx);
3486 }
3487
3488 None
3489 }
3490
3491 fn restart_language_servers(
3492 &mut self,
3493 worktree: Model<Worktree>,
3494 language: Arc<Language>,
3495 cx: &mut ModelContext<Self>,
3496 ) {
3497 let worktree_id = worktree.read(cx).id();
3498
3499 let stop_tasks = language
3500 .lsp_adapters()
3501 .iter()
3502 .map(|adapter| {
3503 let stop_task = self.stop_language_server(worktree_id, adapter.name.clone(), cx);
3504 (stop_task, adapter.name.clone())
3505 })
3506 .collect::<Vec<_>>();
3507 if stop_tasks.is_empty() {
3508 return;
3509 }
3510
3511 cx.spawn(move |this, mut cx| async move {
3512 // For each stopped language server, record all of the worktrees with which
3513 // it was associated.
3514 let mut affected_worktrees = Vec::new();
3515 for (stop_task, language_server_name) in stop_tasks {
3516 for affected_worktree_id in stop_task.await {
3517 affected_worktrees.push((affected_worktree_id, language_server_name.clone()));
3518 }
3519 }
3520
3521 this.update(&mut cx, |this, cx| {
3522 // Restart the language server for the given worktree.
3523 this.start_language_servers(&worktree, language.clone(), cx);
3524
3525 // Lookup new server ids and set them for each of the orphaned worktrees
3526 for (affected_worktree_id, language_server_name) in affected_worktrees {
3527 if let Some(new_server_id) = this
3528 .language_server_ids
3529 .get(&(worktree_id, language_server_name.clone()))
3530 .cloned()
3531 {
3532 this.language_server_ids
3533 .insert((affected_worktree_id, language_server_name), new_server_id);
3534 }
3535 }
3536 })
3537 .ok();
3538 })
3539 .detach();
3540 }
3541
3542 fn check_errored_server(
3543 language: Arc<Language>,
3544 adapter: Arc<CachedLspAdapter>,
3545 server_id: LanguageServerId,
3546 installation_test_binary: Option<LanguageServerBinary>,
3547 cx: &mut ModelContext<Self>,
3548 ) {
3549 if !adapter.can_be_reinstalled() {
3550 log::info!(
3551 "Validation check requested for {:?} but it cannot be reinstalled",
3552 adapter.name.0
3553 );
3554 return;
3555 }
3556
3557 cx.spawn(move |this, mut cx| async move {
3558 log::info!("About to spawn test binary");
3559
3560 // A lack of test binary counts as a failure
3561 let process = installation_test_binary.and_then(|binary| {
3562 smol::process::Command::new(&binary.path)
3563 .current_dir(&binary.path)
3564 .args(binary.arguments)
3565 .stdin(Stdio::piped())
3566 .stdout(Stdio::piped())
3567 .stderr(Stdio::inherit())
3568 .kill_on_drop(true)
3569 .spawn()
3570 .ok()
3571 });
3572
3573 const PROCESS_TIMEOUT: Duration = Duration::from_secs(5);
3574 let mut timeout = cx.background_executor().timer(PROCESS_TIMEOUT).fuse();
3575
3576 let mut errored = false;
3577 if let Some(mut process) = process {
3578 futures::select! {
3579 status = process.status().fuse() => match status {
3580 Ok(status) => errored = !status.success(),
3581 Err(_) => errored = true,
3582 },
3583
3584 _ = timeout => {
3585 log::info!("test binary time-ed out, this counts as a success");
3586 _ = process.kill();
3587 }
3588 }
3589 } else {
3590 log::warn!("test binary failed to launch");
3591 errored = true;
3592 }
3593
3594 if errored {
3595 log::warn!("test binary check failed");
3596 let task = this
3597 .update(&mut cx, move |this, cx| {
3598 this.reinstall_language_server(language, adapter, server_id, cx)
3599 })
3600 .ok()
3601 .flatten();
3602
3603 if let Some(task) = task {
3604 task.await;
3605 }
3606 }
3607 })
3608 .detach();
3609 }
3610
3611 fn on_lsp_progress(
3612 &mut self,
3613 progress: lsp::ProgressParams,
3614 language_server_id: LanguageServerId,
3615 disk_based_diagnostics_progress_token: Option<String>,
3616 cx: &mut ModelContext<Self>,
3617 ) {
3618 let token = match progress.token {
3619 lsp::NumberOrString::String(token) => token,
3620 lsp::NumberOrString::Number(token) => {
3621 log::info!("skipping numeric progress token {}", token);
3622 return;
3623 }
3624 };
3625 let lsp::ProgressParamsValue::WorkDone(progress) = progress.value;
3626 let language_server_status =
3627 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
3628 status
3629 } else {
3630 return;
3631 };
3632
3633 if !language_server_status.progress_tokens.contains(&token) {
3634 return;
3635 }
3636
3637 let is_disk_based_diagnostics_progress = disk_based_diagnostics_progress_token
3638 .as_ref()
3639 .map_or(false, |disk_based_token| {
3640 token.starts_with(disk_based_token)
3641 });
3642
3643 match progress {
3644 lsp::WorkDoneProgress::Begin(report) => {
3645 if is_disk_based_diagnostics_progress {
3646 language_server_status.has_pending_diagnostic_updates = true;
3647 self.disk_based_diagnostics_started(language_server_id, cx);
3648 self.buffer_ordered_messages_tx
3649 .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
3650 language_server_id,
3651 message: proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(Default::default())
3652 })
3653 .ok();
3654 } else {
3655 self.on_lsp_work_start(
3656 language_server_id,
3657 token.clone(),
3658 LanguageServerProgress {
3659 message: report.message.clone(),
3660 percentage: report.percentage.map(|p| p as usize),
3661 last_update_at: Instant::now(),
3662 },
3663 cx,
3664 );
3665 self.buffer_ordered_messages_tx
3666 .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
3667 language_server_id,
3668 message: proto::update_language_server::Variant::WorkStart(
3669 proto::LspWorkStart {
3670 token,
3671 message: report.message,
3672 percentage: report.percentage.map(|p| p as u32),
3673 },
3674 ),
3675 })
3676 .ok();
3677 }
3678 }
3679 lsp::WorkDoneProgress::Report(report) => {
3680 if !is_disk_based_diagnostics_progress {
3681 self.on_lsp_work_progress(
3682 language_server_id,
3683 token.clone(),
3684 LanguageServerProgress {
3685 message: report.message.clone(),
3686 percentage: report.percentage.map(|p| p as usize),
3687 last_update_at: Instant::now(),
3688 },
3689 cx,
3690 );
3691 self.buffer_ordered_messages_tx
3692 .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
3693 language_server_id,
3694 message: proto::update_language_server::Variant::WorkProgress(
3695 proto::LspWorkProgress {
3696 token,
3697 message: report.message,
3698 percentage: report.percentage.map(|p| p as u32),
3699 },
3700 ),
3701 })
3702 .ok();
3703 }
3704 }
3705 lsp::WorkDoneProgress::End(_) => {
3706 language_server_status.progress_tokens.remove(&token);
3707
3708 if is_disk_based_diagnostics_progress {
3709 language_server_status.has_pending_diagnostic_updates = false;
3710 self.disk_based_diagnostics_finished(language_server_id, cx);
3711 self.buffer_ordered_messages_tx
3712 .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
3713 language_server_id,
3714 message:
3715 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
3716 Default::default(),
3717 ),
3718 })
3719 .ok();
3720 } else {
3721 self.on_lsp_work_end(language_server_id, token.clone(), cx);
3722 self.buffer_ordered_messages_tx
3723 .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
3724 language_server_id,
3725 message: proto::update_language_server::Variant::WorkEnd(
3726 proto::LspWorkEnd { token },
3727 ),
3728 })
3729 .ok();
3730 }
3731 }
3732 }
3733 }
3734
3735 fn on_lsp_work_start(
3736 &mut self,
3737 language_server_id: LanguageServerId,
3738 token: String,
3739 progress: LanguageServerProgress,
3740 cx: &mut ModelContext<Self>,
3741 ) {
3742 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
3743 status.pending_work.insert(token, progress);
3744 cx.notify();
3745 }
3746 }
3747
3748 fn on_lsp_work_progress(
3749 &mut self,
3750 language_server_id: LanguageServerId,
3751 token: String,
3752 progress: LanguageServerProgress,
3753 cx: &mut ModelContext<Self>,
3754 ) {
3755 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
3756 let entry = status
3757 .pending_work
3758 .entry(token)
3759 .or_insert(LanguageServerProgress {
3760 message: Default::default(),
3761 percentage: Default::default(),
3762 last_update_at: progress.last_update_at,
3763 });
3764 if progress.message.is_some() {
3765 entry.message = progress.message;
3766 }
3767 if progress.percentage.is_some() {
3768 entry.percentage = progress.percentage;
3769 }
3770 entry.last_update_at = progress.last_update_at;
3771 cx.notify();
3772 }
3773 }
3774
3775 fn on_lsp_work_end(
3776 &mut self,
3777 language_server_id: LanguageServerId,
3778 token: String,
3779 cx: &mut ModelContext<Self>,
3780 ) {
3781 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
3782 cx.emit(Event::RefreshInlayHints);
3783 status.pending_work.remove(&token);
3784 cx.notify();
3785 }
3786 }
3787
3788 fn on_lsp_did_change_watched_files(
3789 &mut self,
3790 language_server_id: LanguageServerId,
3791 params: DidChangeWatchedFilesRegistrationOptions,
3792 cx: &mut ModelContext<Self>,
3793 ) {
3794 if let Some(LanguageServerState::Running { watched_paths, .. }) =
3795 self.language_servers.get_mut(&language_server_id)
3796 {
3797 let mut builders = HashMap::default();
3798 for watcher in params.watchers {
3799 for worktree in &self.worktrees {
3800 if let Some(worktree) = worktree.upgrade() {
3801 let glob_is_inside_worktree = worktree.update(cx, |tree, _| {
3802 if let Some(abs_path) = tree.abs_path().to_str() {
3803 let relative_glob_pattern = match &watcher.glob_pattern {
3804 lsp::GlobPattern::String(s) => s
3805 .strip_prefix(abs_path)
3806 .and_then(|s| s.strip_prefix(std::path::MAIN_SEPARATOR)),
3807 lsp::GlobPattern::Relative(rp) => {
3808 let base_uri = match &rp.base_uri {
3809 lsp::OneOf::Left(workspace_folder) => {
3810 &workspace_folder.uri
3811 }
3812 lsp::OneOf::Right(base_uri) => base_uri,
3813 };
3814 base_uri.to_file_path().ok().and_then(|file_path| {
3815 (file_path.to_str() == Some(abs_path))
3816 .then_some(rp.pattern.as_str())
3817 })
3818 }
3819 };
3820 if let Some(relative_glob_pattern) = relative_glob_pattern {
3821 let literal_prefix = glob_literal_prefix(relative_glob_pattern);
3822 tree.as_local_mut()
3823 .unwrap()
3824 .add_path_prefix_to_scan(Path::new(literal_prefix).into());
3825 if let Some(glob) = Glob::new(relative_glob_pattern).log_err() {
3826 builders
3827 .entry(tree.id())
3828 .or_insert_with(|| GlobSetBuilder::new())
3829 .add(glob);
3830 }
3831 return true;
3832 }
3833 }
3834 false
3835 });
3836 if glob_is_inside_worktree {
3837 break;
3838 }
3839 }
3840 }
3841 }
3842
3843 watched_paths.clear();
3844 for (worktree_id, builder) in builders {
3845 if let Ok(globset) = builder.build() {
3846 watched_paths.insert(worktree_id, globset);
3847 }
3848 }
3849
3850 cx.notify();
3851 }
3852 }
3853
3854 async fn on_lsp_workspace_edit(
3855 this: WeakModel<Self>,
3856 params: lsp::ApplyWorkspaceEditParams,
3857 server_id: LanguageServerId,
3858 adapter: Arc<CachedLspAdapter>,
3859 mut cx: AsyncAppContext,
3860 ) -> Result<lsp::ApplyWorkspaceEditResponse> {
3861 let this = this
3862 .upgrade()
3863 .ok_or_else(|| anyhow!("project project closed"))?;
3864 let language_server = this
3865 .update(&mut cx, |this, _| this.language_server_for_id(server_id))?
3866 .ok_or_else(|| anyhow!("language server not found"))?;
3867 let transaction = Self::deserialize_workspace_edit(
3868 this.clone(),
3869 params.edit,
3870 true,
3871 adapter.clone(),
3872 language_server.clone(),
3873 &mut cx,
3874 )
3875 .await
3876 .log_err();
3877 this.update(&mut cx, |this, _| {
3878 if let Some(transaction) = transaction {
3879 this.last_workspace_edits_by_language_server
3880 .insert(server_id, transaction);
3881 }
3882 })?;
3883 Ok(lsp::ApplyWorkspaceEditResponse {
3884 applied: true,
3885 failed_change: None,
3886 failure_reason: None,
3887 })
3888 }
3889
3890 pub fn language_server_statuses(
3891 &self,
3892 ) -> impl DoubleEndedIterator<Item = &LanguageServerStatus> {
3893 self.language_server_statuses.values()
3894 }
3895
3896 pub fn update_diagnostics(
3897 &mut self,
3898 language_server_id: LanguageServerId,
3899 mut params: lsp::PublishDiagnosticsParams,
3900 disk_based_sources: &[String],
3901 cx: &mut ModelContext<Self>,
3902 ) -> Result<()> {
3903 let abs_path = params
3904 .uri
3905 .to_file_path()
3906 .map_err(|_| anyhow!("URI is not a file"))?;
3907 let mut diagnostics = Vec::default();
3908 let mut primary_diagnostic_group_ids = HashMap::default();
3909 let mut sources_by_group_id = HashMap::default();
3910 let mut supporting_diagnostics = HashMap::default();
3911
3912 // Ensure that primary diagnostics are always the most severe
3913 params.diagnostics.sort_by_key(|item| item.severity);
3914
3915 for diagnostic in ¶ms.diagnostics {
3916 let source = diagnostic.source.as_ref();
3917 let code = diagnostic.code.as_ref().map(|code| match code {
3918 lsp::NumberOrString::Number(code) => code.to_string(),
3919 lsp::NumberOrString::String(code) => code.clone(),
3920 });
3921 let range = range_from_lsp(diagnostic.range);
3922 let is_supporting = diagnostic
3923 .related_information
3924 .as_ref()
3925 .map_or(false, |infos| {
3926 infos.iter().any(|info| {
3927 primary_diagnostic_group_ids.contains_key(&(
3928 source,
3929 code.clone(),
3930 range_from_lsp(info.location.range),
3931 ))
3932 })
3933 });
3934
3935 let is_unnecessary = diagnostic.tags.as_ref().map_or(false, |tags| {
3936 tags.iter().any(|tag| *tag == DiagnosticTag::UNNECESSARY)
3937 });
3938
3939 if is_supporting {
3940 supporting_diagnostics.insert(
3941 (source, code.clone(), range),
3942 (diagnostic.severity, is_unnecessary),
3943 );
3944 } else {
3945 let group_id = post_inc(&mut self.next_diagnostic_group_id);
3946 let is_disk_based =
3947 source.map_or(false, |source| disk_based_sources.contains(source));
3948
3949 sources_by_group_id.insert(group_id, source);
3950 primary_diagnostic_group_ids
3951 .insert((source, code.clone(), range.clone()), group_id);
3952
3953 diagnostics.push(DiagnosticEntry {
3954 range,
3955 diagnostic: Diagnostic {
3956 source: diagnostic.source.clone(),
3957 code: code.clone(),
3958 severity: diagnostic.severity.unwrap_or(DiagnosticSeverity::ERROR),
3959 message: diagnostic.message.trim().to_string(),
3960 group_id,
3961 is_primary: true,
3962 is_disk_based,
3963 is_unnecessary,
3964 },
3965 });
3966 if let Some(infos) = &diagnostic.related_information {
3967 for info in infos {
3968 if info.location.uri == params.uri && !info.message.is_empty() {
3969 let range = range_from_lsp(info.location.range);
3970 diagnostics.push(DiagnosticEntry {
3971 range,
3972 diagnostic: Diagnostic {
3973 source: diagnostic.source.clone(),
3974 code: code.clone(),
3975 severity: DiagnosticSeverity::INFORMATION,
3976 message: info.message.trim().to_string(),
3977 group_id,
3978 is_primary: false,
3979 is_disk_based,
3980 is_unnecessary: false,
3981 },
3982 });
3983 }
3984 }
3985 }
3986 }
3987 }
3988
3989 for entry in &mut diagnostics {
3990 let diagnostic = &mut entry.diagnostic;
3991 if !diagnostic.is_primary {
3992 let source = *sources_by_group_id.get(&diagnostic.group_id).unwrap();
3993 if let Some(&(severity, is_unnecessary)) = supporting_diagnostics.get(&(
3994 source,
3995 diagnostic.code.clone(),
3996 entry.range.clone(),
3997 )) {
3998 if let Some(severity) = severity {
3999 diagnostic.severity = severity;
4000 }
4001 diagnostic.is_unnecessary = is_unnecessary;
4002 }
4003 }
4004 }
4005
4006 self.update_diagnostic_entries(
4007 language_server_id,
4008 abs_path,
4009 params.version,
4010 diagnostics,
4011 cx,
4012 )?;
4013 Ok(())
4014 }
4015
4016 pub fn update_diagnostic_entries(
4017 &mut self,
4018 server_id: LanguageServerId,
4019 abs_path: PathBuf,
4020 version: Option<i32>,
4021 diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
4022 cx: &mut ModelContext<Project>,
4023 ) -> Result<(), anyhow::Error> {
4024 let (worktree, relative_path) = self
4025 .find_local_worktree(&abs_path, cx)
4026 .ok_or_else(|| anyhow!("no worktree found for diagnostics path {abs_path:?}"))?;
4027
4028 let project_path = ProjectPath {
4029 worktree_id: worktree.read(cx).id(),
4030 path: relative_path.into(),
4031 };
4032
4033 if let Some(buffer) = self.get_open_buffer(&project_path, cx) {
4034 self.update_buffer_diagnostics(&buffer, server_id, version, diagnostics.clone(), cx)?;
4035 }
4036
4037 let updated = worktree.update(cx, |worktree, cx| {
4038 worktree
4039 .as_local_mut()
4040 .ok_or_else(|| anyhow!("not a local worktree"))?
4041 .update_diagnostics(server_id, project_path.path.clone(), diagnostics, cx)
4042 })?;
4043 if updated {
4044 cx.emit(Event::DiagnosticsUpdated {
4045 language_server_id: server_id,
4046 path: project_path,
4047 });
4048 }
4049 Ok(())
4050 }
4051
4052 fn update_buffer_diagnostics(
4053 &mut self,
4054 buffer: &Model<Buffer>,
4055 server_id: LanguageServerId,
4056 version: Option<i32>,
4057 mut diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
4058 cx: &mut ModelContext<Self>,
4059 ) -> Result<()> {
4060 fn compare_diagnostics(a: &Diagnostic, b: &Diagnostic) -> Ordering {
4061 Ordering::Equal
4062 .then_with(|| b.is_primary.cmp(&a.is_primary))
4063 .then_with(|| a.is_disk_based.cmp(&b.is_disk_based))
4064 .then_with(|| a.severity.cmp(&b.severity))
4065 .then_with(|| a.message.cmp(&b.message))
4066 }
4067
4068 let snapshot = self.buffer_snapshot_for_lsp_version(buffer, server_id, version, cx)?;
4069
4070 diagnostics.sort_unstable_by(|a, b| {
4071 Ordering::Equal
4072 .then_with(|| a.range.start.cmp(&b.range.start))
4073 .then_with(|| b.range.end.cmp(&a.range.end))
4074 .then_with(|| compare_diagnostics(&a.diagnostic, &b.diagnostic))
4075 });
4076
4077 let mut sanitized_diagnostics = Vec::new();
4078 let edits_since_save = Patch::new(
4079 snapshot
4080 .edits_since::<Unclipped<PointUtf16>>(buffer.read(cx).saved_version())
4081 .collect(),
4082 );
4083 for entry in diagnostics {
4084 let start;
4085 let end;
4086 if entry.diagnostic.is_disk_based {
4087 // Some diagnostics are based on files on disk instead of buffers'
4088 // current contents. Adjust these diagnostics' ranges to reflect
4089 // any unsaved edits.
4090 start = edits_since_save.old_to_new(entry.range.start);
4091 end = edits_since_save.old_to_new(entry.range.end);
4092 } else {
4093 start = entry.range.start;
4094 end = entry.range.end;
4095 }
4096
4097 let mut range = snapshot.clip_point_utf16(start, Bias::Left)
4098 ..snapshot.clip_point_utf16(end, Bias::Right);
4099
4100 // Expand empty ranges by one codepoint
4101 if range.start == range.end {
4102 // This will be go to the next boundary when being clipped
4103 range.end.column += 1;
4104 range.end = snapshot.clip_point_utf16(Unclipped(range.end), Bias::Right);
4105 if range.start == range.end && range.end.column > 0 {
4106 range.start.column -= 1;
4107 range.start = snapshot.clip_point_utf16(Unclipped(range.start), Bias::Left);
4108 }
4109 }
4110
4111 sanitized_diagnostics.push(DiagnosticEntry {
4112 range,
4113 diagnostic: entry.diagnostic,
4114 });
4115 }
4116 drop(edits_since_save);
4117
4118 let set = DiagnosticSet::new(sanitized_diagnostics, &snapshot);
4119 buffer.update(cx, |buffer, cx| {
4120 buffer.update_diagnostics(server_id, set, cx)
4121 });
4122 Ok(())
4123 }
4124
4125 pub fn reload_buffers(
4126 &self,
4127 buffers: HashSet<Model<Buffer>>,
4128 push_to_history: bool,
4129 cx: &mut ModelContext<Self>,
4130 ) -> Task<Result<ProjectTransaction>> {
4131 let mut local_buffers = Vec::new();
4132 let mut remote_buffers = None;
4133 for buffer_handle in buffers {
4134 let buffer = buffer_handle.read(cx);
4135 if buffer.is_dirty() {
4136 if let Some(file) = File::from_dyn(buffer.file()) {
4137 if file.is_local() {
4138 local_buffers.push(buffer_handle);
4139 } else {
4140 remote_buffers.get_or_insert(Vec::new()).push(buffer_handle);
4141 }
4142 }
4143 }
4144 }
4145
4146 let remote_buffers = self.remote_id().zip(remote_buffers);
4147 let client = self.client.clone();
4148
4149 cx.spawn(move |this, mut cx| async move {
4150 let mut project_transaction = ProjectTransaction::default();
4151
4152 if let Some((project_id, remote_buffers)) = remote_buffers {
4153 let response = client
4154 .request(proto::ReloadBuffers {
4155 project_id,
4156 buffer_ids: remote_buffers
4157 .iter()
4158 .filter_map(|buffer| {
4159 buffer
4160 .update(&mut cx, |buffer, _| buffer.remote_id().into())
4161 .ok()
4162 })
4163 .collect(),
4164 })
4165 .await?
4166 .transaction
4167 .ok_or_else(|| anyhow!("missing transaction"))?;
4168 project_transaction = this
4169 .update(&mut cx, |this, cx| {
4170 this.deserialize_project_transaction(response, push_to_history, cx)
4171 })?
4172 .await?;
4173 }
4174
4175 for buffer in local_buffers {
4176 let transaction = buffer
4177 .update(&mut cx, |buffer, cx| buffer.reload(cx))?
4178 .await?;
4179 buffer.update(&mut cx, |buffer, cx| {
4180 if let Some(transaction) = transaction {
4181 if !push_to_history {
4182 buffer.forget_transaction(transaction.id);
4183 }
4184 project_transaction.0.insert(cx.handle(), transaction);
4185 }
4186 })?;
4187 }
4188
4189 Ok(project_transaction)
4190 })
4191 }
4192
4193 pub fn format(
4194 &mut self,
4195 buffers: HashSet<Model<Buffer>>,
4196 push_to_history: bool,
4197 trigger: FormatTrigger,
4198 cx: &mut ModelContext<Project>,
4199 ) -> Task<anyhow::Result<ProjectTransaction>> {
4200 if self.is_local() {
4201 let mut buffers_with_paths_and_servers = buffers
4202 .into_iter()
4203 .filter_map(|buffer_handle| {
4204 let buffer = buffer_handle.read(cx);
4205 let file = File::from_dyn(buffer.file())?;
4206 let buffer_abs_path = file.as_local().map(|f| f.abs_path(cx));
4207 let (adapter, server) = self
4208 .primary_language_server_for_buffer(buffer, cx)
4209 .map(|(a, s)| (Some(a.clone()), Some(s.clone())))
4210 .unwrap_or((None, None));
4211 Some((buffer_handle, buffer_abs_path, adapter, server))
4212 })
4213 .collect::<Vec<_>>();
4214
4215 cx.spawn(move |project, mut cx| async move {
4216 // Do not allow multiple concurrent formatting requests for the
4217 // same buffer.
4218 project.update(&mut cx, |this, cx| {
4219 buffers_with_paths_and_servers.retain(|(buffer, _, _, _)| {
4220 this.buffers_being_formatted
4221 .insert(buffer.read(cx).remote_id())
4222 });
4223 })?;
4224
4225 let _cleanup = defer({
4226 let this = project.clone();
4227 let mut cx = cx.clone();
4228 let buffers = &buffers_with_paths_and_servers;
4229 move || {
4230 this.update(&mut cx, |this, cx| {
4231 for (buffer, _, _, _) in buffers {
4232 this.buffers_being_formatted
4233 .remove(&buffer.read(cx).remote_id());
4234 }
4235 })
4236 .ok();
4237 }
4238 });
4239
4240 let mut project_transaction = ProjectTransaction::default();
4241 for (buffer, buffer_abs_path, lsp_adapter, language_server) in
4242 &buffers_with_paths_and_servers
4243 {
4244 let settings = buffer.update(&mut cx, |buffer, cx| {
4245 language_settings(buffer.language(), buffer.file(), cx).clone()
4246 })?;
4247
4248 let remove_trailing_whitespace = settings.remove_trailing_whitespace_on_save;
4249 let ensure_final_newline = settings.ensure_final_newline_on_save;
4250 let tab_size = settings.tab_size;
4251
4252 // First, format buffer's whitespace according to the settings.
4253 let trailing_whitespace_diff = if remove_trailing_whitespace {
4254 Some(
4255 buffer
4256 .update(&mut cx, |b, cx| b.remove_trailing_whitespace(cx))?
4257 .await,
4258 )
4259 } else {
4260 None
4261 };
4262 let whitespace_transaction_id = buffer.update(&mut cx, |buffer, cx| {
4263 buffer.finalize_last_transaction();
4264 buffer.start_transaction();
4265 if let Some(diff) = trailing_whitespace_diff {
4266 buffer.apply_diff(diff, cx);
4267 }
4268 if ensure_final_newline {
4269 buffer.ensure_final_newline(cx);
4270 }
4271 buffer.end_transaction(cx)
4272 })?;
4273
4274 if let (Some(lsp_adapter), Some(language_server)) =
4275 (lsp_adapter, language_server)
4276 {
4277 // Apply the code actions on
4278 let code_actions: Vec<lsp::CodeActionKind> = settings
4279 .code_actions_on_format
4280 .iter()
4281 .flat_map(|(kind, enabled)| {
4282 if *enabled {
4283 Some(kind.clone().into())
4284 } else {
4285 None
4286 }
4287 })
4288 .collect();
4289
4290 if !code_actions.is_empty()
4291 && !(trigger == FormatTrigger::Save
4292 && settings.format_on_save == FormatOnSave::Off)
4293 {
4294 let actions = project
4295 .update(&mut cx, |this, cx| {
4296 this.request_lsp(
4297 buffer.clone(),
4298 LanguageServerToQuery::Other(language_server.server_id()),
4299 GetCodeActions {
4300 range: text::Anchor::MIN..text::Anchor::MAX,
4301 kinds: Some(code_actions),
4302 },
4303 cx,
4304 )
4305 })?
4306 .await?;
4307
4308 for action in actions {
4309 if let Some(edit) = action.lsp_action.edit {
4310 if edit.changes.is_none() && edit.document_changes.is_none() {
4311 continue;
4312 }
4313 let new = Self::deserialize_workspace_edit(
4314 project
4315 .upgrade()
4316 .ok_or_else(|| anyhow!("project dropped"))?,
4317 edit,
4318 push_to_history,
4319 lsp_adapter.clone(),
4320 language_server.clone(),
4321 &mut cx,
4322 )
4323 .await?;
4324 project_transaction.0.extend(new.0);
4325 }
4326
4327 if let Some(command) = action.lsp_action.command {
4328 project.update(&mut cx, |this, _| {
4329 this.last_workspace_edits_by_language_server
4330 .remove(&language_server.server_id());
4331 })?;
4332
4333 language_server
4334 .request::<lsp::request::ExecuteCommand>(
4335 lsp::ExecuteCommandParams {
4336 command: command.command,
4337 arguments: command.arguments.unwrap_or_default(),
4338 ..Default::default()
4339 },
4340 )
4341 .await?;
4342
4343 project.update(&mut cx, |this, _| {
4344 project_transaction.0.extend(
4345 this.last_workspace_edits_by_language_server
4346 .remove(&language_server.server_id())
4347 .unwrap_or_default()
4348 .0,
4349 )
4350 })?;
4351 }
4352 }
4353 }
4354 }
4355
4356 // Apply language-specific formatting using either a language server
4357 // or external command.
4358 let mut format_operation = None;
4359 match (&settings.formatter, &settings.format_on_save) {
4360 (_, FormatOnSave::Off) if trigger == FormatTrigger::Save => {}
4361
4362 (Formatter::LanguageServer, FormatOnSave::On | FormatOnSave::Off)
4363 | (_, FormatOnSave::LanguageServer) => {
4364 if let Some((language_server, buffer_abs_path)) =
4365 language_server.as_ref().zip(buffer_abs_path.as_ref())
4366 {
4367 format_operation = Some(FormatOperation::Lsp(
4368 Self::format_via_lsp(
4369 &project,
4370 buffer,
4371 buffer_abs_path,
4372 language_server,
4373 tab_size,
4374 &mut cx,
4375 )
4376 .await
4377 .context("failed to format via language server")?,
4378 ));
4379 }
4380 }
4381
4382 (
4383 Formatter::External { command, arguments },
4384 FormatOnSave::On | FormatOnSave::Off,
4385 )
4386 | (_, FormatOnSave::External { command, arguments }) => {
4387 if let Some(buffer_abs_path) = buffer_abs_path {
4388 format_operation = Self::format_via_external_command(
4389 buffer,
4390 buffer_abs_path,
4391 command,
4392 arguments,
4393 &mut cx,
4394 )
4395 .await
4396 .context(format!(
4397 "failed to format via external command {:?}",
4398 command
4399 ))?
4400 .map(FormatOperation::External);
4401 }
4402 }
4403 (Formatter::Auto, FormatOnSave::On | FormatOnSave::Off) => {
4404 if let Some(new_operation) =
4405 prettier_support::format_with_prettier(&project, buffer, &mut cx)
4406 .await
4407 {
4408 format_operation = Some(new_operation);
4409 } else if let Some((language_server, buffer_abs_path)) =
4410 language_server.as_ref().zip(buffer_abs_path.as_ref())
4411 {
4412 format_operation = Some(FormatOperation::Lsp(
4413 Self::format_via_lsp(
4414 &project,
4415 buffer,
4416 buffer_abs_path,
4417 language_server,
4418 tab_size,
4419 &mut cx,
4420 )
4421 .await
4422 .context("failed to format via language server")?,
4423 ));
4424 }
4425 }
4426 (Formatter::Prettier, FormatOnSave::On | FormatOnSave::Off) => {
4427 if let Some(new_operation) =
4428 prettier_support::format_with_prettier(&project, buffer, &mut cx)
4429 .await
4430 {
4431 format_operation = Some(new_operation);
4432 }
4433 }
4434 };
4435
4436 buffer.update(&mut cx, |b, cx| {
4437 // If the buffer had its whitespace formatted and was edited while the language-specific
4438 // formatting was being computed, avoid applying the language-specific formatting, because
4439 // it can't be grouped with the whitespace formatting in the undo history.
4440 if let Some(transaction_id) = whitespace_transaction_id {
4441 if b.peek_undo_stack()
4442 .map_or(true, |e| e.transaction_id() != transaction_id)
4443 {
4444 format_operation.take();
4445 }
4446 }
4447
4448 // Apply any language-specific formatting, and group the two formatting operations
4449 // in the buffer's undo history.
4450 if let Some(operation) = format_operation {
4451 match operation {
4452 FormatOperation::Lsp(edits) => {
4453 b.edit(edits, None, cx);
4454 }
4455 FormatOperation::External(diff) => {
4456 b.apply_diff(diff, cx);
4457 }
4458 FormatOperation::Prettier(diff) => {
4459 b.apply_diff(diff, cx);
4460 }
4461 }
4462
4463 if let Some(transaction_id) = whitespace_transaction_id {
4464 b.group_until_transaction(transaction_id);
4465 } else if let Some(transaction) = project_transaction.0.get(buffer) {
4466 b.group_until_transaction(transaction.id)
4467 }
4468 }
4469
4470 if let Some(transaction) = b.finalize_last_transaction().cloned() {
4471 if !push_to_history {
4472 b.forget_transaction(transaction.id);
4473 }
4474 project_transaction.0.insert(buffer.clone(), transaction);
4475 }
4476 })?;
4477 }
4478
4479 Ok(project_transaction)
4480 })
4481 } else {
4482 let remote_id = self.remote_id();
4483 let client = self.client.clone();
4484 cx.spawn(move |this, mut cx| async move {
4485 let mut project_transaction = ProjectTransaction::default();
4486 if let Some(project_id) = remote_id {
4487 let response = client
4488 .request(proto::FormatBuffers {
4489 project_id,
4490 trigger: trigger as i32,
4491 buffer_ids: buffers
4492 .iter()
4493 .map(|buffer| {
4494 buffer.update(&mut cx, |buffer, _| buffer.remote_id().into())
4495 })
4496 .collect::<Result<_>>()?,
4497 })
4498 .await?
4499 .transaction
4500 .ok_or_else(|| anyhow!("missing transaction"))?;
4501 project_transaction = this
4502 .update(&mut cx, |this, cx| {
4503 this.deserialize_project_transaction(response, push_to_history, cx)
4504 })?
4505 .await?;
4506 }
4507 Ok(project_transaction)
4508 })
4509 }
4510 }
4511
4512 async fn format_via_lsp(
4513 this: &WeakModel<Self>,
4514 buffer: &Model<Buffer>,
4515 abs_path: &Path,
4516 language_server: &Arc<LanguageServer>,
4517 tab_size: NonZeroU32,
4518 cx: &mut AsyncAppContext,
4519 ) -> Result<Vec<(Range<Anchor>, String)>> {
4520 let uri = lsp::Url::from_file_path(abs_path)
4521 .map_err(|_| anyhow!("failed to convert abs path to uri"))?;
4522 let text_document = lsp::TextDocumentIdentifier::new(uri);
4523 let capabilities = &language_server.capabilities();
4524
4525 let formatting_provider = capabilities.document_formatting_provider.as_ref();
4526 let range_formatting_provider = capabilities.document_range_formatting_provider.as_ref();
4527
4528 let lsp_edits = if matches!(formatting_provider, Some(p) if *p != OneOf::Left(false)) {
4529 language_server
4530 .request::<lsp::request::Formatting>(lsp::DocumentFormattingParams {
4531 text_document,
4532 options: lsp_command::lsp_formatting_options(tab_size.get()),
4533 work_done_progress_params: Default::default(),
4534 })
4535 .await?
4536 } else if matches!(range_formatting_provider, Some(p) if *p != OneOf::Left(false)) {
4537 let buffer_start = lsp::Position::new(0, 0);
4538 let buffer_end = buffer.update(cx, |b, _| point_to_lsp(b.max_point_utf16()))?;
4539
4540 language_server
4541 .request::<lsp::request::RangeFormatting>(lsp::DocumentRangeFormattingParams {
4542 text_document,
4543 range: lsp::Range::new(buffer_start, buffer_end),
4544 options: lsp_command::lsp_formatting_options(tab_size.get()),
4545 work_done_progress_params: Default::default(),
4546 })
4547 .await?
4548 } else {
4549 None
4550 };
4551
4552 if let Some(lsp_edits) = lsp_edits {
4553 this.update(cx, |this, cx| {
4554 this.edits_from_lsp(buffer, lsp_edits, language_server.server_id(), None, cx)
4555 })?
4556 .await
4557 } else {
4558 Ok(Vec::new())
4559 }
4560 }
4561
4562 async fn format_via_external_command(
4563 buffer: &Model<Buffer>,
4564 buffer_abs_path: &Path,
4565 command: &str,
4566 arguments: &[String],
4567 cx: &mut AsyncAppContext,
4568 ) -> Result<Option<Diff>> {
4569 let working_dir_path = buffer.update(cx, |buffer, cx| {
4570 let file = File::from_dyn(buffer.file())?;
4571 let worktree = file.worktree.read(cx).as_local()?;
4572 let mut worktree_path = worktree.abs_path().to_path_buf();
4573 if worktree.root_entry()?.is_file() {
4574 worktree_path.pop();
4575 }
4576 Some(worktree_path)
4577 })?;
4578
4579 if let Some(working_dir_path) = working_dir_path {
4580 let mut child =
4581 smol::process::Command::new(command)
4582 .args(arguments.iter().map(|arg| {
4583 arg.replace("{buffer_path}", &buffer_abs_path.to_string_lossy())
4584 }))
4585 .current_dir(&working_dir_path)
4586 .stdin(smol::process::Stdio::piped())
4587 .stdout(smol::process::Stdio::piped())
4588 .stderr(smol::process::Stdio::piped())
4589 .spawn()?;
4590 let stdin = child
4591 .stdin
4592 .as_mut()
4593 .ok_or_else(|| anyhow!("failed to acquire stdin"))?;
4594 let text = buffer.update(cx, |buffer, _| buffer.as_rope().clone())?;
4595 for chunk in text.chunks() {
4596 stdin.write_all(chunk.as_bytes()).await?;
4597 }
4598 stdin.flush().await?;
4599
4600 let output = child.output().await?;
4601 if !output.status.success() {
4602 return Err(anyhow!(
4603 "command failed with exit code {:?}:\nstdout: {}\nstderr: {}",
4604 output.status.code(),
4605 String::from_utf8_lossy(&output.stdout),
4606 String::from_utf8_lossy(&output.stderr),
4607 ));
4608 }
4609
4610 let stdout = String::from_utf8(output.stdout)?;
4611 Ok(Some(
4612 buffer
4613 .update(cx, |buffer, cx| buffer.diff(stdout, cx))?
4614 .await,
4615 ))
4616 } else {
4617 Ok(None)
4618 }
4619 }
4620
4621 #[inline(never)]
4622 fn definition_impl(
4623 &self,
4624 buffer: &Model<Buffer>,
4625 position: PointUtf16,
4626 cx: &mut ModelContext<Self>,
4627 ) -> Task<Result<Vec<LocationLink>>> {
4628 self.request_lsp(
4629 buffer.clone(),
4630 LanguageServerToQuery::Primary,
4631 GetDefinition { position },
4632 cx,
4633 )
4634 }
4635 pub fn definition<T: ToPointUtf16>(
4636 &self,
4637 buffer: &Model<Buffer>,
4638 position: T,
4639 cx: &mut ModelContext<Self>,
4640 ) -> Task<Result<Vec<LocationLink>>> {
4641 let position = position.to_point_utf16(buffer.read(cx));
4642 self.definition_impl(buffer, position, cx)
4643 }
4644
4645 fn type_definition_impl(
4646 &self,
4647 buffer: &Model<Buffer>,
4648 position: PointUtf16,
4649 cx: &mut ModelContext<Self>,
4650 ) -> Task<Result<Vec<LocationLink>>> {
4651 self.request_lsp(
4652 buffer.clone(),
4653 LanguageServerToQuery::Primary,
4654 GetTypeDefinition { position },
4655 cx,
4656 )
4657 }
4658
4659 pub fn type_definition<T: ToPointUtf16>(
4660 &self,
4661 buffer: &Model<Buffer>,
4662 position: T,
4663 cx: &mut ModelContext<Self>,
4664 ) -> Task<Result<Vec<LocationLink>>> {
4665 let position = position.to_point_utf16(buffer.read(cx));
4666 self.type_definition_impl(buffer, position, cx)
4667 }
4668
4669 fn implementation_impl(
4670 &self,
4671 buffer: &Model<Buffer>,
4672 position: PointUtf16,
4673 cx: &mut ModelContext<Self>,
4674 ) -> Task<Result<Vec<LocationLink>>> {
4675 self.request_lsp(
4676 buffer.clone(),
4677 LanguageServerToQuery::Primary,
4678 GetImplementation { position },
4679 cx,
4680 )
4681 }
4682
4683 pub fn implementation<T: ToPointUtf16>(
4684 &self,
4685 buffer: &Model<Buffer>,
4686 position: T,
4687 cx: &mut ModelContext<Self>,
4688 ) -> Task<Result<Vec<LocationLink>>> {
4689 let position = position.to_point_utf16(buffer.read(cx));
4690 self.implementation_impl(buffer, position, cx)
4691 }
4692
4693 fn references_impl(
4694 &self,
4695 buffer: &Model<Buffer>,
4696 position: PointUtf16,
4697 cx: &mut ModelContext<Self>,
4698 ) -> Task<Result<Vec<Location>>> {
4699 self.request_lsp(
4700 buffer.clone(),
4701 LanguageServerToQuery::Primary,
4702 GetReferences { position },
4703 cx,
4704 )
4705 }
4706 pub fn references<T: ToPointUtf16>(
4707 &self,
4708 buffer: &Model<Buffer>,
4709 position: T,
4710 cx: &mut ModelContext<Self>,
4711 ) -> Task<Result<Vec<Location>>> {
4712 let position = position.to_point_utf16(buffer.read(cx));
4713 self.references_impl(buffer, position, cx)
4714 }
4715
4716 fn document_highlights_impl(
4717 &self,
4718 buffer: &Model<Buffer>,
4719 position: PointUtf16,
4720 cx: &mut ModelContext<Self>,
4721 ) -> Task<Result<Vec<DocumentHighlight>>> {
4722 self.request_lsp(
4723 buffer.clone(),
4724 LanguageServerToQuery::Primary,
4725 GetDocumentHighlights { position },
4726 cx,
4727 )
4728 }
4729
4730 pub fn document_highlights<T: ToPointUtf16>(
4731 &self,
4732 buffer: &Model<Buffer>,
4733 position: T,
4734 cx: &mut ModelContext<Self>,
4735 ) -> Task<Result<Vec<DocumentHighlight>>> {
4736 let position = position.to_point_utf16(buffer.read(cx));
4737 self.document_highlights_impl(buffer, position, cx)
4738 }
4739
4740 pub fn symbols(&self, query: &str, cx: &mut ModelContext<Self>) -> Task<Result<Vec<Symbol>>> {
4741 if self.is_local() {
4742 let mut requests = Vec::new();
4743 for ((worktree_id, _), server_id) in self.language_server_ids.iter() {
4744 let worktree_id = *worktree_id;
4745 let worktree_handle = self.worktree_for_id(worktree_id, cx);
4746 let worktree = match worktree_handle.and_then(|tree| tree.read(cx).as_local()) {
4747 Some(worktree) => worktree,
4748 None => continue,
4749 };
4750 let worktree_abs_path = worktree.abs_path().clone();
4751
4752 let (adapter, language, server) = match self.language_servers.get(server_id) {
4753 Some(LanguageServerState::Running {
4754 adapter,
4755 language,
4756 server,
4757 ..
4758 }) => (adapter.clone(), language.clone(), server),
4759
4760 _ => continue,
4761 };
4762
4763 requests.push(
4764 server
4765 .request::<lsp::request::WorkspaceSymbolRequest>(
4766 lsp::WorkspaceSymbolParams {
4767 query: query.to_string(),
4768 ..Default::default()
4769 },
4770 )
4771 .log_err()
4772 .map(move |response| {
4773 let lsp_symbols = response.flatten().map(|symbol_response| match symbol_response {
4774 lsp::WorkspaceSymbolResponse::Flat(flat_responses) => {
4775 flat_responses.into_iter().map(|lsp_symbol| {
4776 (lsp_symbol.name, lsp_symbol.kind, lsp_symbol.location)
4777 }).collect::<Vec<_>>()
4778 }
4779 lsp::WorkspaceSymbolResponse::Nested(nested_responses) => {
4780 nested_responses.into_iter().filter_map(|lsp_symbol| {
4781 let location = match lsp_symbol.location {
4782 OneOf::Left(location) => location,
4783 OneOf::Right(_) => {
4784 error!("Unexpected: client capabilities forbid symbol resolutions in workspace.symbol.resolveSupport");
4785 return None
4786 }
4787 };
4788 Some((lsp_symbol.name, lsp_symbol.kind, location))
4789 }).collect::<Vec<_>>()
4790 }
4791 }).unwrap_or_default();
4792
4793 (
4794 adapter,
4795 language,
4796 worktree_id,
4797 worktree_abs_path,
4798 lsp_symbols,
4799 )
4800 }),
4801 );
4802 }
4803
4804 cx.spawn(move |this, mut cx| async move {
4805 let responses = futures::future::join_all(requests).await;
4806 let this = match this.upgrade() {
4807 Some(this) => this,
4808 None => return Ok(Vec::new()),
4809 };
4810
4811 let symbols = this.update(&mut cx, |this, cx| {
4812 let mut symbols = Vec::new();
4813 for (
4814 adapter,
4815 adapter_language,
4816 source_worktree_id,
4817 worktree_abs_path,
4818 lsp_symbols,
4819 ) in responses
4820 {
4821 symbols.extend(lsp_symbols.into_iter().filter_map(
4822 |(symbol_name, symbol_kind, symbol_location)| {
4823 let abs_path = symbol_location.uri.to_file_path().ok()?;
4824 let mut worktree_id = source_worktree_id;
4825 let path;
4826 if let Some((worktree, rel_path)) =
4827 this.find_local_worktree(&abs_path, cx)
4828 {
4829 worktree_id = worktree.read(cx).id();
4830 path = rel_path;
4831 } else {
4832 path = relativize_path(&worktree_abs_path, &abs_path);
4833 }
4834
4835 let project_path = ProjectPath {
4836 worktree_id,
4837 path: path.into(),
4838 };
4839 let signature = this.symbol_signature(&project_path);
4840 let adapter_language = adapter_language.clone();
4841 let language = this
4842 .languages
4843 .language_for_file(&project_path.path, None)
4844 .unwrap_or_else(move |_| adapter_language);
4845 let language_server_name = adapter.name.clone();
4846 Some(async move {
4847 let language = language.await;
4848 let label =
4849 language.label_for_symbol(&symbol_name, symbol_kind).await;
4850
4851 Symbol {
4852 language_server_name,
4853 source_worktree_id,
4854 path: project_path,
4855 label: label.unwrap_or_else(|| {
4856 CodeLabel::plain(symbol_name.clone(), None)
4857 }),
4858 kind: symbol_kind,
4859 name: symbol_name,
4860 range: range_from_lsp(symbol_location.range),
4861 signature,
4862 }
4863 })
4864 },
4865 ));
4866 }
4867
4868 symbols
4869 })?;
4870
4871 Ok(futures::future::join_all(symbols).await)
4872 })
4873 } else if let Some(project_id) = self.remote_id() {
4874 let request = self.client.request(proto::GetProjectSymbols {
4875 project_id,
4876 query: query.to_string(),
4877 });
4878 cx.spawn(move |this, mut cx| async move {
4879 let response = request.await?;
4880 let mut symbols = Vec::new();
4881 if let Some(this) = this.upgrade() {
4882 let new_symbols = this.update(&mut cx, |this, _| {
4883 response
4884 .symbols
4885 .into_iter()
4886 .map(|symbol| this.deserialize_symbol(symbol))
4887 .collect::<Vec<_>>()
4888 })?;
4889 symbols = futures::future::join_all(new_symbols)
4890 .await
4891 .into_iter()
4892 .filter_map(|symbol| symbol.log_err())
4893 .collect::<Vec<_>>();
4894 }
4895 Ok(symbols)
4896 })
4897 } else {
4898 Task::ready(Ok(Default::default()))
4899 }
4900 }
4901
4902 pub fn open_buffer_for_symbol(
4903 &mut self,
4904 symbol: &Symbol,
4905 cx: &mut ModelContext<Self>,
4906 ) -> Task<Result<Model<Buffer>>> {
4907 if self.is_local() {
4908 let language_server_id = if let Some(id) = self.language_server_ids.get(&(
4909 symbol.source_worktree_id,
4910 symbol.language_server_name.clone(),
4911 )) {
4912 *id
4913 } else {
4914 return Task::ready(Err(anyhow!(
4915 "language server for worktree and language not found"
4916 )));
4917 };
4918
4919 let worktree_abs_path = if let Some(worktree_abs_path) = self
4920 .worktree_for_id(symbol.path.worktree_id, cx)
4921 .and_then(|worktree| worktree.read(cx).as_local())
4922 .map(|local_worktree| local_worktree.abs_path())
4923 {
4924 worktree_abs_path
4925 } else {
4926 return Task::ready(Err(anyhow!("worktree not found for symbol")));
4927 };
4928
4929 let symbol_abs_path = resolve_path(worktree_abs_path, &symbol.path.path);
4930 let symbol_uri = if let Ok(uri) = lsp::Url::from_file_path(symbol_abs_path) {
4931 uri
4932 } else {
4933 return Task::ready(Err(anyhow!("invalid symbol path")));
4934 };
4935
4936 self.open_local_buffer_via_lsp(
4937 symbol_uri,
4938 language_server_id,
4939 symbol.language_server_name.clone(),
4940 cx,
4941 )
4942 } else if let Some(project_id) = self.remote_id() {
4943 let request = self.client.request(proto::OpenBufferForSymbol {
4944 project_id,
4945 symbol: Some(serialize_symbol(symbol)),
4946 });
4947 cx.spawn(move |this, mut cx| async move {
4948 let response = request.await?;
4949 let buffer_id = BufferId::new(response.buffer_id)?;
4950 this.update(&mut cx, |this, cx| {
4951 this.wait_for_remote_buffer(buffer_id, cx)
4952 })?
4953 .await
4954 })
4955 } else {
4956 Task::ready(Err(anyhow!("project does not have a remote id")))
4957 }
4958 }
4959
4960 fn hover_impl(
4961 &self,
4962 buffer: &Model<Buffer>,
4963 position: PointUtf16,
4964 cx: &mut ModelContext<Self>,
4965 ) -> Task<Result<Option<Hover>>> {
4966 self.request_lsp(
4967 buffer.clone(),
4968 LanguageServerToQuery::Primary,
4969 GetHover { position },
4970 cx,
4971 )
4972 }
4973 pub fn hover<T: ToPointUtf16>(
4974 &self,
4975 buffer: &Model<Buffer>,
4976 position: T,
4977 cx: &mut ModelContext<Self>,
4978 ) -> Task<Result<Option<Hover>>> {
4979 let position = position.to_point_utf16(buffer.read(cx));
4980 self.hover_impl(buffer, position, cx)
4981 }
4982
4983 #[inline(never)]
4984 fn completions_impl(
4985 &self,
4986 buffer: &Model<Buffer>,
4987 position: PointUtf16,
4988 cx: &mut ModelContext<Self>,
4989 ) -> Task<Result<Vec<Completion>>> {
4990 if self.is_local() {
4991 let snapshot = buffer.read(cx).snapshot();
4992 let offset = position.to_offset(&snapshot);
4993 let scope = snapshot.language_scope_at(offset);
4994
4995 let server_ids: Vec<_> = self
4996 .language_servers_for_buffer(buffer.read(cx), cx)
4997 .filter(|(_, server)| server.capabilities().completion_provider.is_some())
4998 .filter(|(adapter, _)| {
4999 scope
5000 .as_ref()
5001 .map(|scope| scope.language_allowed(&adapter.name))
5002 .unwrap_or(true)
5003 })
5004 .map(|(_, server)| server.server_id())
5005 .collect();
5006
5007 let buffer = buffer.clone();
5008 cx.spawn(move |this, mut cx| async move {
5009 let mut tasks = Vec::with_capacity(server_ids.len());
5010 this.update(&mut cx, |this, cx| {
5011 for server_id in server_ids {
5012 tasks.push(this.request_lsp(
5013 buffer.clone(),
5014 LanguageServerToQuery::Other(server_id),
5015 GetCompletions { position },
5016 cx,
5017 ));
5018 }
5019 })?;
5020
5021 let mut completions = Vec::new();
5022 for task in tasks {
5023 if let Ok(new_completions) = task.await {
5024 completions.extend_from_slice(&new_completions);
5025 }
5026 }
5027
5028 Ok(completions)
5029 })
5030 } else if let Some(project_id) = self.remote_id() {
5031 self.send_lsp_proto_request(buffer.clone(), project_id, GetCompletions { position }, cx)
5032 } else {
5033 Task::ready(Ok(Default::default()))
5034 }
5035 }
5036 pub fn completions<T: ToOffset + ToPointUtf16>(
5037 &self,
5038 buffer: &Model<Buffer>,
5039 position: T,
5040 cx: &mut ModelContext<Self>,
5041 ) -> Task<Result<Vec<Completion>>> {
5042 let position = position.to_point_utf16(buffer.read(cx));
5043 self.completions_impl(buffer, position, cx)
5044 }
5045
5046 pub fn resolve_completions(
5047 &self,
5048 completion_indices: Vec<usize>,
5049 completions: Arc<RwLock<Box<[Completion]>>>,
5050 cx: &mut ModelContext<Self>,
5051 ) -> Task<Result<bool>> {
5052 let client = self.client();
5053 let language_registry = self.languages().clone();
5054
5055 let is_remote = self.is_remote();
5056 let project_id = self.remote_id();
5057
5058 cx.spawn(move |this, mut cx| async move {
5059 let mut did_resolve = false;
5060 if is_remote {
5061 let project_id =
5062 project_id.ok_or_else(|| anyhow!("Remote project without remote_id"))?;
5063
5064 for completion_index in completion_indices {
5065 let completions_guard = completions.read();
5066 let completion = &completions_guard[completion_index];
5067 if completion.documentation.is_some() {
5068 continue;
5069 }
5070
5071 did_resolve = true;
5072 let server_id = completion.server_id;
5073 let completion = completion.lsp_completion.clone();
5074 drop(completions_guard);
5075
5076 Self::resolve_completion_documentation_remote(
5077 project_id,
5078 server_id,
5079 completions.clone(),
5080 completion_index,
5081 completion,
5082 client.clone(),
5083 language_registry.clone(),
5084 )
5085 .await;
5086 }
5087 } else {
5088 for completion_index in completion_indices {
5089 let completions_guard = completions.read();
5090 let completion = &completions_guard[completion_index];
5091 if completion.documentation.is_some() {
5092 continue;
5093 }
5094
5095 let server_id = completion.server_id;
5096 let completion = completion.lsp_completion.clone();
5097 drop(completions_guard);
5098
5099 let server = this
5100 .read_with(&mut cx, |project, _| {
5101 project.language_server_for_id(server_id)
5102 })
5103 .ok()
5104 .flatten();
5105 let Some(server) = server else {
5106 continue;
5107 };
5108
5109 did_resolve = true;
5110 Self::resolve_completion_documentation_local(
5111 server,
5112 completions.clone(),
5113 completion_index,
5114 completion,
5115 language_registry.clone(),
5116 )
5117 .await;
5118 }
5119 }
5120
5121 Ok(did_resolve)
5122 })
5123 }
5124
5125 async fn resolve_completion_documentation_local(
5126 server: Arc<lsp::LanguageServer>,
5127 completions: Arc<RwLock<Box<[Completion]>>>,
5128 completion_index: usize,
5129 completion: lsp::CompletionItem,
5130 language_registry: Arc<LanguageRegistry>,
5131 ) {
5132 let can_resolve = server
5133 .capabilities()
5134 .completion_provider
5135 .as_ref()
5136 .and_then(|options| options.resolve_provider)
5137 .unwrap_or(false);
5138 if !can_resolve {
5139 return;
5140 }
5141
5142 let request = server.request::<lsp::request::ResolveCompletionItem>(completion);
5143 let Some(completion_item) = request.await.log_err() else {
5144 return;
5145 };
5146
5147 if let Some(lsp_documentation) = completion_item.documentation {
5148 let documentation = language::prepare_completion_documentation(
5149 &lsp_documentation,
5150 &language_registry,
5151 None, // TODO: Try to reasonably work out which language the completion is for
5152 )
5153 .await;
5154
5155 let mut completions = completions.write();
5156 let completion = &mut completions[completion_index];
5157 completion.documentation = Some(documentation);
5158 } else {
5159 let mut completions = completions.write();
5160 let completion = &mut completions[completion_index];
5161 completion.documentation = Some(Documentation::Undocumented);
5162 }
5163 }
5164
5165 async fn resolve_completion_documentation_remote(
5166 project_id: u64,
5167 server_id: LanguageServerId,
5168 completions: Arc<RwLock<Box<[Completion]>>>,
5169 completion_index: usize,
5170 completion: lsp::CompletionItem,
5171 client: Arc<Client>,
5172 language_registry: Arc<LanguageRegistry>,
5173 ) {
5174 let request = proto::ResolveCompletionDocumentation {
5175 project_id,
5176 language_server_id: server_id.0 as u64,
5177 lsp_completion: serde_json::to_string(&completion).unwrap().into_bytes(),
5178 };
5179
5180 let Some(response) = client
5181 .request(request)
5182 .await
5183 .context("completion documentation resolve proto request")
5184 .log_err()
5185 else {
5186 return;
5187 };
5188
5189 if response.text.is_empty() {
5190 let mut completions = completions.write();
5191 let completion = &mut completions[completion_index];
5192 completion.documentation = Some(Documentation::Undocumented);
5193 }
5194
5195 let documentation = if response.is_markdown {
5196 Documentation::MultiLineMarkdown(
5197 markdown::parse_markdown(&response.text, &language_registry, None).await,
5198 )
5199 } else if response.text.lines().count() <= 1 {
5200 Documentation::SingleLine(response.text)
5201 } else {
5202 Documentation::MultiLinePlainText(response.text)
5203 };
5204
5205 let mut completions = completions.write();
5206 let completion = &mut completions[completion_index];
5207 completion.documentation = Some(documentation);
5208 }
5209
5210 pub fn apply_additional_edits_for_completion(
5211 &self,
5212 buffer_handle: Model<Buffer>,
5213 completion: Completion,
5214 push_to_history: bool,
5215 cx: &mut ModelContext<Self>,
5216 ) -> Task<Result<Option<Transaction>>> {
5217 let buffer = buffer_handle.read(cx);
5218 let buffer_id = buffer.remote_id();
5219
5220 if self.is_local() {
5221 let server_id = completion.server_id;
5222 let lang_server = match self.language_server_for_buffer(buffer, server_id, cx) {
5223 Some((_, server)) => server.clone(),
5224 _ => return Task::ready(Ok(Default::default())),
5225 };
5226
5227 cx.spawn(move |this, mut cx| async move {
5228 let can_resolve = lang_server
5229 .capabilities()
5230 .completion_provider
5231 .as_ref()
5232 .and_then(|options| options.resolve_provider)
5233 .unwrap_or(false);
5234 let additional_text_edits = if can_resolve {
5235 lang_server
5236 .request::<lsp::request::ResolveCompletionItem>(completion.lsp_completion)
5237 .await?
5238 .additional_text_edits
5239 } else {
5240 completion.lsp_completion.additional_text_edits
5241 };
5242 if let Some(edits) = additional_text_edits {
5243 let edits = this
5244 .update(&mut cx, |this, cx| {
5245 this.edits_from_lsp(
5246 &buffer_handle,
5247 edits,
5248 lang_server.server_id(),
5249 None,
5250 cx,
5251 )
5252 })?
5253 .await?;
5254
5255 buffer_handle.update(&mut cx, |buffer, cx| {
5256 buffer.finalize_last_transaction();
5257 buffer.start_transaction();
5258
5259 for (range, text) in edits {
5260 let primary = &completion.old_range;
5261 let start_within = primary.start.cmp(&range.start, buffer).is_le()
5262 && primary.end.cmp(&range.start, buffer).is_ge();
5263 let end_within = range.start.cmp(&primary.end, buffer).is_le()
5264 && range.end.cmp(&primary.end, buffer).is_ge();
5265
5266 //Skip additional edits which overlap with the primary completion edit
5267 //https://github.com/zed-industries/zed/pull/1871
5268 if !start_within && !end_within {
5269 buffer.edit([(range, text)], None, cx);
5270 }
5271 }
5272
5273 let transaction = if buffer.end_transaction(cx).is_some() {
5274 let transaction = buffer.finalize_last_transaction().unwrap().clone();
5275 if !push_to_history {
5276 buffer.forget_transaction(transaction.id);
5277 }
5278 Some(transaction)
5279 } else {
5280 None
5281 };
5282 Ok(transaction)
5283 })?
5284 } else {
5285 Ok(None)
5286 }
5287 })
5288 } else if let Some(project_id) = self.remote_id() {
5289 let client = self.client.clone();
5290 cx.spawn(move |_, mut cx| async move {
5291 let response = client
5292 .request(proto::ApplyCompletionAdditionalEdits {
5293 project_id,
5294 buffer_id: buffer_id.into(),
5295 completion: Some(language::proto::serialize_completion(&completion)),
5296 })
5297 .await?;
5298
5299 if let Some(transaction) = response.transaction {
5300 let transaction = language::proto::deserialize_transaction(transaction)?;
5301 buffer_handle
5302 .update(&mut cx, |buffer, _| {
5303 buffer.wait_for_edits(transaction.edit_ids.iter().copied())
5304 })?
5305 .await?;
5306 if push_to_history {
5307 buffer_handle.update(&mut cx, |buffer, _| {
5308 buffer.push_transaction(transaction.clone(), Instant::now());
5309 })?;
5310 }
5311 Ok(Some(transaction))
5312 } else {
5313 Ok(None)
5314 }
5315 })
5316 } else {
5317 Task::ready(Err(anyhow!("project does not have a remote id")))
5318 }
5319 }
5320
5321 fn code_actions_impl(
5322 &self,
5323 buffer_handle: &Model<Buffer>,
5324 range: Range<Anchor>,
5325 cx: &mut ModelContext<Self>,
5326 ) -> Task<Result<Vec<CodeAction>>> {
5327 self.request_lsp(
5328 buffer_handle.clone(),
5329 LanguageServerToQuery::Primary,
5330 GetCodeActions { range, kinds: None },
5331 cx,
5332 )
5333 }
5334
5335 pub fn code_actions<T: Clone + ToOffset>(
5336 &self,
5337 buffer_handle: &Model<Buffer>,
5338 range: Range<T>,
5339 cx: &mut ModelContext<Self>,
5340 ) -> Task<Result<Vec<CodeAction>>> {
5341 let buffer = buffer_handle.read(cx);
5342 let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
5343 self.code_actions_impl(buffer_handle, range, cx)
5344 }
5345
5346 pub fn apply_code_actions_on_save(
5347 &self,
5348 buffers: HashSet<Model<Buffer>>,
5349 cx: &mut ModelContext<Self>,
5350 ) -> Task<Result<ProjectTransaction>> {
5351 if !self.is_local() {
5352 return Task::ready(Ok(Default::default()));
5353 }
5354
5355 let buffers_with_adapters_and_servers = buffers
5356 .into_iter()
5357 .filter_map(|buffer_handle| {
5358 let buffer = buffer_handle.read(cx);
5359 self.primary_language_server_for_buffer(buffer, cx)
5360 .map(|(a, s)| (buffer_handle, a.clone(), s.clone()))
5361 })
5362 .collect::<Vec<_>>();
5363
5364 cx.spawn(move |this, mut cx| async move {
5365 for (buffer_handle, lsp_adapter, lang_server) in buffers_with_adapters_and_servers {
5366 let actions = this
5367 .update(&mut cx, |this, cx| {
5368 let buffer = buffer_handle.read(cx);
5369 let kinds: Vec<lsp::CodeActionKind> =
5370 language_settings(buffer.language(), buffer.file(), cx)
5371 .code_actions_on_format
5372 .iter()
5373 .flat_map(|(kind, enabled)| {
5374 if *enabled {
5375 Some(kind.clone().into())
5376 } else {
5377 None
5378 }
5379 })
5380 .collect();
5381 if kinds.is_empty() {
5382 return Task::ready(Ok(vec![]));
5383 }
5384
5385 this.request_lsp(
5386 buffer_handle.clone(),
5387 LanguageServerToQuery::Other(lang_server.server_id()),
5388 GetCodeActions {
5389 range: text::Anchor::MIN..text::Anchor::MAX,
5390 kinds: Some(kinds),
5391 },
5392 cx,
5393 )
5394 })?
5395 .await?;
5396
5397 for action in actions {
5398 if let Some(edit) = action.lsp_action.edit {
5399 if edit.changes.is_some() || edit.document_changes.is_some() {
5400 return Self::deserialize_workspace_edit(
5401 this.upgrade().ok_or_else(|| anyhow!("no app present"))?,
5402 edit,
5403 true,
5404 lsp_adapter.clone(),
5405 lang_server.clone(),
5406 &mut cx,
5407 )
5408 .await;
5409 }
5410 }
5411
5412 if let Some(command) = action.lsp_action.command {
5413 this.update(&mut cx, |this, _| {
5414 this.last_workspace_edits_by_language_server
5415 .remove(&lang_server.server_id());
5416 })?;
5417
5418 let result = lang_server
5419 .request::<lsp::request::ExecuteCommand>(lsp::ExecuteCommandParams {
5420 command: command.command,
5421 arguments: command.arguments.unwrap_or_default(),
5422 ..Default::default()
5423 })
5424 .await;
5425
5426 if let Err(err) = result {
5427 // TODO: LSP ERROR
5428 return Err(err);
5429 }
5430
5431 return Ok(this.update(&mut cx, |this, _| {
5432 this.last_workspace_edits_by_language_server
5433 .remove(&lang_server.server_id())
5434 .unwrap_or_default()
5435 })?);
5436 }
5437 }
5438 }
5439 Ok(ProjectTransaction::default())
5440 })
5441 }
5442
5443 pub fn apply_code_action(
5444 &self,
5445 buffer_handle: Model<Buffer>,
5446 mut action: CodeAction,
5447 push_to_history: bool,
5448 cx: &mut ModelContext<Self>,
5449 ) -> Task<Result<ProjectTransaction>> {
5450 if self.is_local() {
5451 let buffer = buffer_handle.read(cx);
5452 let (lsp_adapter, lang_server) = if let Some((adapter, server)) =
5453 self.language_server_for_buffer(buffer, action.server_id, cx)
5454 {
5455 (adapter.clone(), server.clone())
5456 } else {
5457 return Task::ready(Ok(Default::default()));
5458 };
5459 let range = action.range.to_point_utf16(buffer);
5460
5461 cx.spawn(move |this, mut cx| async move {
5462 if let Some(lsp_range) = action
5463 .lsp_action
5464 .data
5465 .as_mut()
5466 .and_then(|d| d.get_mut("codeActionParams"))
5467 .and_then(|d| d.get_mut("range"))
5468 {
5469 *lsp_range = serde_json::to_value(&range_to_lsp(range)).unwrap();
5470 action.lsp_action = lang_server
5471 .request::<lsp::request::CodeActionResolveRequest>(action.lsp_action)
5472 .await?;
5473 } else {
5474 let actions = this
5475 .update(&mut cx, |this, cx| {
5476 this.code_actions(&buffer_handle, action.range, cx)
5477 })?
5478 .await?;
5479 action.lsp_action = actions
5480 .into_iter()
5481 .find(|a| a.lsp_action.title == action.lsp_action.title)
5482 .ok_or_else(|| anyhow!("code action is outdated"))?
5483 .lsp_action;
5484 }
5485
5486 if let Some(edit) = action.lsp_action.edit {
5487 if edit.changes.is_some() || edit.document_changes.is_some() {
5488 return Self::deserialize_workspace_edit(
5489 this.upgrade().ok_or_else(|| anyhow!("no app present"))?,
5490 edit,
5491 push_to_history,
5492 lsp_adapter.clone(),
5493 lang_server.clone(),
5494 &mut cx,
5495 )
5496 .await;
5497 }
5498 }
5499
5500 if let Some(command) = action.lsp_action.command {
5501 this.update(&mut cx, |this, _| {
5502 this.last_workspace_edits_by_language_server
5503 .remove(&lang_server.server_id());
5504 })?;
5505
5506 let result = lang_server
5507 .request::<lsp::request::ExecuteCommand>(lsp::ExecuteCommandParams {
5508 command: command.command,
5509 arguments: command.arguments.unwrap_or_default(),
5510 ..Default::default()
5511 })
5512 .await;
5513
5514 if let Err(err) = result {
5515 // TODO: LSP ERROR
5516 return Err(err);
5517 }
5518
5519 return Ok(this.update(&mut cx, |this, _| {
5520 this.last_workspace_edits_by_language_server
5521 .remove(&lang_server.server_id())
5522 .unwrap_or_default()
5523 })?);
5524 }
5525
5526 Ok(ProjectTransaction::default())
5527 })
5528 } else if let Some(project_id) = self.remote_id() {
5529 let client = self.client.clone();
5530 let request = proto::ApplyCodeAction {
5531 project_id,
5532 buffer_id: buffer_handle.read(cx).remote_id().into(),
5533 action: Some(language::proto::serialize_code_action(&action)),
5534 };
5535 cx.spawn(move |this, mut cx| async move {
5536 let response = client
5537 .request(request)
5538 .await?
5539 .transaction
5540 .ok_or_else(|| anyhow!("missing transaction"))?;
5541 this.update(&mut cx, |this, cx| {
5542 this.deserialize_project_transaction(response, push_to_history, cx)
5543 })?
5544 .await
5545 })
5546 } else {
5547 Task::ready(Err(anyhow!("project does not have a remote id")))
5548 }
5549 }
5550
5551 fn apply_on_type_formatting(
5552 &self,
5553 buffer: Model<Buffer>,
5554 position: Anchor,
5555 trigger: String,
5556 cx: &mut ModelContext<Self>,
5557 ) -> Task<Result<Option<Transaction>>> {
5558 if self.is_local() {
5559 cx.spawn(move |this, mut cx| async move {
5560 // Do not allow multiple concurrent formatting requests for the
5561 // same buffer.
5562 this.update(&mut cx, |this, cx| {
5563 this.buffers_being_formatted
5564 .insert(buffer.read(cx).remote_id())
5565 })?;
5566
5567 let _cleanup = defer({
5568 let this = this.clone();
5569 let mut cx = cx.clone();
5570 let closure_buffer = buffer.clone();
5571 move || {
5572 this.update(&mut cx, |this, cx| {
5573 this.buffers_being_formatted
5574 .remove(&closure_buffer.read(cx).remote_id());
5575 })
5576 .ok();
5577 }
5578 });
5579
5580 buffer
5581 .update(&mut cx, |buffer, _| {
5582 buffer.wait_for_edits(Some(position.timestamp))
5583 })?
5584 .await?;
5585 this.update(&mut cx, |this, cx| {
5586 let position = position.to_point_utf16(buffer.read(cx));
5587 this.on_type_format(buffer, position, trigger, false, cx)
5588 })?
5589 .await
5590 })
5591 } else if let Some(project_id) = self.remote_id() {
5592 let client = self.client.clone();
5593 let request = proto::OnTypeFormatting {
5594 project_id,
5595 buffer_id: buffer.read(cx).remote_id().into(),
5596 position: Some(serialize_anchor(&position)),
5597 trigger,
5598 version: serialize_version(&buffer.read(cx).version()),
5599 };
5600 cx.spawn(move |_, _| async move {
5601 client
5602 .request(request)
5603 .await?
5604 .transaction
5605 .map(language::proto::deserialize_transaction)
5606 .transpose()
5607 })
5608 } else {
5609 Task::ready(Err(anyhow!("project does not have a remote id")))
5610 }
5611 }
5612
5613 async fn deserialize_edits(
5614 this: Model<Self>,
5615 buffer_to_edit: Model<Buffer>,
5616 edits: Vec<lsp::TextEdit>,
5617 push_to_history: bool,
5618 _: Arc<CachedLspAdapter>,
5619 language_server: Arc<LanguageServer>,
5620 cx: &mut AsyncAppContext,
5621 ) -> Result<Option<Transaction>> {
5622 let edits = this
5623 .update(cx, |this, cx| {
5624 this.edits_from_lsp(
5625 &buffer_to_edit,
5626 edits,
5627 language_server.server_id(),
5628 None,
5629 cx,
5630 )
5631 })?
5632 .await?;
5633
5634 let transaction = buffer_to_edit.update(cx, |buffer, cx| {
5635 buffer.finalize_last_transaction();
5636 buffer.start_transaction();
5637 for (range, text) in edits {
5638 buffer.edit([(range, text)], None, cx);
5639 }
5640
5641 if buffer.end_transaction(cx).is_some() {
5642 let transaction = buffer.finalize_last_transaction().unwrap().clone();
5643 if !push_to_history {
5644 buffer.forget_transaction(transaction.id);
5645 }
5646 Some(transaction)
5647 } else {
5648 None
5649 }
5650 })?;
5651
5652 Ok(transaction)
5653 }
5654
5655 async fn deserialize_workspace_edit(
5656 this: Model<Self>,
5657 edit: lsp::WorkspaceEdit,
5658 push_to_history: bool,
5659 lsp_adapter: Arc<CachedLspAdapter>,
5660 language_server: Arc<LanguageServer>,
5661 cx: &mut AsyncAppContext,
5662 ) -> Result<ProjectTransaction> {
5663 let fs = this.update(cx, |this, _| this.fs.clone())?;
5664 let mut operations = Vec::new();
5665 if let Some(document_changes) = edit.document_changes {
5666 match document_changes {
5667 lsp::DocumentChanges::Edits(edits) => {
5668 operations.extend(edits.into_iter().map(lsp::DocumentChangeOperation::Edit))
5669 }
5670 lsp::DocumentChanges::Operations(ops) => operations = ops,
5671 }
5672 } else if let Some(changes) = edit.changes {
5673 operations.extend(changes.into_iter().map(|(uri, edits)| {
5674 lsp::DocumentChangeOperation::Edit(lsp::TextDocumentEdit {
5675 text_document: lsp::OptionalVersionedTextDocumentIdentifier {
5676 uri,
5677 version: None,
5678 },
5679 edits: edits.into_iter().map(OneOf::Left).collect(),
5680 })
5681 }));
5682 }
5683
5684 let mut project_transaction = ProjectTransaction::default();
5685 for operation in operations {
5686 match operation {
5687 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Create(op)) => {
5688 let abs_path = op
5689 .uri
5690 .to_file_path()
5691 .map_err(|_| anyhow!("can't convert URI to path"))?;
5692
5693 if let Some(parent_path) = abs_path.parent() {
5694 fs.create_dir(parent_path).await?;
5695 }
5696 if abs_path.ends_with("/") {
5697 fs.create_dir(&abs_path).await?;
5698 } else {
5699 fs.create_file(
5700 &abs_path,
5701 op.options
5702 .map(|options| fs::CreateOptions {
5703 overwrite: options.overwrite.unwrap_or(false),
5704 ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
5705 })
5706 .unwrap_or_default(),
5707 )
5708 .await?;
5709 }
5710 }
5711
5712 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Rename(op)) => {
5713 let source_abs_path = op
5714 .old_uri
5715 .to_file_path()
5716 .map_err(|_| anyhow!("can't convert URI to path"))?;
5717 let target_abs_path = op
5718 .new_uri
5719 .to_file_path()
5720 .map_err(|_| anyhow!("can't convert URI to path"))?;
5721 fs.rename(
5722 &source_abs_path,
5723 &target_abs_path,
5724 op.options
5725 .map(|options| fs::RenameOptions {
5726 overwrite: options.overwrite.unwrap_or(false),
5727 ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
5728 })
5729 .unwrap_or_default(),
5730 )
5731 .await?;
5732 }
5733
5734 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Delete(op)) => {
5735 let abs_path = op
5736 .uri
5737 .to_file_path()
5738 .map_err(|_| anyhow!("can't convert URI to path"))?;
5739 let options = op
5740 .options
5741 .map(|options| fs::RemoveOptions {
5742 recursive: options.recursive.unwrap_or(false),
5743 ignore_if_not_exists: options.ignore_if_not_exists.unwrap_or(false),
5744 })
5745 .unwrap_or_default();
5746 if abs_path.ends_with("/") {
5747 fs.remove_dir(&abs_path, options).await?;
5748 } else {
5749 fs.remove_file(&abs_path, options).await?;
5750 }
5751 }
5752
5753 lsp::DocumentChangeOperation::Edit(op) => {
5754 let buffer_to_edit = this
5755 .update(cx, |this, cx| {
5756 this.open_local_buffer_via_lsp(
5757 op.text_document.uri,
5758 language_server.server_id(),
5759 lsp_adapter.name.clone(),
5760 cx,
5761 )
5762 })?
5763 .await?;
5764
5765 let edits = this
5766 .update(cx, |this, cx| {
5767 let edits = op.edits.into_iter().map(|edit| match edit {
5768 OneOf::Left(edit) => edit,
5769 OneOf::Right(edit) => edit.text_edit,
5770 });
5771 this.edits_from_lsp(
5772 &buffer_to_edit,
5773 edits,
5774 language_server.server_id(),
5775 op.text_document.version,
5776 cx,
5777 )
5778 })?
5779 .await?;
5780
5781 let transaction = buffer_to_edit.update(cx, |buffer, cx| {
5782 buffer.finalize_last_transaction();
5783 buffer.start_transaction();
5784 for (range, text) in edits {
5785 buffer.edit([(range, text)], None, cx);
5786 }
5787 let transaction = if buffer.end_transaction(cx).is_some() {
5788 let transaction = buffer.finalize_last_transaction().unwrap().clone();
5789 if !push_to_history {
5790 buffer.forget_transaction(transaction.id);
5791 }
5792 Some(transaction)
5793 } else {
5794 None
5795 };
5796
5797 transaction
5798 })?;
5799 if let Some(transaction) = transaction {
5800 project_transaction.0.insert(buffer_to_edit, transaction);
5801 }
5802 }
5803 }
5804 }
5805
5806 Ok(project_transaction)
5807 }
5808
5809 fn prepare_rename_impl(
5810 &self,
5811 buffer: Model<Buffer>,
5812 position: PointUtf16,
5813 cx: &mut ModelContext<Self>,
5814 ) -> Task<Result<Option<Range<Anchor>>>> {
5815 self.request_lsp(
5816 buffer,
5817 LanguageServerToQuery::Primary,
5818 PrepareRename { position },
5819 cx,
5820 )
5821 }
5822 pub fn prepare_rename<T: ToPointUtf16>(
5823 &self,
5824 buffer: Model<Buffer>,
5825 position: T,
5826 cx: &mut ModelContext<Self>,
5827 ) -> Task<Result<Option<Range<Anchor>>>> {
5828 let position = position.to_point_utf16(buffer.read(cx));
5829 self.prepare_rename_impl(buffer, position, cx)
5830 }
5831
5832 fn perform_rename_impl(
5833 &self,
5834 buffer: Model<Buffer>,
5835 position: PointUtf16,
5836 new_name: String,
5837 push_to_history: bool,
5838 cx: &mut ModelContext<Self>,
5839 ) -> Task<Result<ProjectTransaction>> {
5840 let position = position.to_point_utf16(buffer.read(cx));
5841 self.request_lsp(
5842 buffer,
5843 LanguageServerToQuery::Primary,
5844 PerformRename {
5845 position,
5846 new_name,
5847 push_to_history,
5848 },
5849 cx,
5850 )
5851 }
5852 pub fn perform_rename<T: ToPointUtf16>(
5853 &self,
5854 buffer: Model<Buffer>,
5855 position: T,
5856 new_name: String,
5857 push_to_history: bool,
5858 cx: &mut ModelContext<Self>,
5859 ) -> Task<Result<ProjectTransaction>> {
5860 let position = position.to_point_utf16(buffer.read(cx));
5861 self.perform_rename_impl(buffer, position, new_name, push_to_history, cx)
5862 }
5863
5864 pub fn on_type_format_impl(
5865 &self,
5866 buffer: Model<Buffer>,
5867 position: PointUtf16,
5868 trigger: String,
5869 push_to_history: bool,
5870 cx: &mut ModelContext<Self>,
5871 ) -> Task<Result<Option<Transaction>>> {
5872 let tab_size = buffer.update(cx, |buffer, cx| {
5873 language_settings(buffer.language_at(position).as_ref(), buffer.file(), cx).tab_size
5874 });
5875 self.request_lsp(
5876 buffer.clone(),
5877 LanguageServerToQuery::Primary,
5878 OnTypeFormatting {
5879 position,
5880 trigger,
5881 options: lsp_command::lsp_formatting_options(tab_size.get()).into(),
5882 push_to_history,
5883 },
5884 cx,
5885 )
5886 }
5887
5888 pub fn on_type_format<T: ToPointUtf16>(
5889 &self,
5890 buffer: Model<Buffer>,
5891 position: T,
5892 trigger: String,
5893 push_to_history: bool,
5894 cx: &mut ModelContext<Self>,
5895 ) -> Task<Result<Option<Transaction>>> {
5896 let position = position.to_point_utf16(buffer.read(cx));
5897 self.on_type_format_impl(buffer, position, trigger, push_to_history, cx)
5898 }
5899
5900 pub fn inlay_hints<T: ToOffset>(
5901 &self,
5902 buffer_handle: Model<Buffer>,
5903 range: Range<T>,
5904 cx: &mut ModelContext<Self>,
5905 ) -> Task<anyhow::Result<Vec<InlayHint>>> {
5906 let buffer = buffer_handle.read(cx);
5907 let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
5908 self.inlay_hints_impl(buffer_handle, range, cx)
5909 }
5910 fn inlay_hints_impl(
5911 &self,
5912 buffer_handle: Model<Buffer>,
5913 range: Range<Anchor>,
5914 cx: &mut ModelContext<Self>,
5915 ) -> Task<anyhow::Result<Vec<InlayHint>>> {
5916 let buffer = buffer_handle.read(cx);
5917 let range_start = range.start;
5918 let range_end = range.end;
5919 let buffer_id = buffer.remote_id().into();
5920 let buffer_version = buffer.version().clone();
5921 let lsp_request = InlayHints { range };
5922
5923 if self.is_local() {
5924 let lsp_request_task = self.request_lsp(
5925 buffer_handle.clone(),
5926 LanguageServerToQuery::Primary,
5927 lsp_request,
5928 cx,
5929 );
5930 cx.spawn(move |_, mut cx| async move {
5931 buffer_handle
5932 .update(&mut cx, |buffer, _| {
5933 buffer.wait_for_edits(vec![range_start.timestamp, range_end.timestamp])
5934 })?
5935 .await
5936 .context("waiting for inlay hint request range edits")?;
5937 lsp_request_task.await.context("inlay hints LSP request")
5938 })
5939 } else if let Some(project_id) = self.remote_id() {
5940 let client = self.client.clone();
5941 let request = proto::InlayHints {
5942 project_id,
5943 buffer_id,
5944 start: Some(serialize_anchor(&range_start)),
5945 end: Some(serialize_anchor(&range_end)),
5946 version: serialize_version(&buffer_version),
5947 };
5948 cx.spawn(move |project, cx| async move {
5949 let response = client
5950 .request(request)
5951 .await
5952 .context("inlay hints proto request")?;
5953 let hints_request_result = LspCommand::response_from_proto(
5954 lsp_request,
5955 response,
5956 project.upgrade().ok_or_else(|| anyhow!("No project"))?,
5957 buffer_handle.clone(),
5958 cx,
5959 )
5960 .await;
5961
5962 hints_request_result.context("inlay hints proto response conversion")
5963 })
5964 } else {
5965 Task::ready(Err(anyhow!("project does not have a remote id")))
5966 }
5967 }
5968
5969 pub fn resolve_inlay_hint(
5970 &self,
5971 hint: InlayHint,
5972 buffer_handle: Model<Buffer>,
5973 server_id: LanguageServerId,
5974 cx: &mut ModelContext<Self>,
5975 ) -> Task<anyhow::Result<InlayHint>> {
5976 if self.is_local() {
5977 let buffer = buffer_handle.read(cx);
5978 let (_, lang_server) = if let Some((adapter, server)) =
5979 self.language_server_for_buffer(buffer, server_id, cx)
5980 {
5981 (adapter.clone(), server.clone())
5982 } else {
5983 return Task::ready(Ok(hint));
5984 };
5985 if !InlayHints::can_resolve_inlays(lang_server.capabilities()) {
5986 return Task::ready(Ok(hint));
5987 }
5988
5989 let buffer_snapshot = buffer.snapshot();
5990 cx.spawn(move |_, mut cx| async move {
5991 let resolve_task = lang_server.request::<lsp::request::InlayHintResolveRequest>(
5992 InlayHints::project_to_lsp_hint(hint, &buffer_snapshot),
5993 );
5994 let resolved_hint = resolve_task
5995 .await
5996 .context("inlay hint resolve LSP request")?;
5997 let resolved_hint = InlayHints::lsp_to_project_hint(
5998 resolved_hint,
5999 &buffer_handle,
6000 server_id,
6001 ResolveState::Resolved,
6002 false,
6003 &mut cx,
6004 )
6005 .await?;
6006 Ok(resolved_hint)
6007 })
6008 } else if let Some(project_id) = self.remote_id() {
6009 let client = self.client.clone();
6010 let request = proto::ResolveInlayHint {
6011 project_id,
6012 buffer_id: buffer_handle.read(cx).remote_id().into(),
6013 language_server_id: server_id.0 as u64,
6014 hint: Some(InlayHints::project_to_proto_hint(hint.clone())),
6015 };
6016 cx.spawn(move |_, _| async move {
6017 let response = client
6018 .request(request)
6019 .await
6020 .context("inlay hints proto request")?;
6021 match response.hint {
6022 Some(resolved_hint) => InlayHints::proto_to_project_hint(resolved_hint)
6023 .context("inlay hints proto resolve response conversion"),
6024 None => Ok(hint),
6025 }
6026 })
6027 } else {
6028 Task::ready(Err(anyhow!("project does not have a remote id")))
6029 }
6030 }
6031
6032 #[allow(clippy::type_complexity)]
6033 pub fn search(
6034 &self,
6035 query: SearchQuery,
6036 cx: &mut ModelContext<Self>,
6037 ) -> Receiver<(Model<Buffer>, Vec<Range<Anchor>>)> {
6038 if self.is_local() {
6039 self.search_local(query, cx)
6040 } else if let Some(project_id) = self.remote_id() {
6041 let (tx, rx) = smol::channel::unbounded();
6042 let request = self.client.request(query.to_proto(project_id));
6043 cx.spawn(move |this, mut cx| async move {
6044 let response = request.await?;
6045 let mut result = HashMap::default();
6046 for location in response.locations {
6047 let buffer_id = BufferId::new(location.buffer_id)?;
6048 let target_buffer = this
6049 .update(&mut cx, |this, cx| {
6050 this.wait_for_remote_buffer(buffer_id, cx)
6051 })?
6052 .await?;
6053 let start = location
6054 .start
6055 .and_then(deserialize_anchor)
6056 .ok_or_else(|| anyhow!("missing target start"))?;
6057 let end = location
6058 .end
6059 .and_then(deserialize_anchor)
6060 .ok_or_else(|| anyhow!("missing target end"))?;
6061 result
6062 .entry(target_buffer)
6063 .or_insert(Vec::new())
6064 .push(start..end)
6065 }
6066 for (buffer, ranges) in result {
6067 let _ = tx.send((buffer, ranges)).await;
6068 }
6069 Result::<(), anyhow::Error>::Ok(())
6070 })
6071 .detach_and_log_err(cx);
6072 rx
6073 } else {
6074 unimplemented!();
6075 }
6076 }
6077
6078 pub fn search_local(
6079 &self,
6080 query: SearchQuery,
6081 cx: &mut ModelContext<Self>,
6082 ) -> Receiver<(Model<Buffer>, Vec<Range<Anchor>>)> {
6083 // Local search is split into several phases.
6084 // TL;DR is that we do 2 passes; initial pass to pick files which contain at least one match
6085 // and the second phase that finds positions of all the matches found in the candidate files.
6086 // The Receiver obtained from this function returns matches sorted by buffer path. Files without a buffer path are reported first.
6087 //
6088 // It gets a bit hairy though, because we must account for files that do not have a persistent representation
6089 // on FS. Namely, if you have an untitled buffer or unsaved changes in a buffer, we want to scan that too.
6090 //
6091 // 1. We initialize a queue of match candidates and feed all opened buffers into it (== unsaved files / untitled buffers).
6092 // 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
6093 // of FS version for that file altogether - after all, what we have in memory is more up-to-date than what's in FS.
6094 // 2. At this point, we have a list of all potentially matching buffers/files.
6095 // We sort that list by buffer path - this list is retained for later use.
6096 // We ensure that all buffers are now opened and available in project.
6097 // 3. We run a scan over all the candidate buffers on multiple background threads.
6098 // We cannot assume that there will even be a match - while at least one match
6099 // is guaranteed for files obtained from FS, the buffers we got from memory (unsaved files/unnamed buffers) might not have a match at all.
6100 // There is also an auxiliary background thread responsible for result gathering.
6101 // 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),
6102 // it keeps it around. It reports matches in sorted order, though it accepts them in unsorted order as well.
6103 // 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
6104 // entry - which might already be available thanks to out-of-order processing.
6105 //
6106 // We could also report matches fully out-of-order, without maintaining a sorted list of matching paths.
6107 // 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.
6108 // 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
6109 // in face of constantly updating list of sorted matches.
6110 // Meanwhile, this implementation offers index stability, since the matches are already reported in a sorted order.
6111 let snapshots = self
6112 .visible_worktrees(cx)
6113 .filter_map(|tree| {
6114 let tree = tree.read(cx).as_local()?;
6115 Some(tree.snapshot())
6116 })
6117 .collect::<Vec<_>>();
6118
6119 let background = cx.background_executor().clone();
6120 let path_count: usize = snapshots
6121 .iter()
6122 .map(|s| {
6123 if query.include_ignored() {
6124 s.file_count()
6125 } else {
6126 s.visible_file_count()
6127 }
6128 })
6129 .sum();
6130 if path_count == 0 {
6131 let (_, rx) = smol::channel::bounded(1024);
6132 return rx;
6133 }
6134 let workers = background.num_cpus().min(path_count);
6135 let (matching_paths_tx, matching_paths_rx) = smol::channel::bounded(1024);
6136 let mut unnamed_files = vec![];
6137 let opened_buffers = self
6138 .opened_buffers
6139 .iter()
6140 .filter_map(|(_, b)| {
6141 let buffer = b.upgrade()?;
6142 let (is_ignored, snapshot) = buffer.update(cx, |buffer, cx| {
6143 let is_ignored = buffer
6144 .project_path(cx)
6145 .and_then(|path| self.entry_for_path(&path, cx))
6146 .map_or(false, |entry| entry.is_ignored);
6147 (is_ignored, buffer.snapshot())
6148 });
6149 if is_ignored && !query.include_ignored() {
6150 return None;
6151 } else if let Some(path) = snapshot.file().map(|file| file.path()) {
6152 Some((path.clone(), (buffer, snapshot)))
6153 } else {
6154 unnamed_files.push(buffer);
6155 None
6156 }
6157 })
6158 .collect();
6159 cx.background_executor()
6160 .spawn(Self::background_search(
6161 unnamed_files,
6162 opened_buffers,
6163 cx.background_executor().clone(),
6164 self.fs.clone(),
6165 workers,
6166 query.clone(),
6167 path_count,
6168 snapshots,
6169 matching_paths_tx,
6170 ))
6171 .detach();
6172
6173 let (buffers, buffers_rx) = Self::sort_candidates_and_open_buffers(matching_paths_rx, cx);
6174 let background = cx.background_executor().clone();
6175 let (result_tx, result_rx) = smol::channel::bounded(1024);
6176 cx.background_executor()
6177 .spawn(async move {
6178 let Ok(buffers) = buffers.await else {
6179 return;
6180 };
6181
6182 let buffers_len = buffers.len();
6183 if buffers_len == 0 {
6184 return;
6185 }
6186 let query = &query;
6187 let (finished_tx, mut finished_rx) = smol::channel::unbounded();
6188 background
6189 .scoped(|scope| {
6190 #[derive(Clone)]
6191 struct FinishedStatus {
6192 entry: Option<(Model<Buffer>, Vec<Range<Anchor>>)>,
6193 buffer_index: SearchMatchCandidateIndex,
6194 }
6195
6196 for _ in 0..workers {
6197 let finished_tx = finished_tx.clone();
6198 let mut buffers_rx = buffers_rx.clone();
6199 scope.spawn(async move {
6200 while let Some((entry, buffer_index)) = buffers_rx.next().await {
6201 let buffer_matches = if let Some((_, snapshot)) = entry.as_ref()
6202 {
6203 if query.file_matches(
6204 snapshot.file().map(|file| file.path().as_ref()),
6205 ) {
6206 query
6207 .search(snapshot, None)
6208 .await
6209 .iter()
6210 .map(|range| {
6211 snapshot.anchor_before(range.start)
6212 ..snapshot.anchor_after(range.end)
6213 })
6214 .collect()
6215 } else {
6216 Vec::new()
6217 }
6218 } else {
6219 Vec::new()
6220 };
6221
6222 let status = if !buffer_matches.is_empty() {
6223 let entry = if let Some((buffer, _)) = entry.as_ref() {
6224 Some((buffer.clone(), buffer_matches))
6225 } else {
6226 None
6227 };
6228 FinishedStatus {
6229 entry,
6230 buffer_index,
6231 }
6232 } else {
6233 FinishedStatus {
6234 entry: None,
6235 buffer_index,
6236 }
6237 };
6238 if finished_tx.send(status).await.is_err() {
6239 break;
6240 }
6241 }
6242 });
6243 }
6244 // Report sorted matches
6245 scope.spawn(async move {
6246 let mut current_index = 0;
6247 let mut scratch = vec![None; buffers_len];
6248 while let Some(status) = finished_rx.next().await {
6249 debug_assert!(
6250 scratch[status.buffer_index].is_none(),
6251 "Got match status of position {} twice",
6252 status.buffer_index
6253 );
6254 let index = status.buffer_index;
6255 scratch[index] = Some(status);
6256 while current_index < buffers_len {
6257 let Some(current_entry) = scratch[current_index].take() else {
6258 // We intentionally **do not** increment `current_index` here. When next element arrives
6259 // from `finished_rx`, we will inspect the same position again, hoping for it to be Some(_)
6260 // this time.
6261 break;
6262 };
6263 if let Some(entry) = current_entry.entry {
6264 result_tx.send(entry).await.log_err();
6265 }
6266 current_index += 1;
6267 }
6268 if current_index == buffers_len {
6269 break;
6270 }
6271 }
6272 });
6273 })
6274 .await;
6275 })
6276 .detach();
6277 result_rx
6278 }
6279
6280 /// Pick paths that might potentially contain a match of a given search query.
6281 async fn background_search(
6282 unnamed_buffers: Vec<Model<Buffer>>,
6283 opened_buffers: HashMap<Arc<Path>, (Model<Buffer>, BufferSnapshot)>,
6284 executor: BackgroundExecutor,
6285 fs: Arc<dyn Fs>,
6286 workers: usize,
6287 query: SearchQuery,
6288 path_count: usize,
6289 snapshots: Vec<LocalSnapshot>,
6290 matching_paths_tx: Sender<SearchMatchCandidate>,
6291 ) {
6292 let fs = &fs;
6293 let query = &query;
6294 let matching_paths_tx = &matching_paths_tx;
6295 let snapshots = &snapshots;
6296 let paths_per_worker = (path_count + workers - 1) / workers;
6297 for buffer in unnamed_buffers {
6298 matching_paths_tx
6299 .send(SearchMatchCandidate::OpenBuffer {
6300 buffer: buffer.clone(),
6301 path: None,
6302 })
6303 .await
6304 .log_err();
6305 }
6306 for (path, (buffer, _)) in opened_buffers.iter() {
6307 matching_paths_tx
6308 .send(SearchMatchCandidate::OpenBuffer {
6309 buffer: buffer.clone(),
6310 path: Some(path.clone()),
6311 })
6312 .await
6313 .log_err();
6314 }
6315 executor
6316 .scoped(|scope| {
6317 let max_concurrent_workers = Arc::new(Semaphore::new(workers));
6318
6319 for worker_ix in 0..workers {
6320 let worker_start_ix = worker_ix * paths_per_worker;
6321 let worker_end_ix = worker_start_ix + paths_per_worker;
6322 let unnamed_buffers = opened_buffers.clone();
6323 let limiter = Arc::clone(&max_concurrent_workers);
6324 scope.spawn(async move {
6325 let _guard = limiter.acquire().await;
6326 let mut snapshot_start_ix = 0;
6327 let mut abs_path = PathBuf::new();
6328 for snapshot in snapshots {
6329 let snapshot_end_ix = snapshot_start_ix
6330 + if query.include_ignored() {
6331 snapshot.file_count()
6332 } else {
6333 snapshot.visible_file_count()
6334 };
6335 if worker_end_ix <= snapshot_start_ix {
6336 break;
6337 } else if worker_start_ix > snapshot_end_ix {
6338 snapshot_start_ix = snapshot_end_ix;
6339 continue;
6340 } else {
6341 let start_in_snapshot =
6342 worker_start_ix.saturating_sub(snapshot_start_ix);
6343 let end_in_snapshot =
6344 cmp::min(worker_end_ix, snapshot_end_ix) - snapshot_start_ix;
6345
6346 for entry in snapshot
6347 .files(query.include_ignored(), start_in_snapshot)
6348 .take(end_in_snapshot - start_in_snapshot)
6349 {
6350 if matching_paths_tx.is_closed() {
6351 break;
6352 }
6353 if unnamed_buffers.contains_key(&entry.path) {
6354 continue;
6355 }
6356 let matches = if query.file_matches(Some(&entry.path)) {
6357 abs_path.clear();
6358 abs_path.push(&snapshot.abs_path());
6359 abs_path.push(&entry.path);
6360 if let Some(file) = fs.open_sync(&abs_path).await.log_err()
6361 {
6362 query.detect(file).unwrap_or(false)
6363 } else {
6364 false
6365 }
6366 } else {
6367 false
6368 };
6369
6370 if matches {
6371 let project_path = SearchMatchCandidate::Path {
6372 worktree_id: snapshot.id(),
6373 path: entry.path.clone(),
6374 is_ignored: entry.is_ignored,
6375 };
6376 if matching_paths_tx.send(project_path).await.is_err() {
6377 break;
6378 }
6379 }
6380 }
6381
6382 snapshot_start_ix = snapshot_end_ix;
6383 }
6384 }
6385 });
6386 }
6387
6388 if query.include_ignored() {
6389 for snapshot in snapshots {
6390 for ignored_entry in snapshot
6391 .entries(query.include_ignored())
6392 .filter(|e| e.is_ignored)
6393 {
6394 let limiter = Arc::clone(&max_concurrent_workers);
6395 scope.spawn(async move {
6396 let _guard = limiter.acquire().await;
6397 let mut ignored_paths_to_process =
6398 VecDeque::from([snapshot.abs_path().join(&ignored_entry.path)]);
6399 while let Some(ignored_abs_path) =
6400 ignored_paths_to_process.pop_front()
6401 {
6402 if let Some(fs_metadata) = fs
6403 .metadata(&ignored_abs_path)
6404 .await
6405 .with_context(|| {
6406 format!("fetching fs metadata for {ignored_abs_path:?}")
6407 })
6408 .log_err()
6409 .flatten()
6410 {
6411 if fs_metadata.is_dir {
6412 if let Some(mut subfiles) = fs
6413 .read_dir(&ignored_abs_path)
6414 .await
6415 .with_context(|| {
6416 format!(
6417 "listing ignored path {ignored_abs_path:?}"
6418 )
6419 })
6420 .log_err()
6421 {
6422 while let Some(subfile) = subfiles.next().await {
6423 if let Some(subfile) = subfile.log_err() {
6424 ignored_paths_to_process.push_back(subfile);
6425 }
6426 }
6427 }
6428 } else if !fs_metadata.is_symlink {
6429 if !query.file_matches(Some(&ignored_abs_path))
6430 || snapshot.is_path_excluded(
6431 ignored_entry.path.to_path_buf(),
6432 )
6433 {
6434 continue;
6435 }
6436 let matches = if let Some(file) = fs
6437 .open_sync(&ignored_abs_path)
6438 .await
6439 .with_context(|| {
6440 format!(
6441 "Opening ignored path {ignored_abs_path:?}"
6442 )
6443 })
6444 .log_err()
6445 {
6446 query.detect(file).unwrap_or(false)
6447 } else {
6448 false
6449 };
6450 if matches {
6451 let project_path = SearchMatchCandidate::Path {
6452 worktree_id: snapshot.id(),
6453 path: Arc::from(
6454 ignored_abs_path
6455 .strip_prefix(snapshot.abs_path())
6456 .expect(
6457 "scanning worktree-related files",
6458 ),
6459 ),
6460 is_ignored: true,
6461 };
6462 if matching_paths_tx
6463 .send(project_path)
6464 .await
6465 .is_err()
6466 {
6467 return;
6468 }
6469 }
6470 }
6471 }
6472 }
6473 });
6474 }
6475 }
6476 }
6477 })
6478 .await;
6479 }
6480
6481 pub fn request_lsp<R: LspCommand>(
6482 &self,
6483 buffer_handle: Model<Buffer>,
6484 server: LanguageServerToQuery,
6485 request: R,
6486 cx: &mut ModelContext<Self>,
6487 ) -> Task<Result<R::Response>>
6488 where
6489 <R::LspRequest as lsp::request::Request>::Result: Send,
6490 <R::LspRequest as lsp::request::Request>::Params: Send,
6491 {
6492 let buffer = buffer_handle.read(cx);
6493 if self.is_local() {
6494 let language_server = match server {
6495 LanguageServerToQuery::Primary => {
6496 match self.primary_language_server_for_buffer(buffer, cx) {
6497 Some((_, server)) => Some(Arc::clone(server)),
6498 None => return Task::ready(Ok(Default::default())),
6499 }
6500 }
6501 LanguageServerToQuery::Other(id) => self
6502 .language_server_for_buffer(buffer, id, cx)
6503 .map(|(_, server)| Arc::clone(server)),
6504 };
6505 let file = File::from_dyn(buffer.file()).and_then(File::as_local);
6506 if let (Some(file), Some(language_server)) = (file, language_server) {
6507 let lsp_params = request.to_lsp(&file.abs_path(cx), buffer, &language_server, cx);
6508 return cx.spawn(move |this, cx| async move {
6509 if !request.check_capabilities(language_server.capabilities()) {
6510 return Ok(Default::default());
6511 }
6512
6513 let result = language_server.request::<R::LspRequest>(lsp_params).await;
6514 let response = match result {
6515 Ok(response) => response,
6516
6517 Err(err) => {
6518 log::warn!(
6519 "Generic lsp request to {} failed: {}",
6520 language_server.name(),
6521 err
6522 );
6523 return Err(err);
6524 }
6525 };
6526
6527 request
6528 .response_from_lsp(
6529 response,
6530 this.upgrade().ok_or_else(|| anyhow!("no app context"))?,
6531 buffer_handle,
6532 language_server.server_id(),
6533 cx,
6534 )
6535 .await
6536 });
6537 }
6538 } else if let Some(project_id) = self.remote_id() {
6539 return self.send_lsp_proto_request(buffer_handle, project_id, request, cx);
6540 }
6541
6542 Task::ready(Ok(Default::default()))
6543 }
6544
6545 fn send_lsp_proto_request<R: LspCommand>(
6546 &self,
6547 buffer: Model<Buffer>,
6548 project_id: u64,
6549 request: R,
6550 cx: &mut ModelContext<'_, Project>,
6551 ) -> Task<anyhow::Result<<R as LspCommand>::Response>> {
6552 let rpc = self.client.clone();
6553 let message = request.to_proto(project_id, buffer.read(cx));
6554 cx.spawn(move |this, mut cx| async move {
6555 // Ensure the project is still alive by the time the task
6556 // is scheduled.
6557 this.upgrade().context("project dropped")?;
6558 let response = rpc.request(message).await?;
6559 let this = this.upgrade().context("project dropped")?;
6560 if this.update(&mut cx, |this, _| this.is_disconnected())? {
6561 Err(anyhow!("disconnected before completing request"))
6562 } else {
6563 request
6564 .response_from_proto(response, this, buffer, cx)
6565 .await
6566 }
6567 })
6568 }
6569
6570 fn sort_candidates_and_open_buffers(
6571 mut matching_paths_rx: Receiver<SearchMatchCandidate>,
6572 cx: &mut ModelContext<Self>,
6573 ) -> (
6574 futures::channel::oneshot::Receiver<Vec<SearchMatchCandidate>>,
6575 Receiver<(
6576 Option<(Model<Buffer>, BufferSnapshot)>,
6577 SearchMatchCandidateIndex,
6578 )>,
6579 ) {
6580 let (buffers_tx, buffers_rx) = smol::channel::bounded(1024);
6581 let (sorted_buffers_tx, sorted_buffers_rx) = futures::channel::oneshot::channel();
6582 cx.spawn(move |this, cx| async move {
6583 let mut buffers = Vec::new();
6584 let mut ignored_buffers = Vec::new();
6585 while let Some(entry) = matching_paths_rx.next().await {
6586 if matches!(
6587 entry,
6588 SearchMatchCandidate::Path {
6589 is_ignored: true,
6590 ..
6591 }
6592 ) {
6593 ignored_buffers.push(entry);
6594 } else {
6595 buffers.push(entry);
6596 }
6597 }
6598 buffers.sort_by_key(|candidate| candidate.path());
6599 ignored_buffers.sort_by_key(|candidate| candidate.path());
6600 buffers.extend(ignored_buffers);
6601 let matching_paths = buffers.clone();
6602 let _ = sorted_buffers_tx.send(buffers);
6603 for (index, candidate) in matching_paths.into_iter().enumerate() {
6604 if buffers_tx.is_closed() {
6605 break;
6606 }
6607 let this = this.clone();
6608 let buffers_tx = buffers_tx.clone();
6609 cx.spawn(move |mut cx| async move {
6610 let buffer = match candidate {
6611 SearchMatchCandidate::OpenBuffer { buffer, .. } => Some(buffer),
6612 SearchMatchCandidate::Path {
6613 worktree_id, path, ..
6614 } => this
6615 .update(&mut cx, |this, cx| {
6616 this.open_buffer((worktree_id, path), cx)
6617 })?
6618 .await
6619 .log_err(),
6620 };
6621 if let Some(buffer) = buffer {
6622 let snapshot = buffer.update(&mut cx, |buffer, _| buffer.snapshot())?;
6623 buffers_tx
6624 .send((Some((buffer, snapshot)), index))
6625 .await
6626 .log_err();
6627 } else {
6628 buffers_tx.send((None, index)).await.log_err();
6629 }
6630
6631 Ok::<_, anyhow::Error>(())
6632 })
6633 .detach();
6634 }
6635 })
6636 .detach();
6637 (sorted_buffers_rx, buffers_rx)
6638 }
6639
6640 pub fn find_or_create_local_worktree(
6641 &mut self,
6642 abs_path: impl AsRef<Path>,
6643 visible: bool,
6644 cx: &mut ModelContext<Self>,
6645 ) -> Task<Result<(Model<Worktree>, PathBuf)>> {
6646 let abs_path = abs_path.as_ref();
6647 if let Some((tree, relative_path)) = self.find_local_worktree(abs_path, cx) {
6648 Task::ready(Ok((tree, relative_path)))
6649 } else {
6650 let worktree = self.create_local_worktree(abs_path, visible, cx);
6651 cx.background_executor()
6652 .spawn(async move { Ok((worktree.await?, PathBuf::new())) })
6653 }
6654 }
6655
6656 pub fn find_local_worktree(
6657 &self,
6658 abs_path: &Path,
6659 cx: &AppContext,
6660 ) -> Option<(Model<Worktree>, PathBuf)> {
6661 for tree in &self.worktrees {
6662 if let Some(tree) = tree.upgrade() {
6663 if let Some(relative_path) = tree
6664 .read(cx)
6665 .as_local()
6666 .and_then(|t| abs_path.strip_prefix(t.abs_path()).ok())
6667 {
6668 return Some((tree.clone(), relative_path.into()));
6669 }
6670 }
6671 }
6672 None
6673 }
6674
6675 pub fn is_shared(&self) -> bool {
6676 match &self.client_state {
6677 ProjectClientState::Shared { .. } => true,
6678 ProjectClientState::Local | ProjectClientState::Remote { .. } => false,
6679 }
6680 }
6681
6682 fn create_local_worktree(
6683 &mut self,
6684 abs_path: impl AsRef<Path>,
6685 visible: bool,
6686 cx: &mut ModelContext<Self>,
6687 ) -> Task<Result<Model<Worktree>>> {
6688 let fs = self.fs.clone();
6689 let client = self.client.clone();
6690 let next_entry_id = self.next_entry_id.clone();
6691 let path: Arc<Path> = abs_path.as_ref().into();
6692 let task = self
6693 .loading_local_worktrees
6694 .entry(path.clone())
6695 .or_insert_with(|| {
6696 cx.spawn(move |project, mut cx| {
6697 async move {
6698 let worktree = Worktree::local(
6699 client.clone(),
6700 path.clone(),
6701 visible,
6702 fs,
6703 next_entry_id,
6704 &mut cx,
6705 )
6706 .await;
6707
6708 project.update(&mut cx, |project, _| {
6709 project.loading_local_worktrees.remove(&path);
6710 })?;
6711
6712 let worktree = worktree?;
6713 project
6714 .update(&mut cx, |project, cx| project.add_worktree(&worktree, cx))?;
6715 Ok(worktree)
6716 }
6717 .map_err(Arc::new)
6718 })
6719 .shared()
6720 })
6721 .clone();
6722 cx.background_executor().spawn(async move {
6723 match task.await {
6724 Ok(worktree) => Ok(worktree),
6725 Err(err) => Err(anyhow!("{}", err)),
6726 }
6727 })
6728 }
6729
6730 pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut ModelContext<Self>) {
6731 let mut servers_to_remove = HashMap::default();
6732 let mut servers_to_preserve = HashSet::default();
6733 for ((worktree_id, server_name), &server_id) in &self.language_server_ids {
6734 if worktree_id == &id_to_remove {
6735 servers_to_remove.insert(server_id, server_name.clone());
6736 } else {
6737 servers_to_preserve.insert(server_id);
6738 }
6739 }
6740 servers_to_remove.retain(|server_id, _| !servers_to_preserve.contains(server_id));
6741 for (server_id_to_remove, server_name) in servers_to_remove {
6742 self.language_server_ids
6743 .remove(&(id_to_remove, server_name));
6744 self.language_server_statuses.remove(&server_id_to_remove);
6745 self.last_workspace_edits_by_language_server
6746 .remove(&server_id_to_remove);
6747 self.language_servers.remove(&server_id_to_remove);
6748 cx.emit(Event::LanguageServerRemoved(server_id_to_remove));
6749 }
6750
6751 let mut prettier_instances_to_clean = FuturesUnordered::new();
6752 if let Some(prettier_paths) = self.prettiers_per_worktree.remove(&id_to_remove) {
6753 for path in prettier_paths.iter().flatten() {
6754 if let Some(prettier_instance) = self.prettier_instances.remove(path) {
6755 prettier_instances_to_clean.push(async move {
6756 prettier_instance
6757 .server()
6758 .await
6759 .map(|server| server.server_id())
6760 });
6761 }
6762 }
6763 }
6764 cx.spawn(|project, mut cx| async move {
6765 while let Some(prettier_server_id) = prettier_instances_to_clean.next().await {
6766 if let Some(prettier_server_id) = prettier_server_id {
6767 project
6768 .update(&mut cx, |project, cx| {
6769 project
6770 .supplementary_language_servers
6771 .remove(&prettier_server_id);
6772 cx.emit(Event::LanguageServerRemoved(prettier_server_id));
6773 })
6774 .ok();
6775 }
6776 }
6777 })
6778 .detach();
6779
6780 self.worktrees.retain(|worktree| {
6781 if let Some(worktree) = worktree.upgrade() {
6782 let id = worktree.read(cx).id();
6783 if id == id_to_remove {
6784 cx.emit(Event::WorktreeRemoved(id));
6785 false
6786 } else {
6787 true
6788 }
6789 } else {
6790 false
6791 }
6792 });
6793 self.metadata_changed(cx);
6794 }
6795
6796 fn add_worktree(&mut self, worktree: &Model<Worktree>, cx: &mut ModelContext<Self>) {
6797 cx.observe(worktree, |_, _, cx| cx.notify()).detach();
6798 if worktree.read(cx).is_local() {
6799 cx.subscribe(worktree, |this, worktree, event, cx| match event {
6800 worktree::Event::UpdatedEntries(changes) => {
6801 this.update_local_worktree_buffers(&worktree, changes, cx);
6802 this.update_local_worktree_language_servers(&worktree, changes, cx);
6803 this.update_local_worktree_settings(&worktree, changes, cx);
6804 this.update_prettier_settings(&worktree, changes, cx);
6805 cx.emit(Event::WorktreeUpdatedEntries(
6806 worktree.read(cx).id(),
6807 changes.clone(),
6808 ));
6809 }
6810 worktree::Event::UpdatedGitRepositories(updated_repos) => {
6811 this.update_local_worktree_buffers_git_repos(worktree, updated_repos, cx)
6812 }
6813 })
6814 .detach();
6815 }
6816
6817 let push_strong_handle = {
6818 let worktree = worktree.read(cx);
6819 self.is_shared() || worktree.is_visible() || worktree.is_remote()
6820 };
6821 if push_strong_handle {
6822 self.worktrees
6823 .push(WorktreeHandle::Strong(worktree.clone()));
6824 } else {
6825 self.worktrees
6826 .push(WorktreeHandle::Weak(worktree.downgrade()));
6827 }
6828
6829 let handle_id = worktree.entity_id();
6830 cx.observe_release(worktree, move |this, worktree, cx| {
6831 let _ = this.remove_worktree(worktree.id(), cx);
6832 cx.update_global::<SettingsStore, _>(|store, cx| {
6833 store
6834 .clear_local_settings(handle_id.as_u64() as usize, cx)
6835 .log_err()
6836 });
6837 })
6838 .detach();
6839
6840 cx.emit(Event::WorktreeAdded);
6841 self.metadata_changed(cx);
6842 }
6843
6844 fn update_local_worktree_buffers(
6845 &mut self,
6846 worktree_handle: &Model<Worktree>,
6847 changes: &[(Arc<Path>, ProjectEntryId, PathChange)],
6848 cx: &mut ModelContext<Self>,
6849 ) {
6850 let snapshot = worktree_handle.read(cx).snapshot();
6851
6852 let mut renamed_buffers = Vec::new();
6853 for (path, entry_id, _) in changes {
6854 let worktree_id = worktree_handle.read(cx).id();
6855 let project_path = ProjectPath {
6856 worktree_id,
6857 path: path.clone(),
6858 };
6859
6860 let buffer_id = match self.local_buffer_ids_by_entry_id.get(entry_id) {
6861 Some(&buffer_id) => buffer_id,
6862 None => match self.local_buffer_ids_by_path.get(&project_path) {
6863 Some(&buffer_id) => buffer_id,
6864 None => {
6865 continue;
6866 }
6867 },
6868 };
6869
6870 let open_buffer = self.opened_buffers.get(&buffer_id);
6871 let buffer = if let Some(buffer) = open_buffer.and_then(|buffer| buffer.upgrade()) {
6872 buffer
6873 } else {
6874 self.opened_buffers.remove(&buffer_id);
6875 self.local_buffer_ids_by_path.remove(&project_path);
6876 self.local_buffer_ids_by_entry_id.remove(entry_id);
6877 continue;
6878 };
6879
6880 buffer.update(cx, |buffer, cx| {
6881 if let Some(old_file) = File::from_dyn(buffer.file()) {
6882 if old_file.worktree != *worktree_handle {
6883 return;
6884 }
6885
6886 let new_file = if let Some(entry) = old_file
6887 .entry_id
6888 .and_then(|entry_id| snapshot.entry_for_id(entry_id))
6889 {
6890 File {
6891 is_local: true,
6892 entry_id: Some(entry.id),
6893 mtime: entry.mtime,
6894 path: entry.path.clone(),
6895 worktree: worktree_handle.clone(),
6896 is_deleted: false,
6897 is_private: entry.is_private,
6898 }
6899 } else if let Some(entry) = snapshot.entry_for_path(old_file.path().as_ref()) {
6900 File {
6901 is_local: true,
6902 entry_id: Some(entry.id),
6903 mtime: entry.mtime,
6904 path: entry.path.clone(),
6905 worktree: worktree_handle.clone(),
6906 is_deleted: false,
6907 is_private: entry.is_private,
6908 }
6909 } else {
6910 File {
6911 is_local: true,
6912 entry_id: old_file.entry_id,
6913 path: old_file.path().clone(),
6914 mtime: old_file.mtime(),
6915 worktree: worktree_handle.clone(),
6916 is_deleted: true,
6917 is_private: old_file.is_private,
6918 }
6919 };
6920
6921 let old_path = old_file.abs_path(cx);
6922 if new_file.abs_path(cx) != old_path {
6923 renamed_buffers.push((cx.handle(), old_file.clone()));
6924 self.local_buffer_ids_by_path.remove(&project_path);
6925 self.local_buffer_ids_by_path.insert(
6926 ProjectPath {
6927 worktree_id,
6928 path: path.clone(),
6929 },
6930 buffer_id,
6931 );
6932 }
6933
6934 if new_file.entry_id != Some(*entry_id) {
6935 self.local_buffer_ids_by_entry_id.remove(entry_id);
6936 if let Some(entry_id) = new_file.entry_id {
6937 self.local_buffer_ids_by_entry_id
6938 .insert(entry_id, buffer_id);
6939 }
6940 }
6941
6942 if new_file != *old_file {
6943 if let Some(project_id) = self.remote_id() {
6944 self.client
6945 .send(proto::UpdateBufferFile {
6946 project_id,
6947 buffer_id: buffer_id.into(),
6948 file: Some(new_file.to_proto()),
6949 })
6950 .log_err();
6951 }
6952
6953 buffer.file_updated(Arc::new(new_file), cx);
6954 }
6955 }
6956 });
6957 }
6958
6959 for (buffer, old_file) in renamed_buffers {
6960 self.unregister_buffer_from_language_servers(&buffer, &old_file, cx);
6961 self.detect_language_for_buffer(&buffer, cx);
6962 self.register_buffer_with_language_servers(&buffer, cx);
6963 }
6964 }
6965
6966 fn update_local_worktree_language_servers(
6967 &mut self,
6968 worktree_handle: &Model<Worktree>,
6969 changes: &[(Arc<Path>, ProjectEntryId, PathChange)],
6970 cx: &mut ModelContext<Self>,
6971 ) {
6972 if changes.is_empty() {
6973 return;
6974 }
6975
6976 let worktree_id = worktree_handle.read(cx).id();
6977 let mut language_server_ids = self
6978 .language_server_ids
6979 .iter()
6980 .filter_map(|((server_worktree_id, _), server_id)| {
6981 (*server_worktree_id == worktree_id).then_some(*server_id)
6982 })
6983 .collect::<Vec<_>>();
6984 language_server_ids.sort();
6985 language_server_ids.dedup();
6986
6987 let abs_path = worktree_handle.read(cx).abs_path();
6988 for server_id in &language_server_ids {
6989 if let Some(LanguageServerState::Running {
6990 server,
6991 watched_paths,
6992 ..
6993 }) = self.language_servers.get(server_id)
6994 {
6995 if let Some(watched_paths) = watched_paths.get(&worktree_id) {
6996 let params = lsp::DidChangeWatchedFilesParams {
6997 changes: changes
6998 .iter()
6999 .filter_map(|(path, _, change)| {
7000 if !watched_paths.is_match(&path) {
7001 return None;
7002 }
7003 let typ = match change {
7004 PathChange::Loaded => return None,
7005 PathChange::Added => lsp::FileChangeType::CREATED,
7006 PathChange::Removed => lsp::FileChangeType::DELETED,
7007 PathChange::Updated => lsp::FileChangeType::CHANGED,
7008 PathChange::AddedOrUpdated => lsp::FileChangeType::CHANGED,
7009 };
7010 Some(lsp::FileEvent {
7011 uri: lsp::Url::from_file_path(abs_path.join(path)).unwrap(),
7012 typ,
7013 })
7014 })
7015 .collect(),
7016 };
7017
7018 if !params.changes.is_empty() {
7019 server
7020 .notify::<lsp::notification::DidChangeWatchedFiles>(params)
7021 .log_err();
7022 }
7023 }
7024 }
7025 }
7026 }
7027
7028 fn update_local_worktree_buffers_git_repos(
7029 &mut self,
7030 worktree_handle: Model<Worktree>,
7031 changed_repos: &UpdatedGitRepositoriesSet,
7032 cx: &mut ModelContext<Self>,
7033 ) {
7034 debug_assert!(worktree_handle.read(cx).is_local());
7035
7036 // Identify the loading buffers whose containing repository that has changed.
7037 let future_buffers = self
7038 .loading_buffers_by_path
7039 .iter()
7040 .filter_map(|(project_path, receiver)| {
7041 if project_path.worktree_id != worktree_handle.read(cx).id() {
7042 return None;
7043 }
7044 let path = &project_path.path;
7045 changed_repos
7046 .iter()
7047 .find(|(work_dir, _)| path.starts_with(work_dir))?;
7048 let receiver = receiver.clone();
7049 let path = path.clone();
7050 Some(async move {
7051 wait_for_loading_buffer(receiver)
7052 .await
7053 .ok()
7054 .map(|buffer| (buffer, path))
7055 })
7056 })
7057 .collect::<FuturesUnordered<_>>();
7058
7059 // Identify the current buffers whose containing repository has changed.
7060 let current_buffers = self
7061 .opened_buffers
7062 .values()
7063 .filter_map(|buffer| {
7064 let buffer = buffer.upgrade()?;
7065 let file = File::from_dyn(buffer.read(cx).file())?;
7066 if file.worktree != worktree_handle {
7067 return None;
7068 }
7069 let path = file.path();
7070 changed_repos
7071 .iter()
7072 .find(|(work_dir, _)| path.starts_with(work_dir))?;
7073 Some((buffer, path.clone()))
7074 })
7075 .collect::<Vec<_>>();
7076
7077 if future_buffers.len() + current_buffers.len() == 0 {
7078 return;
7079 }
7080
7081 let remote_id = self.remote_id();
7082 let client = self.client.clone();
7083 cx.spawn(move |_, mut cx| async move {
7084 // Wait for all of the buffers to load.
7085 let future_buffers = future_buffers.collect::<Vec<_>>().await;
7086
7087 // Reload the diff base for every buffer whose containing git repository has changed.
7088 let snapshot =
7089 worktree_handle.update(&mut cx, |tree, _| tree.as_local().unwrap().snapshot())?;
7090 let diff_bases_by_buffer = cx
7091 .background_executor()
7092 .spawn(async move {
7093 future_buffers
7094 .into_iter()
7095 .filter_map(|e| e)
7096 .chain(current_buffers)
7097 .filter_map(|(buffer, path)| {
7098 let (work_directory, repo) =
7099 snapshot.repository_and_work_directory_for_path(&path)?;
7100 let repo = snapshot.get_local_repo(&repo)?;
7101 let relative_path = path.strip_prefix(&work_directory).ok()?;
7102 let base_text = repo.repo_ptr.lock().load_index_text(relative_path);
7103 Some((buffer, base_text))
7104 })
7105 .collect::<Vec<_>>()
7106 })
7107 .await;
7108
7109 // Assign the new diff bases on all of the buffers.
7110 for (buffer, diff_base) in diff_bases_by_buffer {
7111 let buffer_id = buffer.update(&mut cx, |buffer, cx| {
7112 buffer.set_diff_base(diff_base.clone(), cx);
7113 buffer.remote_id().into()
7114 })?;
7115 if let Some(project_id) = remote_id {
7116 client
7117 .send(proto::UpdateDiffBase {
7118 project_id,
7119 buffer_id,
7120 diff_base,
7121 })
7122 .log_err();
7123 }
7124 }
7125
7126 anyhow::Ok(())
7127 })
7128 .detach();
7129 }
7130
7131 fn update_local_worktree_settings(
7132 &mut self,
7133 worktree: &Model<Worktree>,
7134 changes: &UpdatedEntriesSet,
7135 cx: &mut ModelContext<Self>,
7136 ) {
7137 let project_id = self.remote_id();
7138 let worktree_id = worktree.entity_id();
7139 let worktree = worktree.read(cx).as_local().unwrap();
7140 let remote_worktree_id = worktree.id();
7141
7142 let mut settings_contents = Vec::new();
7143 for (path, _, change) in changes.iter() {
7144 if path.ends_with(&*LOCAL_SETTINGS_RELATIVE_PATH) {
7145 let settings_dir = Arc::from(
7146 path.ancestors()
7147 .nth(LOCAL_SETTINGS_RELATIVE_PATH.components().count())
7148 .unwrap(),
7149 );
7150 let fs = self.fs.clone();
7151 let removed = *change == PathChange::Removed;
7152 let abs_path = worktree.absolutize(path);
7153 settings_contents.push(async move {
7154 (
7155 settings_dir,
7156 if removed {
7157 None
7158 } else {
7159 Some(async move { fs.load(&abs_path?).await }.await)
7160 },
7161 )
7162 });
7163 }
7164 }
7165
7166 if settings_contents.is_empty() {
7167 return;
7168 }
7169
7170 let client = self.client.clone();
7171 cx.spawn(move |_, cx| async move {
7172 let settings_contents: Vec<(Arc<Path>, _)> =
7173 futures::future::join_all(settings_contents).await;
7174 cx.update(|cx| {
7175 cx.update_global::<SettingsStore, _>(|store, cx| {
7176 for (directory, file_content) in settings_contents {
7177 let file_content = file_content.and_then(|content| content.log_err());
7178 store
7179 .set_local_settings(
7180 worktree_id.as_u64() as usize,
7181 directory.clone(),
7182 file_content.as_ref().map(String::as_str),
7183 cx,
7184 )
7185 .log_err();
7186 if let Some(remote_id) = project_id {
7187 client
7188 .send(proto::UpdateWorktreeSettings {
7189 project_id: remote_id,
7190 worktree_id: remote_worktree_id.to_proto(),
7191 path: directory.to_string_lossy().into_owned(),
7192 content: file_content,
7193 })
7194 .log_err();
7195 }
7196 }
7197 });
7198 })
7199 .ok();
7200 })
7201 .detach();
7202 }
7203
7204 pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
7205 let new_active_entry = entry.and_then(|project_path| {
7206 let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
7207 let entry = worktree.read(cx).entry_for_path(project_path.path)?;
7208 Some(entry.id)
7209 });
7210 if new_active_entry != self.active_entry {
7211 self.active_entry = new_active_entry;
7212 cx.emit(Event::ActiveEntryChanged(new_active_entry));
7213 }
7214 }
7215
7216 pub fn language_servers_running_disk_based_diagnostics(
7217 &self,
7218 ) -> impl Iterator<Item = LanguageServerId> + '_ {
7219 self.language_server_statuses
7220 .iter()
7221 .filter_map(|(id, status)| {
7222 if status.has_pending_diagnostic_updates {
7223 Some(*id)
7224 } else {
7225 None
7226 }
7227 })
7228 }
7229
7230 pub fn diagnostic_summary(&self, include_ignored: bool, cx: &AppContext) -> DiagnosticSummary {
7231 let mut summary = DiagnosticSummary::default();
7232 for (_, _, path_summary) in
7233 self.diagnostic_summaries(include_ignored, cx)
7234 .filter(|(path, _, _)| {
7235 let worktree = self.entry_for_path(path, cx).map(|entry| entry.is_ignored);
7236 include_ignored || worktree == Some(false)
7237 })
7238 {
7239 summary.error_count += path_summary.error_count;
7240 summary.warning_count += path_summary.warning_count;
7241 }
7242 summary
7243 }
7244
7245 pub fn diagnostic_summaries<'a>(
7246 &'a self,
7247 include_ignored: bool,
7248 cx: &'a AppContext,
7249 ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
7250 self.visible_worktrees(cx)
7251 .flat_map(move |worktree| {
7252 let worktree = worktree.read(cx);
7253 let worktree_id = worktree.id();
7254 worktree
7255 .diagnostic_summaries()
7256 .map(move |(path, server_id, summary)| {
7257 (ProjectPath { worktree_id, path }, server_id, summary)
7258 })
7259 })
7260 .filter(move |(path, _, _)| {
7261 let worktree = self.entry_for_path(path, cx).map(|entry| entry.is_ignored);
7262 include_ignored || worktree == Some(false)
7263 })
7264 }
7265
7266 pub fn disk_based_diagnostics_started(
7267 &mut self,
7268 language_server_id: LanguageServerId,
7269 cx: &mut ModelContext<Self>,
7270 ) {
7271 cx.emit(Event::DiskBasedDiagnosticsStarted { language_server_id });
7272 }
7273
7274 pub fn disk_based_diagnostics_finished(
7275 &mut self,
7276 language_server_id: LanguageServerId,
7277 cx: &mut ModelContext<Self>,
7278 ) {
7279 cx.emit(Event::DiskBasedDiagnosticsFinished { language_server_id });
7280 }
7281
7282 pub fn active_entry(&self) -> Option<ProjectEntryId> {
7283 self.active_entry
7284 }
7285
7286 pub fn entry_for_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<Entry> {
7287 self.worktree_for_id(path.worktree_id, cx)?
7288 .read(cx)
7289 .entry_for_path(&path.path)
7290 .cloned()
7291 }
7292
7293 pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &AppContext) -> Option<ProjectPath> {
7294 let worktree = self.worktree_for_entry(entry_id, cx)?;
7295 let worktree = worktree.read(cx);
7296 let worktree_id = worktree.id();
7297 let path = worktree.entry_for_id(entry_id)?.path.clone();
7298 Some(ProjectPath { worktree_id, path })
7299 }
7300
7301 pub fn absolute_path(&self, project_path: &ProjectPath, cx: &AppContext) -> Option<PathBuf> {
7302 let workspace_root = self
7303 .worktree_for_id(project_path.worktree_id, cx)?
7304 .read(cx)
7305 .abs_path();
7306 let project_path = project_path.path.as_ref();
7307
7308 Some(if project_path == Path::new("") {
7309 workspace_root.to_path_buf()
7310 } else {
7311 workspace_root.join(project_path)
7312 })
7313 }
7314
7315 // RPC message handlers
7316
7317 async fn handle_unshare_project(
7318 this: Model<Self>,
7319 _: TypedEnvelope<proto::UnshareProject>,
7320 _: Arc<Client>,
7321 mut cx: AsyncAppContext,
7322 ) -> Result<()> {
7323 this.update(&mut cx, |this, cx| {
7324 if this.is_local() {
7325 this.unshare(cx)?;
7326 } else {
7327 this.disconnected_from_host(cx);
7328 }
7329 Ok(())
7330 })?
7331 }
7332
7333 async fn handle_add_collaborator(
7334 this: Model<Self>,
7335 mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
7336 _: Arc<Client>,
7337 mut cx: AsyncAppContext,
7338 ) -> Result<()> {
7339 let collaborator = envelope
7340 .payload
7341 .collaborator
7342 .take()
7343 .ok_or_else(|| anyhow!("empty collaborator"))?;
7344
7345 let collaborator = Collaborator::from_proto(collaborator)?;
7346 this.update(&mut cx, |this, cx| {
7347 this.shared_buffers.remove(&collaborator.peer_id);
7348 cx.emit(Event::CollaboratorJoined(collaborator.peer_id));
7349 this.collaborators
7350 .insert(collaborator.peer_id, collaborator);
7351 cx.notify();
7352 })?;
7353
7354 Ok(())
7355 }
7356
7357 async fn handle_update_project_collaborator(
7358 this: Model<Self>,
7359 envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
7360 _: Arc<Client>,
7361 mut cx: AsyncAppContext,
7362 ) -> Result<()> {
7363 let old_peer_id = envelope
7364 .payload
7365 .old_peer_id
7366 .ok_or_else(|| anyhow!("missing old peer id"))?;
7367 let new_peer_id = envelope
7368 .payload
7369 .new_peer_id
7370 .ok_or_else(|| anyhow!("missing new peer id"))?;
7371 this.update(&mut cx, |this, cx| {
7372 let collaborator = this
7373 .collaborators
7374 .remove(&old_peer_id)
7375 .ok_or_else(|| anyhow!("received UpdateProjectCollaborator for unknown peer"))?;
7376 let is_host = collaborator.replica_id == 0;
7377 this.collaborators.insert(new_peer_id, collaborator);
7378
7379 let buffers = this.shared_buffers.remove(&old_peer_id);
7380 log::info!(
7381 "peer {} became {}. moving buffers {:?}",
7382 old_peer_id,
7383 new_peer_id,
7384 &buffers
7385 );
7386 if let Some(buffers) = buffers {
7387 this.shared_buffers.insert(new_peer_id, buffers);
7388 }
7389
7390 if is_host {
7391 this.opened_buffers
7392 .retain(|_, buffer| !matches!(buffer, OpenBuffer::Operations(_)));
7393 this.buffer_ordered_messages_tx
7394 .unbounded_send(BufferOrderedMessage::Resync)
7395 .unwrap();
7396 }
7397
7398 cx.emit(Event::CollaboratorUpdated {
7399 old_peer_id,
7400 new_peer_id,
7401 });
7402 cx.notify();
7403 Ok(())
7404 })?
7405 }
7406
7407 async fn handle_remove_collaborator(
7408 this: Model<Self>,
7409 envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
7410 _: Arc<Client>,
7411 mut cx: AsyncAppContext,
7412 ) -> Result<()> {
7413 this.update(&mut cx, |this, cx| {
7414 let peer_id = envelope
7415 .payload
7416 .peer_id
7417 .ok_or_else(|| anyhow!("invalid peer id"))?;
7418 let replica_id = this
7419 .collaborators
7420 .remove(&peer_id)
7421 .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
7422 .replica_id;
7423 for buffer in this.opened_buffers.values() {
7424 if let Some(buffer) = buffer.upgrade() {
7425 buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
7426 }
7427 }
7428 this.shared_buffers.remove(&peer_id);
7429
7430 cx.emit(Event::CollaboratorLeft(peer_id));
7431 cx.notify();
7432 Ok(())
7433 })?
7434 }
7435
7436 async fn handle_update_project(
7437 this: Model<Self>,
7438 envelope: TypedEnvelope<proto::UpdateProject>,
7439 _: Arc<Client>,
7440 mut cx: AsyncAppContext,
7441 ) -> Result<()> {
7442 this.update(&mut cx, |this, cx| {
7443 // Don't handle messages that were sent before the response to us joining the project
7444 if envelope.message_id > this.join_project_response_message_id {
7445 this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
7446 }
7447 Ok(())
7448 })?
7449 }
7450
7451 async fn handle_update_worktree(
7452 this: Model<Self>,
7453 envelope: TypedEnvelope<proto::UpdateWorktree>,
7454 _: Arc<Client>,
7455 mut cx: AsyncAppContext,
7456 ) -> Result<()> {
7457 this.update(&mut cx, |this, cx| {
7458 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
7459 if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
7460 worktree.update(cx, |worktree, _| {
7461 let worktree = worktree.as_remote_mut().unwrap();
7462 worktree.update_from_remote(envelope.payload);
7463 });
7464 }
7465 Ok(())
7466 })?
7467 }
7468
7469 async fn handle_update_worktree_settings(
7470 this: Model<Self>,
7471 envelope: TypedEnvelope<proto::UpdateWorktreeSettings>,
7472 _: Arc<Client>,
7473 mut cx: AsyncAppContext,
7474 ) -> Result<()> {
7475 this.update(&mut cx, |this, cx| {
7476 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
7477 if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
7478 cx.update_global::<SettingsStore, _>(|store, cx| {
7479 store
7480 .set_local_settings(
7481 worktree.entity_id().as_u64() as usize,
7482 PathBuf::from(&envelope.payload.path).into(),
7483 envelope.payload.content.as_ref().map(String::as_str),
7484 cx,
7485 )
7486 .log_err();
7487 });
7488 }
7489 Ok(())
7490 })?
7491 }
7492
7493 async fn handle_create_project_entry(
7494 this: Model<Self>,
7495 envelope: TypedEnvelope<proto::CreateProjectEntry>,
7496 _: Arc<Client>,
7497 mut cx: AsyncAppContext,
7498 ) -> Result<proto::ProjectEntryResponse> {
7499 let worktree = this.update(&mut cx, |this, cx| {
7500 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
7501 this.worktree_for_id(worktree_id, cx)
7502 .ok_or_else(|| anyhow!("worktree not found"))
7503 })??;
7504 let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())?;
7505 let entry = worktree
7506 .update(&mut cx, |worktree, cx| {
7507 let worktree = worktree.as_local_mut().unwrap();
7508 let path = PathBuf::from(envelope.payload.path);
7509 worktree.create_entry(path, envelope.payload.is_directory, 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_rename_project_entry(
7519 this: Model<Self>,
7520 envelope: TypedEnvelope<proto::RenameProjectEntry>,
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 .rename_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_copy_project_entry(
7546 this: Model<Self>,
7547 envelope: TypedEnvelope<proto::CopyProjectEntry>,
7548 _: Arc<Client>,
7549 mut cx: AsyncAppContext,
7550 ) -> Result<proto::ProjectEntryResponse> {
7551 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
7552 let worktree = this.update(&mut cx, |this, cx| {
7553 this.worktree_for_entry(entry_id, cx)
7554 .ok_or_else(|| anyhow!("worktree not found"))
7555 })??;
7556 let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())?;
7557 let entry = worktree
7558 .update(&mut cx, |worktree, cx| {
7559 let new_path = PathBuf::from(envelope.payload.new_path);
7560 worktree
7561 .as_local_mut()
7562 .unwrap()
7563 .copy_entry(entry_id, new_path, cx)
7564 })?
7565 .await?;
7566 Ok(proto::ProjectEntryResponse {
7567 entry: entry.as_ref().map(|e| e.into()),
7568 worktree_scan_id: worktree_scan_id as u64,
7569 })
7570 }
7571
7572 async fn handle_delete_project_entry(
7573 this: Model<Self>,
7574 envelope: TypedEnvelope<proto::DeleteProjectEntry>,
7575 _: Arc<Client>,
7576 mut cx: AsyncAppContext,
7577 ) -> Result<proto::ProjectEntryResponse> {
7578 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
7579
7580 this.update(&mut cx, |_, cx| cx.emit(Event::DeletedEntry(entry_id)))?;
7581
7582 let worktree = this.update(&mut cx, |this, cx| {
7583 this.worktree_for_entry(entry_id, cx)
7584 .ok_or_else(|| anyhow!("worktree not found"))
7585 })??;
7586 let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())?;
7587 worktree
7588 .update(&mut cx, |worktree, cx| {
7589 worktree
7590 .as_local_mut()
7591 .unwrap()
7592 .delete_entry(entry_id, cx)
7593 .ok_or_else(|| anyhow!("invalid entry"))
7594 })??
7595 .await?;
7596 Ok(proto::ProjectEntryResponse {
7597 entry: None,
7598 worktree_scan_id: worktree_scan_id as u64,
7599 })
7600 }
7601
7602 async fn handle_expand_project_entry(
7603 this: Model<Self>,
7604 envelope: TypedEnvelope<proto::ExpandProjectEntry>,
7605 _: Arc<Client>,
7606 mut cx: AsyncAppContext,
7607 ) -> Result<proto::ExpandProjectEntryResponse> {
7608 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
7609 let worktree = this
7610 .update(&mut cx, |this, cx| this.worktree_for_entry(entry_id, cx))?
7611 .ok_or_else(|| anyhow!("invalid request"))?;
7612 worktree
7613 .update(&mut cx, |worktree, cx| {
7614 worktree
7615 .as_local_mut()
7616 .unwrap()
7617 .expand_entry(entry_id, cx)
7618 .ok_or_else(|| anyhow!("invalid entry"))
7619 })??
7620 .await?;
7621 let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())? as u64;
7622 Ok(proto::ExpandProjectEntryResponse { worktree_scan_id })
7623 }
7624
7625 async fn handle_update_diagnostic_summary(
7626 this: Model<Self>,
7627 envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
7628 _: Arc<Client>,
7629 mut cx: AsyncAppContext,
7630 ) -> Result<()> {
7631 this.update(&mut cx, |this, cx| {
7632 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
7633 if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
7634 if let Some(summary) = envelope.payload.summary {
7635 let project_path = ProjectPath {
7636 worktree_id,
7637 path: Path::new(&summary.path).into(),
7638 };
7639 worktree.update(cx, |worktree, _| {
7640 worktree
7641 .as_remote_mut()
7642 .unwrap()
7643 .update_diagnostic_summary(project_path.path.clone(), &summary);
7644 });
7645 cx.emit(Event::DiagnosticsUpdated {
7646 language_server_id: LanguageServerId(summary.language_server_id as usize),
7647 path: project_path,
7648 });
7649 }
7650 }
7651 Ok(())
7652 })?
7653 }
7654
7655 async fn handle_start_language_server(
7656 this: Model<Self>,
7657 envelope: TypedEnvelope<proto::StartLanguageServer>,
7658 _: Arc<Client>,
7659 mut cx: AsyncAppContext,
7660 ) -> Result<()> {
7661 let server = envelope
7662 .payload
7663 .server
7664 .ok_or_else(|| anyhow!("invalid server"))?;
7665 this.update(&mut cx, |this, cx| {
7666 this.language_server_statuses.insert(
7667 LanguageServerId(server.id as usize),
7668 LanguageServerStatus {
7669 name: server.name,
7670 pending_work: Default::default(),
7671 has_pending_diagnostic_updates: false,
7672 progress_tokens: Default::default(),
7673 },
7674 );
7675 cx.notify();
7676 })?;
7677 Ok(())
7678 }
7679
7680 async fn handle_update_language_server(
7681 this: Model<Self>,
7682 envelope: TypedEnvelope<proto::UpdateLanguageServer>,
7683 _: Arc<Client>,
7684 mut cx: AsyncAppContext,
7685 ) -> Result<()> {
7686 this.update(&mut cx, |this, cx| {
7687 let language_server_id = LanguageServerId(envelope.payload.language_server_id as usize);
7688
7689 match envelope
7690 .payload
7691 .variant
7692 .ok_or_else(|| anyhow!("invalid variant"))?
7693 {
7694 proto::update_language_server::Variant::WorkStart(payload) => {
7695 this.on_lsp_work_start(
7696 language_server_id,
7697 payload.token,
7698 LanguageServerProgress {
7699 message: payload.message,
7700 percentage: payload.percentage.map(|p| p as usize),
7701 last_update_at: Instant::now(),
7702 },
7703 cx,
7704 );
7705 }
7706
7707 proto::update_language_server::Variant::WorkProgress(payload) => {
7708 this.on_lsp_work_progress(
7709 language_server_id,
7710 payload.token,
7711 LanguageServerProgress {
7712 message: payload.message,
7713 percentage: payload.percentage.map(|p| p as usize),
7714 last_update_at: Instant::now(),
7715 },
7716 cx,
7717 );
7718 }
7719
7720 proto::update_language_server::Variant::WorkEnd(payload) => {
7721 this.on_lsp_work_end(language_server_id, payload.token, cx);
7722 }
7723
7724 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(_) => {
7725 this.disk_based_diagnostics_started(language_server_id, cx);
7726 }
7727
7728 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(_) => {
7729 this.disk_based_diagnostics_finished(language_server_id, cx)
7730 }
7731 }
7732
7733 Ok(())
7734 })?
7735 }
7736
7737 async fn handle_update_buffer(
7738 this: Model<Self>,
7739 envelope: TypedEnvelope<proto::UpdateBuffer>,
7740 _: Arc<Client>,
7741 mut cx: AsyncAppContext,
7742 ) -> Result<proto::Ack> {
7743 this.update(&mut cx, |this, cx| {
7744 let payload = envelope.payload.clone();
7745 let buffer_id = BufferId::new(payload.buffer_id)?;
7746 let ops = payload
7747 .operations
7748 .into_iter()
7749 .map(language::proto::deserialize_operation)
7750 .collect::<Result<Vec<_>, _>>()?;
7751 let is_remote = this.is_remote();
7752 match this.opened_buffers.entry(buffer_id) {
7753 hash_map::Entry::Occupied(mut e) => match e.get_mut() {
7754 OpenBuffer::Strong(buffer) => {
7755 buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx))?;
7756 }
7757 OpenBuffer::Operations(operations) => operations.extend_from_slice(&ops),
7758 OpenBuffer::Weak(_) => {}
7759 },
7760 hash_map::Entry::Vacant(e) => {
7761 assert!(
7762 is_remote,
7763 "received buffer update from {:?}",
7764 envelope.original_sender_id
7765 );
7766 e.insert(OpenBuffer::Operations(ops));
7767 }
7768 }
7769 Ok(proto::Ack {})
7770 })?
7771 }
7772
7773 async fn handle_create_buffer_for_peer(
7774 this: Model<Self>,
7775 envelope: TypedEnvelope<proto::CreateBufferForPeer>,
7776 _: Arc<Client>,
7777 mut cx: AsyncAppContext,
7778 ) -> Result<()> {
7779 this.update(&mut cx, |this, cx| {
7780 match envelope
7781 .payload
7782 .variant
7783 .ok_or_else(|| anyhow!("missing variant"))?
7784 {
7785 proto::create_buffer_for_peer::Variant::State(mut state) => {
7786 let mut buffer_file = None;
7787 if let Some(file) = state.file.take() {
7788 let worktree_id = WorktreeId::from_proto(file.worktree_id);
7789 let worktree = this.worktree_for_id(worktree_id, cx).ok_or_else(|| {
7790 anyhow!("no worktree found for id {}", file.worktree_id)
7791 })?;
7792 buffer_file = Some(Arc::new(File::from_proto(file, worktree.clone(), cx)?)
7793 as Arc<dyn language::File>);
7794 }
7795
7796 let buffer_id = BufferId::new(state.id)?;
7797 let buffer = cx.new_model(|_| {
7798 Buffer::from_proto(this.replica_id(), this.capability(), state, buffer_file)
7799 .unwrap()
7800 });
7801 this.incomplete_remote_buffers
7802 .insert(buffer_id, Some(buffer));
7803 }
7804 proto::create_buffer_for_peer::Variant::Chunk(chunk) => {
7805 let buffer_id = BufferId::new(chunk.buffer_id)?;
7806 let buffer = this
7807 .incomplete_remote_buffers
7808 .get(&buffer_id)
7809 .cloned()
7810 .flatten()
7811 .ok_or_else(|| {
7812 anyhow!(
7813 "received chunk for buffer {} without initial state",
7814 chunk.buffer_id
7815 )
7816 })?;
7817 let operations = chunk
7818 .operations
7819 .into_iter()
7820 .map(language::proto::deserialize_operation)
7821 .collect::<Result<Vec<_>>>()?;
7822 buffer.update(cx, |buffer, cx| buffer.apply_ops(operations, cx))?;
7823
7824 if chunk.is_last {
7825 this.incomplete_remote_buffers.remove(&buffer_id);
7826 this.register_buffer(&buffer, cx)?;
7827 }
7828 }
7829 }
7830
7831 Ok(())
7832 })?
7833 }
7834
7835 async fn handle_update_diff_base(
7836 this: Model<Self>,
7837 envelope: TypedEnvelope<proto::UpdateDiffBase>,
7838 _: Arc<Client>,
7839 mut cx: AsyncAppContext,
7840 ) -> Result<()> {
7841 this.update(&mut cx, |this, cx| {
7842 let buffer_id = envelope.payload.buffer_id;
7843 let buffer_id = BufferId::new(buffer_id)?;
7844 let diff_base = envelope.payload.diff_base;
7845 if let Some(buffer) = this
7846 .opened_buffers
7847 .get_mut(&buffer_id)
7848 .and_then(|b| b.upgrade())
7849 .or_else(|| {
7850 this.incomplete_remote_buffers
7851 .get(&buffer_id)
7852 .cloned()
7853 .flatten()
7854 })
7855 {
7856 buffer.update(cx, |buffer, cx| buffer.set_diff_base(diff_base, cx));
7857 }
7858 Ok(())
7859 })?
7860 }
7861
7862 async fn handle_update_buffer_file(
7863 this: Model<Self>,
7864 envelope: TypedEnvelope<proto::UpdateBufferFile>,
7865 _: Arc<Client>,
7866 mut cx: AsyncAppContext,
7867 ) -> Result<()> {
7868 let buffer_id = envelope.payload.buffer_id;
7869 let buffer_id = BufferId::new(buffer_id)?;
7870
7871 this.update(&mut cx, |this, cx| {
7872 let payload = envelope.payload.clone();
7873 if let Some(buffer) = this
7874 .opened_buffers
7875 .get(&buffer_id)
7876 .and_then(|b| b.upgrade())
7877 .or_else(|| {
7878 this.incomplete_remote_buffers
7879 .get(&buffer_id)
7880 .cloned()
7881 .flatten()
7882 })
7883 {
7884 let file = payload.file.ok_or_else(|| anyhow!("invalid file"))?;
7885 let worktree = this
7886 .worktree_for_id(WorktreeId::from_proto(file.worktree_id), cx)
7887 .ok_or_else(|| anyhow!("no such worktree"))?;
7888 let file = File::from_proto(file, worktree, cx)?;
7889 buffer.update(cx, |buffer, cx| {
7890 buffer.file_updated(Arc::new(file), cx);
7891 });
7892 this.detect_language_for_buffer(&buffer, cx);
7893 }
7894 Ok(())
7895 })?
7896 }
7897
7898 async fn handle_save_buffer(
7899 this: Model<Self>,
7900 envelope: TypedEnvelope<proto::SaveBuffer>,
7901 _: Arc<Client>,
7902 mut cx: AsyncAppContext,
7903 ) -> Result<proto::BufferSaved> {
7904 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
7905 let (project_id, buffer) = this.update(&mut cx, |this, _cx| {
7906 let project_id = this.remote_id().ok_or_else(|| anyhow!("not connected"))?;
7907 let buffer = this
7908 .opened_buffers
7909 .get(&buffer_id)
7910 .and_then(|buffer| buffer.upgrade())
7911 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
7912 anyhow::Ok((project_id, buffer))
7913 })??;
7914 buffer
7915 .update(&mut cx, |buffer, _| {
7916 buffer.wait_for_version(deserialize_version(&envelope.payload.version))
7917 })?
7918 .await?;
7919 let buffer_id = buffer.update(&mut cx, |buffer, _| buffer.remote_id())?;
7920
7921 this.update(&mut cx, |this, cx| this.save_buffer(buffer.clone(), cx))?
7922 .await?;
7923 Ok(buffer.update(&mut cx, |buffer, _| proto::BufferSaved {
7924 project_id,
7925 buffer_id: buffer_id.into(),
7926 version: serialize_version(buffer.saved_version()),
7927 mtime: Some(buffer.saved_mtime().into()),
7928 fingerprint: language::proto::serialize_fingerprint(buffer.saved_version_fingerprint()),
7929 })?)
7930 }
7931
7932 async fn handle_reload_buffers(
7933 this: Model<Self>,
7934 envelope: TypedEnvelope<proto::ReloadBuffers>,
7935 _: Arc<Client>,
7936 mut cx: AsyncAppContext,
7937 ) -> Result<proto::ReloadBuffersResponse> {
7938 let sender_id = envelope.original_sender_id()?;
7939 let reload = this.update(&mut cx, |this, cx| {
7940 let mut buffers = HashSet::default();
7941 for buffer_id in &envelope.payload.buffer_ids {
7942 let buffer_id = BufferId::new(*buffer_id)?;
7943 buffers.insert(
7944 this.opened_buffers
7945 .get(&buffer_id)
7946 .and_then(|buffer| buffer.upgrade())
7947 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
7948 );
7949 }
7950 Ok::<_, anyhow::Error>(this.reload_buffers(buffers, false, cx))
7951 })??;
7952
7953 let project_transaction = reload.await?;
7954 let project_transaction = this.update(&mut cx, |this, cx| {
7955 this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
7956 })?;
7957 Ok(proto::ReloadBuffersResponse {
7958 transaction: Some(project_transaction),
7959 })
7960 }
7961
7962 async fn handle_synchronize_buffers(
7963 this: Model<Self>,
7964 envelope: TypedEnvelope<proto::SynchronizeBuffers>,
7965 _: Arc<Client>,
7966 mut cx: AsyncAppContext,
7967 ) -> Result<proto::SynchronizeBuffersResponse> {
7968 let project_id = envelope.payload.project_id;
7969 let mut response = proto::SynchronizeBuffersResponse {
7970 buffers: Default::default(),
7971 };
7972
7973 this.update(&mut cx, |this, cx| {
7974 let Some(guest_id) = envelope.original_sender_id else {
7975 error!("missing original_sender_id on SynchronizeBuffers request");
7976 bail!("missing original_sender_id on SynchronizeBuffers request");
7977 };
7978
7979 this.shared_buffers.entry(guest_id).or_default().clear();
7980 for buffer in envelope.payload.buffers {
7981 let buffer_id = BufferId::new(buffer.id)?;
7982 let remote_version = language::proto::deserialize_version(&buffer.version);
7983 if let Some(buffer) = this.buffer_for_id(buffer_id) {
7984 this.shared_buffers
7985 .entry(guest_id)
7986 .or_default()
7987 .insert(buffer_id);
7988
7989 let buffer = buffer.read(cx);
7990 response.buffers.push(proto::BufferVersion {
7991 id: buffer_id.into(),
7992 version: language::proto::serialize_version(&buffer.version),
7993 });
7994
7995 let operations = buffer.serialize_ops(Some(remote_version), cx);
7996 let client = this.client.clone();
7997 if let Some(file) = buffer.file() {
7998 client
7999 .send(proto::UpdateBufferFile {
8000 project_id,
8001 buffer_id: buffer_id.into(),
8002 file: Some(file.to_proto()),
8003 })
8004 .log_err();
8005 }
8006
8007 client
8008 .send(proto::UpdateDiffBase {
8009 project_id,
8010 buffer_id: buffer_id.into(),
8011 diff_base: buffer.diff_base().map(Into::into),
8012 })
8013 .log_err();
8014
8015 client
8016 .send(proto::BufferReloaded {
8017 project_id,
8018 buffer_id: buffer_id.into(),
8019 version: language::proto::serialize_version(buffer.saved_version()),
8020 mtime: Some(buffer.saved_mtime().into()),
8021 fingerprint: language::proto::serialize_fingerprint(
8022 buffer.saved_version_fingerprint(),
8023 ),
8024 line_ending: language::proto::serialize_line_ending(
8025 buffer.line_ending(),
8026 ) as i32,
8027 })
8028 .log_err();
8029
8030 cx.background_executor()
8031 .spawn(
8032 async move {
8033 let operations = operations.await;
8034 for chunk in split_operations(operations) {
8035 client
8036 .request(proto::UpdateBuffer {
8037 project_id,
8038 buffer_id: buffer_id.into(),
8039 operations: chunk,
8040 })
8041 .await?;
8042 }
8043 anyhow::Ok(())
8044 }
8045 .log_err(),
8046 )
8047 .detach();
8048 }
8049 }
8050 Ok(())
8051 })??;
8052
8053 Ok(response)
8054 }
8055
8056 async fn handle_format_buffers(
8057 this: Model<Self>,
8058 envelope: TypedEnvelope<proto::FormatBuffers>,
8059 _: Arc<Client>,
8060 mut cx: AsyncAppContext,
8061 ) -> Result<proto::FormatBuffersResponse> {
8062 let sender_id = envelope.original_sender_id()?;
8063 let format = this.update(&mut cx, |this, cx| {
8064 let mut buffers = HashSet::default();
8065 for buffer_id in &envelope.payload.buffer_ids {
8066 let buffer_id = BufferId::new(*buffer_id)?;
8067 buffers.insert(
8068 this.opened_buffers
8069 .get(&buffer_id)
8070 .and_then(|buffer| buffer.upgrade())
8071 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
8072 );
8073 }
8074 let trigger = FormatTrigger::from_proto(envelope.payload.trigger);
8075 Ok::<_, anyhow::Error>(this.format(buffers, false, trigger, cx))
8076 })??;
8077
8078 let project_transaction = format.await?;
8079 let project_transaction = this.update(&mut cx, |this, cx| {
8080 this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
8081 })?;
8082 Ok(proto::FormatBuffersResponse {
8083 transaction: Some(project_transaction),
8084 })
8085 }
8086
8087 async fn handle_apply_additional_edits_for_completion(
8088 this: Model<Self>,
8089 envelope: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
8090 _: Arc<Client>,
8091 mut cx: AsyncAppContext,
8092 ) -> Result<proto::ApplyCompletionAdditionalEditsResponse> {
8093 let (buffer, completion) = this.update(&mut cx, |this, cx| {
8094 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
8095 let buffer = this
8096 .opened_buffers
8097 .get(&buffer_id)
8098 .and_then(|buffer| buffer.upgrade())
8099 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
8100 let language = buffer.read(cx).language();
8101 let completion = language::proto::deserialize_completion(
8102 envelope
8103 .payload
8104 .completion
8105 .ok_or_else(|| anyhow!("invalid completion"))?,
8106 language.cloned(),
8107 );
8108 Ok::<_, anyhow::Error>((buffer, completion))
8109 })??;
8110
8111 let completion = completion.await?;
8112
8113 let apply_additional_edits = this.update(&mut cx, |this, cx| {
8114 this.apply_additional_edits_for_completion(buffer, completion, false, cx)
8115 })?;
8116
8117 Ok(proto::ApplyCompletionAdditionalEditsResponse {
8118 transaction: apply_additional_edits
8119 .await?
8120 .as_ref()
8121 .map(language::proto::serialize_transaction),
8122 })
8123 }
8124
8125 async fn handle_resolve_completion_documentation(
8126 this: Model<Self>,
8127 envelope: TypedEnvelope<proto::ResolveCompletionDocumentation>,
8128 _: Arc<Client>,
8129 mut cx: AsyncAppContext,
8130 ) -> Result<proto::ResolveCompletionDocumentationResponse> {
8131 let lsp_completion = serde_json::from_slice(&envelope.payload.lsp_completion)?;
8132
8133 let completion = this
8134 .read_with(&mut cx, |this, _| {
8135 let id = LanguageServerId(envelope.payload.language_server_id as usize);
8136 let Some(server) = this.language_server_for_id(id) else {
8137 return Err(anyhow!("No language server {id}"));
8138 };
8139
8140 Ok(server.request::<lsp::request::ResolveCompletionItem>(lsp_completion))
8141 })??
8142 .await?;
8143
8144 let mut is_markdown = false;
8145 let text = match completion.documentation {
8146 Some(lsp::Documentation::String(text)) => text,
8147
8148 Some(lsp::Documentation::MarkupContent(lsp::MarkupContent { kind, value })) => {
8149 is_markdown = kind == lsp::MarkupKind::Markdown;
8150 value
8151 }
8152
8153 _ => String::new(),
8154 };
8155
8156 Ok(proto::ResolveCompletionDocumentationResponse { text, is_markdown })
8157 }
8158
8159 async fn handle_apply_code_action(
8160 this: Model<Self>,
8161 envelope: TypedEnvelope<proto::ApplyCodeAction>,
8162 _: Arc<Client>,
8163 mut cx: AsyncAppContext,
8164 ) -> Result<proto::ApplyCodeActionResponse> {
8165 let sender_id = envelope.original_sender_id()?;
8166 let action = language::proto::deserialize_code_action(
8167 envelope
8168 .payload
8169 .action
8170 .ok_or_else(|| anyhow!("invalid action"))?,
8171 )?;
8172 let apply_code_action = this.update(&mut cx, |this, cx| {
8173 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
8174 let buffer = this
8175 .opened_buffers
8176 .get(&buffer_id)
8177 .and_then(|buffer| buffer.upgrade())
8178 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
8179 Ok::<_, anyhow::Error>(this.apply_code_action(buffer, action, false, cx))
8180 })??;
8181
8182 let project_transaction = apply_code_action.await?;
8183 let project_transaction = this.update(&mut cx, |this, cx| {
8184 this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
8185 })?;
8186 Ok(proto::ApplyCodeActionResponse {
8187 transaction: Some(project_transaction),
8188 })
8189 }
8190
8191 async fn handle_on_type_formatting(
8192 this: Model<Self>,
8193 envelope: TypedEnvelope<proto::OnTypeFormatting>,
8194 _: Arc<Client>,
8195 mut cx: AsyncAppContext,
8196 ) -> Result<proto::OnTypeFormattingResponse> {
8197 let on_type_formatting = this.update(&mut cx, |this, cx| {
8198 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
8199 let buffer = this
8200 .opened_buffers
8201 .get(&buffer_id)
8202 .and_then(|buffer| buffer.upgrade())
8203 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
8204 let position = envelope
8205 .payload
8206 .position
8207 .and_then(deserialize_anchor)
8208 .ok_or_else(|| anyhow!("invalid position"))?;
8209 Ok::<_, anyhow::Error>(this.apply_on_type_formatting(
8210 buffer,
8211 position,
8212 envelope.payload.trigger.clone(),
8213 cx,
8214 ))
8215 })??;
8216
8217 let transaction = on_type_formatting
8218 .await?
8219 .as_ref()
8220 .map(language::proto::serialize_transaction);
8221 Ok(proto::OnTypeFormattingResponse { transaction })
8222 }
8223
8224 async fn handle_inlay_hints(
8225 this: Model<Self>,
8226 envelope: TypedEnvelope<proto::InlayHints>,
8227 _: Arc<Client>,
8228 mut cx: AsyncAppContext,
8229 ) -> Result<proto::InlayHintsResponse> {
8230 let sender_id = envelope.original_sender_id()?;
8231 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
8232 let buffer = this.update(&mut cx, |this, _| {
8233 this.opened_buffers
8234 .get(&buffer_id)
8235 .and_then(|buffer| buffer.upgrade())
8236 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
8237 })??;
8238 let buffer_version = deserialize_version(&envelope.payload.version);
8239
8240 buffer
8241 .update(&mut cx, |buffer, _| {
8242 buffer.wait_for_version(buffer_version.clone())
8243 })?
8244 .await
8245 .with_context(|| {
8246 format!(
8247 "waiting for version {:?} for buffer {}",
8248 buffer_version,
8249 buffer.entity_id()
8250 )
8251 })?;
8252
8253 let start = envelope
8254 .payload
8255 .start
8256 .and_then(deserialize_anchor)
8257 .context("missing range start")?;
8258 let end = envelope
8259 .payload
8260 .end
8261 .and_then(deserialize_anchor)
8262 .context("missing range end")?;
8263 let buffer_hints = this
8264 .update(&mut cx, |project, cx| {
8265 project.inlay_hints(buffer, start..end, cx)
8266 })?
8267 .await
8268 .context("inlay hints fetch")?;
8269
8270 Ok(this.update(&mut cx, |project, cx| {
8271 InlayHints::response_to_proto(buffer_hints, project, sender_id, &buffer_version, cx)
8272 })?)
8273 }
8274
8275 async fn handle_resolve_inlay_hint(
8276 this: Model<Self>,
8277 envelope: TypedEnvelope<proto::ResolveInlayHint>,
8278 _: Arc<Client>,
8279 mut cx: AsyncAppContext,
8280 ) -> Result<proto::ResolveInlayHintResponse> {
8281 let proto_hint = envelope
8282 .payload
8283 .hint
8284 .expect("incorrect protobuf resolve inlay hint message: missing the inlay hint");
8285 let hint = InlayHints::proto_to_project_hint(proto_hint)
8286 .context("resolved proto inlay hint conversion")?;
8287 let buffer = this.update(&mut cx, |this, _cx| {
8288 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
8289 this.opened_buffers
8290 .get(&buffer_id)
8291 .and_then(|buffer| buffer.upgrade())
8292 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
8293 })??;
8294 let response_hint = this
8295 .update(&mut cx, |project, cx| {
8296 project.resolve_inlay_hint(
8297 hint,
8298 buffer,
8299 LanguageServerId(envelope.payload.language_server_id as usize),
8300 cx,
8301 )
8302 })?
8303 .await
8304 .context("inlay hints fetch")?;
8305 Ok(proto::ResolveInlayHintResponse {
8306 hint: Some(InlayHints::project_to_proto_hint(response_hint)),
8307 })
8308 }
8309
8310 async fn handle_refresh_inlay_hints(
8311 this: Model<Self>,
8312 _: TypedEnvelope<proto::RefreshInlayHints>,
8313 _: Arc<Client>,
8314 mut cx: AsyncAppContext,
8315 ) -> Result<proto::Ack> {
8316 this.update(&mut cx, |_, cx| {
8317 cx.emit(Event::RefreshInlayHints);
8318 })?;
8319 Ok(proto::Ack {})
8320 }
8321
8322 async fn handle_lsp_command<T: LspCommand>(
8323 this: Model<Self>,
8324 envelope: TypedEnvelope<T::ProtoRequest>,
8325 _: Arc<Client>,
8326 mut cx: AsyncAppContext,
8327 ) -> Result<<T::ProtoRequest as proto::RequestMessage>::Response>
8328 where
8329 <T::LspRequest as lsp::request::Request>::Params: Send,
8330 <T::LspRequest as lsp::request::Request>::Result: Send,
8331 {
8332 let sender_id = envelope.original_sender_id()?;
8333 let buffer_id = T::buffer_id_from_proto(&envelope.payload)?;
8334 let buffer_handle = this.update(&mut cx, |this, _cx| {
8335 this.opened_buffers
8336 .get(&buffer_id)
8337 .and_then(|buffer| buffer.upgrade())
8338 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
8339 })??;
8340 let request = T::from_proto(
8341 envelope.payload,
8342 this.clone(),
8343 buffer_handle.clone(),
8344 cx.clone(),
8345 )
8346 .await?;
8347 let buffer_version = buffer_handle.update(&mut cx, |buffer, _| buffer.version())?;
8348 let response = this
8349 .update(&mut cx, |this, cx| {
8350 this.request_lsp(buffer_handle, LanguageServerToQuery::Primary, request, cx)
8351 })?
8352 .await?;
8353 this.update(&mut cx, |this, cx| {
8354 Ok(T::response_to_proto(
8355 response,
8356 this,
8357 sender_id,
8358 &buffer_version,
8359 cx,
8360 ))
8361 })?
8362 }
8363
8364 async fn handle_get_project_symbols(
8365 this: Model<Self>,
8366 envelope: TypedEnvelope<proto::GetProjectSymbols>,
8367 _: Arc<Client>,
8368 mut cx: AsyncAppContext,
8369 ) -> Result<proto::GetProjectSymbolsResponse> {
8370 let symbols = this
8371 .update(&mut cx, |this, cx| {
8372 this.symbols(&envelope.payload.query, cx)
8373 })?
8374 .await?;
8375
8376 Ok(proto::GetProjectSymbolsResponse {
8377 symbols: symbols.iter().map(serialize_symbol).collect(),
8378 })
8379 }
8380
8381 async fn handle_search_project(
8382 this: Model<Self>,
8383 envelope: TypedEnvelope<proto::SearchProject>,
8384 _: Arc<Client>,
8385 mut cx: AsyncAppContext,
8386 ) -> Result<proto::SearchProjectResponse> {
8387 let peer_id = envelope.original_sender_id()?;
8388 let query = SearchQuery::from_proto(envelope.payload)?;
8389 let mut result = this.update(&mut cx, |this, cx| this.search(query, cx))?;
8390
8391 cx.spawn(move |mut cx| async move {
8392 let mut locations = Vec::new();
8393 while let Some((buffer, ranges)) = result.next().await {
8394 for range in ranges {
8395 let start = serialize_anchor(&range.start);
8396 let end = serialize_anchor(&range.end);
8397 let buffer_id = this.update(&mut cx, |this, cx| {
8398 this.create_buffer_for_peer(&buffer, peer_id, cx).into()
8399 })?;
8400 locations.push(proto::Location {
8401 buffer_id,
8402 start: Some(start),
8403 end: Some(end),
8404 });
8405 }
8406 }
8407 Ok(proto::SearchProjectResponse { locations })
8408 })
8409 .await
8410 }
8411
8412 async fn handle_open_buffer_for_symbol(
8413 this: Model<Self>,
8414 envelope: TypedEnvelope<proto::OpenBufferForSymbol>,
8415 _: Arc<Client>,
8416 mut cx: AsyncAppContext,
8417 ) -> Result<proto::OpenBufferForSymbolResponse> {
8418 let peer_id = envelope.original_sender_id()?;
8419 let symbol = envelope
8420 .payload
8421 .symbol
8422 .ok_or_else(|| anyhow!("invalid symbol"))?;
8423 let symbol = this
8424 .update(&mut cx, |this, _| this.deserialize_symbol(symbol))?
8425 .await?;
8426 let symbol = this.update(&mut cx, |this, _| {
8427 let signature = this.symbol_signature(&symbol.path);
8428 if signature == symbol.signature {
8429 Ok(symbol)
8430 } else {
8431 Err(anyhow!("invalid symbol signature"))
8432 }
8433 })??;
8434 let buffer = this
8435 .update(&mut cx, |this, cx| this.open_buffer_for_symbol(&symbol, cx))?
8436 .await?;
8437
8438 this.update(&mut cx, |this, cx| {
8439 let is_private = buffer
8440 .read(cx)
8441 .file()
8442 .map(|f| f.is_private())
8443 .unwrap_or_default();
8444 if is_private {
8445 Err(anyhow!(ErrorCode::UnsharedItem))
8446 } else {
8447 Ok(proto::OpenBufferForSymbolResponse {
8448 buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx).into(),
8449 })
8450 }
8451 })?
8452 }
8453
8454 fn symbol_signature(&self, project_path: &ProjectPath) -> [u8; 32] {
8455 let mut hasher = Sha256::new();
8456 hasher.update(project_path.worktree_id.to_proto().to_be_bytes());
8457 hasher.update(project_path.path.to_string_lossy().as_bytes());
8458 hasher.update(self.nonce.to_be_bytes());
8459 hasher.finalize().as_slice().try_into().unwrap()
8460 }
8461
8462 async fn handle_open_buffer_by_id(
8463 this: Model<Self>,
8464 envelope: TypedEnvelope<proto::OpenBufferById>,
8465 _: Arc<Client>,
8466 mut cx: AsyncAppContext,
8467 ) -> Result<proto::OpenBufferResponse> {
8468 let peer_id = envelope.original_sender_id()?;
8469 let buffer_id = BufferId::new(envelope.payload.id)?;
8470 let buffer = this
8471 .update(&mut cx, |this, cx| this.open_buffer_by_id(buffer_id, cx))?
8472 .await?;
8473 Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
8474 }
8475
8476 async fn handle_open_buffer_by_path(
8477 this: Model<Self>,
8478 envelope: TypedEnvelope<proto::OpenBufferByPath>,
8479 _: Arc<Client>,
8480 mut cx: AsyncAppContext,
8481 ) -> Result<proto::OpenBufferResponse> {
8482 let peer_id = envelope.original_sender_id()?;
8483 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
8484 let open_buffer = this.update(&mut cx, |this, cx| {
8485 this.open_buffer(
8486 ProjectPath {
8487 worktree_id,
8488 path: PathBuf::from(envelope.payload.path).into(),
8489 },
8490 cx,
8491 )
8492 })?;
8493
8494 let buffer = open_buffer.await?;
8495 Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
8496 }
8497
8498 fn respond_to_open_buffer_request(
8499 this: Model<Self>,
8500 buffer: Model<Buffer>,
8501 peer_id: proto::PeerId,
8502 cx: &mut AsyncAppContext,
8503 ) -> Result<proto::OpenBufferResponse> {
8504 this.update(cx, |this, cx| {
8505 let is_private = buffer
8506 .read(cx)
8507 .file()
8508 .map(|f| f.is_private())
8509 .unwrap_or_default();
8510 if is_private {
8511 Err(anyhow!(ErrorCode::UnsharedItem))
8512 } else {
8513 Ok(proto::OpenBufferResponse {
8514 buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx).into(),
8515 })
8516 }
8517 })?
8518 }
8519
8520 fn serialize_project_transaction_for_peer(
8521 &mut self,
8522 project_transaction: ProjectTransaction,
8523 peer_id: proto::PeerId,
8524 cx: &mut AppContext,
8525 ) -> proto::ProjectTransaction {
8526 let mut serialized_transaction = proto::ProjectTransaction {
8527 buffer_ids: Default::default(),
8528 transactions: Default::default(),
8529 };
8530 for (buffer, transaction) in project_transaction.0 {
8531 serialized_transaction
8532 .buffer_ids
8533 .push(self.create_buffer_for_peer(&buffer, peer_id, cx).into());
8534 serialized_transaction
8535 .transactions
8536 .push(language::proto::serialize_transaction(&transaction));
8537 }
8538 serialized_transaction
8539 }
8540
8541 fn deserialize_project_transaction(
8542 &mut self,
8543 message: proto::ProjectTransaction,
8544 push_to_history: bool,
8545 cx: &mut ModelContext<Self>,
8546 ) -> Task<Result<ProjectTransaction>> {
8547 cx.spawn(move |this, mut cx| async move {
8548 let mut project_transaction = ProjectTransaction::default();
8549 for (buffer_id, transaction) in message.buffer_ids.into_iter().zip(message.transactions)
8550 {
8551 let buffer_id = BufferId::new(buffer_id)?;
8552 let buffer = this
8553 .update(&mut cx, |this, cx| {
8554 this.wait_for_remote_buffer(buffer_id, cx)
8555 })?
8556 .await?;
8557 let transaction = language::proto::deserialize_transaction(transaction)?;
8558 project_transaction.0.insert(buffer, transaction);
8559 }
8560
8561 for (buffer, transaction) in &project_transaction.0 {
8562 buffer
8563 .update(&mut cx, |buffer, _| {
8564 buffer.wait_for_edits(transaction.edit_ids.iter().copied())
8565 })?
8566 .await?;
8567
8568 if push_to_history {
8569 buffer.update(&mut cx, |buffer, _| {
8570 buffer.push_transaction(transaction.clone(), Instant::now());
8571 })?;
8572 }
8573 }
8574
8575 Ok(project_transaction)
8576 })
8577 }
8578
8579 fn create_buffer_for_peer(
8580 &mut self,
8581 buffer: &Model<Buffer>,
8582 peer_id: proto::PeerId,
8583 cx: &mut AppContext,
8584 ) -> BufferId {
8585 let buffer_id = buffer.read(cx).remote_id();
8586 if let ProjectClientState::Shared { updates_tx, .. } = &self.client_state {
8587 updates_tx
8588 .unbounded_send(LocalProjectUpdate::CreateBufferForPeer { peer_id, buffer_id })
8589 .ok();
8590 }
8591 buffer_id
8592 }
8593
8594 fn wait_for_remote_buffer(
8595 &mut self,
8596 id: BufferId,
8597 cx: &mut ModelContext<Self>,
8598 ) -> Task<Result<Model<Buffer>>> {
8599 let mut opened_buffer_rx = self.opened_buffer.1.clone();
8600
8601 cx.spawn(move |this, mut cx| async move {
8602 let buffer = loop {
8603 let Some(this) = this.upgrade() else {
8604 return Err(anyhow!("project dropped"));
8605 };
8606
8607 let buffer = this.update(&mut cx, |this, _cx| {
8608 this.opened_buffers
8609 .get(&id)
8610 .and_then(|buffer| buffer.upgrade())
8611 })?;
8612
8613 if let Some(buffer) = buffer {
8614 break buffer;
8615 } else if this.update(&mut cx, |this, _| this.is_disconnected())? {
8616 return Err(anyhow!("disconnected before buffer {} could be opened", id));
8617 }
8618
8619 this.update(&mut cx, |this, _| {
8620 this.incomplete_remote_buffers.entry(id).or_default();
8621 })?;
8622 drop(this);
8623
8624 opened_buffer_rx
8625 .next()
8626 .await
8627 .ok_or_else(|| anyhow!("project dropped while waiting for buffer"))?;
8628 };
8629
8630 Ok(buffer)
8631 })
8632 }
8633
8634 fn synchronize_remote_buffers(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
8635 let project_id = match self.client_state {
8636 ProjectClientState::Remote {
8637 sharing_has_stopped,
8638 remote_id,
8639 ..
8640 } => {
8641 if sharing_has_stopped {
8642 return Task::ready(Err(anyhow!(
8643 "can't synchronize remote buffers on a readonly project"
8644 )));
8645 } else {
8646 remote_id
8647 }
8648 }
8649 ProjectClientState::Shared { .. } | ProjectClientState::Local => {
8650 return Task::ready(Err(anyhow!(
8651 "can't synchronize remote buffers on a local project"
8652 )))
8653 }
8654 };
8655
8656 let client = self.client.clone();
8657 cx.spawn(move |this, mut cx| async move {
8658 let (buffers, incomplete_buffer_ids) = this.update(&mut cx, |this, cx| {
8659 let buffers = this
8660 .opened_buffers
8661 .iter()
8662 .filter_map(|(id, buffer)| {
8663 let buffer = buffer.upgrade()?;
8664 Some(proto::BufferVersion {
8665 id: (*id).into(),
8666 version: language::proto::serialize_version(&buffer.read(cx).version),
8667 })
8668 })
8669 .collect();
8670 let incomplete_buffer_ids = this
8671 .incomplete_remote_buffers
8672 .keys()
8673 .copied()
8674 .collect::<Vec<_>>();
8675
8676 (buffers, incomplete_buffer_ids)
8677 })?;
8678 let response = client
8679 .request(proto::SynchronizeBuffers {
8680 project_id,
8681 buffers,
8682 })
8683 .await?;
8684
8685 let send_updates_for_buffers = this.update(&mut cx, |this, cx| {
8686 response
8687 .buffers
8688 .into_iter()
8689 .map(|buffer| {
8690 let client = client.clone();
8691 let buffer_id = match BufferId::new(buffer.id) {
8692 Ok(id) => id,
8693 Err(e) => {
8694 return Task::ready(Err(e));
8695 }
8696 };
8697 let remote_version = language::proto::deserialize_version(&buffer.version);
8698 if let Some(buffer) = this.buffer_for_id(buffer_id) {
8699 let operations =
8700 buffer.read(cx).serialize_ops(Some(remote_version), cx);
8701 cx.background_executor().spawn(async move {
8702 let operations = operations.await;
8703 for chunk in split_operations(operations) {
8704 client
8705 .request(proto::UpdateBuffer {
8706 project_id,
8707 buffer_id: buffer_id.into(),
8708 operations: chunk,
8709 })
8710 .await?;
8711 }
8712 anyhow::Ok(())
8713 })
8714 } else {
8715 Task::ready(Ok(()))
8716 }
8717 })
8718 .collect::<Vec<_>>()
8719 })?;
8720
8721 // Any incomplete buffers have open requests waiting. Request that the host sends
8722 // creates these buffers for us again to unblock any waiting futures.
8723 for id in incomplete_buffer_ids {
8724 cx.background_executor()
8725 .spawn(client.request(proto::OpenBufferById {
8726 project_id,
8727 id: id.into(),
8728 }))
8729 .detach();
8730 }
8731
8732 futures::future::join_all(send_updates_for_buffers)
8733 .await
8734 .into_iter()
8735 .collect()
8736 })
8737 }
8738
8739 pub fn worktree_metadata_protos(&self, cx: &AppContext) -> Vec<proto::WorktreeMetadata> {
8740 self.worktrees()
8741 .map(|worktree| {
8742 let worktree = worktree.read(cx);
8743 proto::WorktreeMetadata {
8744 id: worktree.id().to_proto(),
8745 root_name: worktree.root_name().into(),
8746 visible: worktree.is_visible(),
8747 abs_path: worktree.abs_path().to_string_lossy().into(),
8748 }
8749 })
8750 .collect()
8751 }
8752
8753 fn set_worktrees_from_proto(
8754 &mut self,
8755 worktrees: Vec<proto::WorktreeMetadata>,
8756 cx: &mut ModelContext<Project>,
8757 ) -> Result<()> {
8758 let replica_id = self.replica_id();
8759 let remote_id = self.remote_id().ok_or_else(|| anyhow!("invalid project"))?;
8760
8761 let mut old_worktrees_by_id = self
8762 .worktrees
8763 .drain(..)
8764 .filter_map(|worktree| {
8765 let worktree = worktree.upgrade()?;
8766 Some((worktree.read(cx).id(), worktree))
8767 })
8768 .collect::<HashMap<_, _>>();
8769
8770 for worktree in worktrees {
8771 if let Some(old_worktree) =
8772 old_worktrees_by_id.remove(&WorktreeId::from_proto(worktree.id))
8773 {
8774 self.worktrees.push(WorktreeHandle::Strong(old_worktree));
8775 } else {
8776 let worktree =
8777 Worktree::remote(remote_id, replica_id, worktree, self.client.clone(), cx);
8778 let _ = self.add_worktree(&worktree, cx);
8779 }
8780 }
8781
8782 self.metadata_changed(cx);
8783 for id in old_worktrees_by_id.keys() {
8784 cx.emit(Event::WorktreeRemoved(*id));
8785 }
8786
8787 Ok(())
8788 }
8789
8790 fn set_collaborators_from_proto(
8791 &mut self,
8792 messages: Vec<proto::Collaborator>,
8793 cx: &mut ModelContext<Self>,
8794 ) -> Result<()> {
8795 let mut collaborators = HashMap::default();
8796 for message in messages {
8797 let collaborator = Collaborator::from_proto(message)?;
8798 collaborators.insert(collaborator.peer_id, collaborator);
8799 }
8800 for old_peer_id in self.collaborators.keys() {
8801 if !collaborators.contains_key(old_peer_id) {
8802 cx.emit(Event::CollaboratorLeft(*old_peer_id));
8803 }
8804 }
8805 self.collaborators = collaborators;
8806 Ok(())
8807 }
8808
8809 fn deserialize_symbol(
8810 &self,
8811 serialized_symbol: proto::Symbol,
8812 ) -> impl Future<Output = Result<Symbol>> {
8813 let languages = self.languages.clone();
8814 async move {
8815 let source_worktree_id = WorktreeId::from_proto(serialized_symbol.source_worktree_id);
8816 let worktree_id = WorktreeId::from_proto(serialized_symbol.worktree_id);
8817 let start = serialized_symbol
8818 .start
8819 .ok_or_else(|| anyhow!("invalid start"))?;
8820 let end = serialized_symbol
8821 .end
8822 .ok_or_else(|| anyhow!("invalid end"))?;
8823 let kind = unsafe { mem::transmute(serialized_symbol.kind) };
8824 let path = ProjectPath {
8825 worktree_id,
8826 path: PathBuf::from(serialized_symbol.path).into(),
8827 };
8828 let language = languages
8829 .language_for_file(&path.path, None)
8830 .await
8831 .log_err();
8832 Ok(Symbol {
8833 language_server_name: LanguageServerName(
8834 serialized_symbol.language_server_name.into(),
8835 ),
8836 source_worktree_id,
8837 path,
8838 label: {
8839 match language {
8840 Some(language) => {
8841 language
8842 .label_for_symbol(&serialized_symbol.name, kind)
8843 .await
8844 }
8845 None => None,
8846 }
8847 .unwrap_or_else(|| CodeLabel::plain(serialized_symbol.name.clone(), None))
8848 },
8849
8850 name: serialized_symbol.name,
8851 range: Unclipped(PointUtf16::new(start.row, start.column))
8852 ..Unclipped(PointUtf16::new(end.row, end.column)),
8853 kind,
8854 signature: serialized_symbol
8855 .signature
8856 .try_into()
8857 .map_err(|_| anyhow!("invalid signature"))?,
8858 })
8859 }
8860 }
8861
8862 async fn handle_buffer_saved(
8863 this: Model<Self>,
8864 envelope: TypedEnvelope<proto::BufferSaved>,
8865 _: Arc<Client>,
8866 mut cx: AsyncAppContext,
8867 ) -> Result<()> {
8868 let fingerprint = deserialize_fingerprint(&envelope.payload.fingerprint)?;
8869 let version = deserialize_version(&envelope.payload.version);
8870 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
8871 let mtime = envelope
8872 .payload
8873 .mtime
8874 .ok_or_else(|| anyhow!("missing mtime"))?
8875 .into();
8876
8877 this.update(&mut cx, |this, cx| {
8878 let buffer = this
8879 .opened_buffers
8880 .get(&buffer_id)
8881 .and_then(|buffer| buffer.upgrade())
8882 .or_else(|| {
8883 this.incomplete_remote_buffers
8884 .get(&buffer_id)
8885 .and_then(|b| b.clone())
8886 });
8887 if let Some(buffer) = buffer {
8888 buffer.update(cx, |buffer, cx| {
8889 buffer.did_save(version, fingerprint, mtime, cx);
8890 });
8891 }
8892 Ok(())
8893 })?
8894 }
8895
8896 async fn handle_buffer_reloaded(
8897 this: Model<Self>,
8898 envelope: TypedEnvelope<proto::BufferReloaded>,
8899 _: Arc<Client>,
8900 mut cx: AsyncAppContext,
8901 ) -> Result<()> {
8902 let payload = envelope.payload;
8903 let version = deserialize_version(&payload.version);
8904 let fingerprint = deserialize_fingerprint(&payload.fingerprint)?;
8905 let line_ending = deserialize_line_ending(
8906 proto::LineEnding::from_i32(payload.line_ending)
8907 .ok_or_else(|| anyhow!("missing line ending"))?,
8908 );
8909 let mtime = payload
8910 .mtime
8911 .ok_or_else(|| anyhow!("missing mtime"))?
8912 .into();
8913 let buffer_id = BufferId::new(payload.buffer_id)?;
8914 this.update(&mut cx, |this, cx| {
8915 let buffer = this
8916 .opened_buffers
8917 .get(&buffer_id)
8918 .and_then(|buffer| buffer.upgrade())
8919 .or_else(|| {
8920 this.incomplete_remote_buffers
8921 .get(&buffer_id)
8922 .cloned()
8923 .flatten()
8924 });
8925 if let Some(buffer) = buffer {
8926 buffer.update(cx, |buffer, cx| {
8927 buffer.did_reload(version, fingerprint, line_ending, mtime, cx);
8928 });
8929 }
8930 Ok(())
8931 })?
8932 }
8933
8934 #[allow(clippy::type_complexity)]
8935 fn edits_from_lsp(
8936 &mut self,
8937 buffer: &Model<Buffer>,
8938 lsp_edits: impl 'static + Send + IntoIterator<Item = lsp::TextEdit>,
8939 server_id: LanguageServerId,
8940 version: Option<i32>,
8941 cx: &mut ModelContext<Self>,
8942 ) -> Task<Result<Vec<(Range<Anchor>, String)>>> {
8943 let snapshot = self.buffer_snapshot_for_lsp_version(buffer, server_id, version, cx);
8944 cx.background_executor().spawn(async move {
8945 let snapshot = snapshot?;
8946 let mut lsp_edits = lsp_edits
8947 .into_iter()
8948 .map(|edit| (range_from_lsp(edit.range), edit.new_text))
8949 .collect::<Vec<_>>();
8950 lsp_edits.sort_by_key(|(range, _)| range.start);
8951
8952 let mut lsp_edits = lsp_edits.into_iter().peekable();
8953 let mut edits = Vec::new();
8954 while let Some((range, mut new_text)) = lsp_edits.next() {
8955 // Clip invalid ranges provided by the language server.
8956 let mut range = snapshot.clip_point_utf16(range.start, Bias::Left)
8957 ..snapshot.clip_point_utf16(range.end, Bias::Left);
8958
8959 // Combine any LSP edits that are adjacent.
8960 //
8961 // Also, combine LSP edits that are separated from each other by only
8962 // a newline. This is important because for some code actions,
8963 // Rust-analyzer rewrites the entire buffer via a series of edits that
8964 // are separated by unchanged newline characters.
8965 //
8966 // In order for the diffing logic below to work properly, any edits that
8967 // cancel each other out must be combined into one.
8968 while let Some((next_range, next_text)) = lsp_edits.peek() {
8969 if next_range.start.0 > range.end {
8970 if next_range.start.0.row > range.end.row + 1
8971 || next_range.start.0.column > 0
8972 || snapshot.clip_point_utf16(
8973 Unclipped(PointUtf16::new(range.end.row, u32::MAX)),
8974 Bias::Left,
8975 ) > range.end
8976 {
8977 break;
8978 }
8979 new_text.push('\n');
8980 }
8981 range.end = snapshot.clip_point_utf16(next_range.end, Bias::Left);
8982 new_text.push_str(next_text);
8983 lsp_edits.next();
8984 }
8985
8986 // For multiline edits, perform a diff of the old and new text so that
8987 // we can identify the changes more precisely, preserving the locations
8988 // of any anchors positioned in the unchanged regions.
8989 if range.end.row > range.start.row {
8990 let mut offset = range.start.to_offset(&snapshot);
8991 let old_text = snapshot.text_for_range(range).collect::<String>();
8992
8993 let diff = TextDiff::from_lines(old_text.as_str(), &new_text);
8994 let mut moved_since_edit = true;
8995 for change in diff.iter_all_changes() {
8996 let tag = change.tag();
8997 let value = change.value();
8998 match tag {
8999 ChangeTag::Equal => {
9000 offset += value.len();
9001 moved_since_edit = true;
9002 }
9003 ChangeTag::Delete => {
9004 let start = snapshot.anchor_after(offset);
9005 let end = snapshot.anchor_before(offset + value.len());
9006 if moved_since_edit {
9007 edits.push((start..end, String::new()));
9008 } else {
9009 edits.last_mut().unwrap().0.end = end;
9010 }
9011 offset += value.len();
9012 moved_since_edit = false;
9013 }
9014 ChangeTag::Insert => {
9015 if moved_since_edit {
9016 let anchor = snapshot.anchor_after(offset);
9017 edits.push((anchor..anchor, value.to_string()));
9018 } else {
9019 edits.last_mut().unwrap().1.push_str(value);
9020 }
9021 moved_since_edit = false;
9022 }
9023 }
9024 }
9025 } else if range.end == range.start {
9026 let anchor = snapshot.anchor_after(range.start);
9027 edits.push((anchor..anchor, new_text));
9028 } else {
9029 let edit_start = snapshot.anchor_after(range.start);
9030 let edit_end = snapshot.anchor_before(range.end);
9031 edits.push((edit_start..edit_end, new_text));
9032 }
9033 }
9034
9035 Ok(edits)
9036 })
9037 }
9038
9039 fn buffer_snapshot_for_lsp_version(
9040 &mut self,
9041 buffer: &Model<Buffer>,
9042 server_id: LanguageServerId,
9043 version: Option<i32>,
9044 cx: &AppContext,
9045 ) -> Result<TextBufferSnapshot> {
9046 const OLD_VERSIONS_TO_RETAIN: i32 = 10;
9047
9048 if let Some(version) = version {
9049 let buffer_id = buffer.read(cx).remote_id();
9050 let snapshots = self
9051 .buffer_snapshots
9052 .get_mut(&buffer_id)
9053 .and_then(|m| m.get_mut(&server_id))
9054 .ok_or_else(|| {
9055 anyhow!("no snapshots found for buffer {buffer_id} and server {server_id}")
9056 })?;
9057
9058 let found_snapshot = snapshots
9059 .binary_search_by_key(&version, |e| e.version)
9060 .map(|ix| snapshots[ix].snapshot.clone())
9061 .map_err(|_| {
9062 anyhow!("snapshot not found for buffer {buffer_id} server {server_id} at version {version}")
9063 })?;
9064
9065 snapshots.retain(|snapshot| snapshot.version + OLD_VERSIONS_TO_RETAIN >= version);
9066 Ok(found_snapshot)
9067 } else {
9068 Ok((buffer.read(cx)).text_snapshot())
9069 }
9070 }
9071
9072 pub fn language_servers(
9073 &self,
9074 ) -> impl '_ + Iterator<Item = (LanguageServerId, LanguageServerName, WorktreeId)> {
9075 self.language_server_ids
9076 .iter()
9077 .map(|((worktree_id, server_name), server_id)| {
9078 (*server_id, server_name.clone(), *worktree_id)
9079 })
9080 }
9081
9082 pub fn supplementary_language_servers(
9083 &self,
9084 ) -> impl '_
9085 + Iterator<
9086 Item = (
9087 &LanguageServerId,
9088 &(LanguageServerName, Arc<LanguageServer>),
9089 ),
9090 > {
9091 self.supplementary_language_servers.iter()
9092 }
9093
9094 pub fn language_server_for_id(&self, id: LanguageServerId) -> Option<Arc<LanguageServer>> {
9095 if let Some(LanguageServerState::Running { server, .. }) = self.language_servers.get(&id) {
9096 Some(server.clone())
9097 } else if let Some((_, server)) = self.supplementary_language_servers.get(&id) {
9098 Some(Arc::clone(server))
9099 } else {
9100 None
9101 }
9102 }
9103
9104 pub fn language_servers_for_buffer(
9105 &self,
9106 buffer: &Buffer,
9107 cx: &AppContext,
9108 ) -> impl Iterator<Item = (&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
9109 self.language_server_ids_for_buffer(buffer, cx)
9110 .into_iter()
9111 .filter_map(|server_id| match self.language_servers.get(&server_id)? {
9112 LanguageServerState::Running {
9113 adapter, server, ..
9114 } => Some((adapter, server)),
9115 _ => None,
9116 })
9117 }
9118
9119 fn primary_language_server_for_buffer(
9120 &self,
9121 buffer: &Buffer,
9122 cx: &AppContext,
9123 ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
9124 self.language_servers_for_buffer(buffer, cx).next()
9125 }
9126
9127 pub fn language_server_for_buffer(
9128 &self,
9129 buffer: &Buffer,
9130 server_id: LanguageServerId,
9131 cx: &AppContext,
9132 ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
9133 self.language_servers_for_buffer(buffer, cx)
9134 .find(|(_, s)| s.server_id() == server_id)
9135 }
9136
9137 fn language_server_ids_for_buffer(
9138 &self,
9139 buffer: &Buffer,
9140 cx: &AppContext,
9141 ) -> Vec<LanguageServerId> {
9142 if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language()) {
9143 let worktree_id = file.worktree_id(cx);
9144 language
9145 .lsp_adapters()
9146 .iter()
9147 .flat_map(|adapter| {
9148 let key = (worktree_id, adapter.name.clone());
9149 self.language_server_ids.get(&key).copied()
9150 })
9151 .collect()
9152 } else {
9153 Vec::new()
9154 }
9155 }
9156}
9157
9158fn subscribe_for_copilot_events(
9159 copilot: &Model<Copilot>,
9160 cx: &mut ModelContext<'_, Project>,
9161) -> gpui::Subscription {
9162 cx.subscribe(
9163 copilot,
9164 |project, copilot, copilot_event, cx| match copilot_event {
9165 copilot::Event::CopilotLanguageServerStarted => {
9166 match copilot.read(cx).language_server() {
9167 Some((name, copilot_server)) => {
9168 // Another event wants to re-add the server that was already added and subscribed to, avoid doing it again.
9169 if !copilot_server.has_notification_handler::<copilot::request::LogMessage>() {
9170 let new_server_id = copilot_server.server_id();
9171 let weak_project = cx.weak_model();
9172 let copilot_log_subscription = copilot_server
9173 .on_notification::<copilot::request::LogMessage, _>(
9174 move |params, mut cx| {
9175 weak_project.update(&mut cx, |_, cx| {
9176 cx.emit(Event::LanguageServerLog(
9177 new_server_id,
9178 params.message,
9179 ));
9180 }).ok();
9181 },
9182 );
9183 project.supplementary_language_servers.insert(new_server_id, (name.clone(), Arc::clone(copilot_server)));
9184 project.copilot_log_subscription = Some(copilot_log_subscription);
9185 cx.emit(Event::LanguageServerAdded(new_server_id));
9186 }
9187 }
9188 None => debug_panic!("Received Copilot language server started event, but no language server is running"),
9189 }
9190 }
9191 },
9192 )
9193}
9194
9195fn glob_literal_prefix<'a>(glob: &'a str) -> &'a str {
9196 let mut literal_end = 0;
9197 for (i, part) in glob.split(path::MAIN_SEPARATOR).enumerate() {
9198 if part.contains(&['*', '?', '{', '}']) {
9199 break;
9200 } else {
9201 if i > 0 {
9202 // Account for separator prior to this part
9203 literal_end += path::MAIN_SEPARATOR.len_utf8();
9204 }
9205 literal_end += part.len();
9206 }
9207 }
9208 &glob[..literal_end]
9209}
9210
9211impl WorktreeHandle {
9212 pub fn upgrade(&self) -> Option<Model<Worktree>> {
9213 match self {
9214 WorktreeHandle::Strong(handle) => Some(handle.clone()),
9215 WorktreeHandle::Weak(handle) => handle.upgrade(),
9216 }
9217 }
9218
9219 pub fn handle_id(&self) -> usize {
9220 match self {
9221 WorktreeHandle::Strong(handle) => handle.entity_id().as_u64() as usize,
9222 WorktreeHandle::Weak(handle) => handle.entity_id().as_u64() as usize,
9223 }
9224 }
9225}
9226
9227impl OpenBuffer {
9228 pub fn upgrade(&self) -> Option<Model<Buffer>> {
9229 match self {
9230 OpenBuffer::Strong(handle) => Some(handle.clone()),
9231 OpenBuffer::Weak(handle) => handle.upgrade(),
9232 OpenBuffer::Operations(_) => None,
9233 }
9234 }
9235}
9236
9237pub struct PathMatchCandidateSet {
9238 pub snapshot: Snapshot,
9239 pub include_ignored: bool,
9240 pub include_root_name: bool,
9241}
9242
9243impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
9244 type Candidates = PathMatchCandidateSetIter<'a>;
9245
9246 fn id(&self) -> usize {
9247 self.snapshot.id().to_usize()
9248 }
9249
9250 fn len(&self) -> usize {
9251 if self.include_ignored {
9252 self.snapshot.file_count()
9253 } else {
9254 self.snapshot.visible_file_count()
9255 }
9256 }
9257
9258 fn prefix(&self) -> Arc<str> {
9259 if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
9260 self.snapshot.root_name().into()
9261 } else if self.include_root_name {
9262 format!("{}/", self.snapshot.root_name()).into()
9263 } else {
9264 "".into()
9265 }
9266 }
9267
9268 fn candidates(&'a self, start: usize) -> Self::Candidates {
9269 PathMatchCandidateSetIter {
9270 traversal: self.snapshot.files(self.include_ignored, start),
9271 }
9272 }
9273}
9274
9275pub struct PathMatchCandidateSetIter<'a> {
9276 traversal: Traversal<'a>,
9277}
9278
9279impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
9280 type Item = fuzzy::PathMatchCandidate<'a>;
9281
9282 fn next(&mut self) -> Option<Self::Item> {
9283 self.traversal.next().map(|entry| {
9284 if let EntryKind::File(char_bag) = entry.kind {
9285 fuzzy::PathMatchCandidate {
9286 path: &entry.path,
9287 char_bag,
9288 }
9289 } else {
9290 unreachable!()
9291 }
9292 })
9293 }
9294}
9295
9296impl EventEmitter<Event> for Project {}
9297
9298impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
9299 fn from((worktree_id, path): (WorktreeId, P)) -> Self {
9300 Self {
9301 worktree_id,
9302 path: path.as_ref().into(),
9303 }
9304 }
9305}
9306
9307struct ProjectLspAdapterDelegate {
9308 project: Model<Project>,
9309 worktree: Model<Worktree>,
9310 http_client: Arc<dyn HttpClient>,
9311}
9312
9313impl ProjectLspAdapterDelegate {
9314 fn new(project: &Project, worktree: &Model<Worktree>, cx: &ModelContext<Project>) -> Arc<Self> {
9315 Arc::new(Self {
9316 project: cx.handle(),
9317 worktree: worktree.clone(),
9318 http_client: project.client.http_client(),
9319 })
9320 }
9321}
9322
9323impl LspAdapterDelegate for ProjectLspAdapterDelegate {
9324 fn show_notification(&self, message: &str, cx: &mut AppContext) {
9325 self.project
9326 .update(cx, |_, cx| cx.emit(Event::Notification(message.to_owned())));
9327 }
9328
9329 fn http_client(&self) -> Arc<dyn HttpClient> {
9330 self.http_client.clone()
9331 }
9332
9333 fn which_command(
9334 &self,
9335 command: OsString,
9336 cx: &AppContext,
9337 ) -> Task<Option<(PathBuf, HashMap<String, String>)>> {
9338 let worktree_abs_path = self.worktree.read(cx).abs_path();
9339 let command = command.to_owned();
9340
9341 cx.background_executor().spawn(async move {
9342 let shell_env = load_shell_environment(&worktree_abs_path)
9343 .await
9344 .with_context(|| {
9345 format!(
9346 "failed to determine load login shell environment in {worktree_abs_path:?}"
9347 )
9348 })
9349 .log_err();
9350
9351 if let Some(shell_env) = shell_env {
9352 let shell_path = shell_env.get("PATH");
9353 match which::which_in(&command, shell_path, &worktree_abs_path) {
9354 Ok(command_path) => Some((command_path, shell_env)),
9355 Err(error) => {
9356 log::warn!(
9357 "failed to determine path for command {:?} in shell PATH {:?}: {error}",
9358 command.to_string_lossy(),
9359 shell_path.map(String::as_str).unwrap_or("")
9360 );
9361 None
9362 }
9363 }
9364 } else {
9365 None
9366 }
9367 })
9368 }
9369}
9370
9371fn serialize_symbol(symbol: &Symbol) -> proto::Symbol {
9372 proto::Symbol {
9373 language_server_name: symbol.language_server_name.0.to_string(),
9374 source_worktree_id: symbol.source_worktree_id.to_proto(),
9375 worktree_id: symbol.path.worktree_id.to_proto(),
9376 path: symbol.path.path.to_string_lossy().to_string(),
9377 name: symbol.name.clone(),
9378 kind: unsafe { mem::transmute(symbol.kind) },
9379 start: Some(proto::PointUtf16 {
9380 row: symbol.range.start.0.row,
9381 column: symbol.range.start.0.column,
9382 }),
9383 end: Some(proto::PointUtf16 {
9384 row: symbol.range.end.0.row,
9385 column: symbol.range.end.0.column,
9386 }),
9387 signature: symbol.signature.to_vec(),
9388 }
9389}
9390
9391fn relativize_path(base: &Path, path: &Path) -> PathBuf {
9392 let mut path_components = path.components();
9393 let mut base_components = base.components();
9394 let mut components: Vec<Component> = Vec::new();
9395 loop {
9396 match (path_components.next(), base_components.next()) {
9397 (None, None) => break,
9398 (Some(a), None) => {
9399 components.push(a);
9400 components.extend(path_components.by_ref());
9401 break;
9402 }
9403 (None, _) => components.push(Component::ParentDir),
9404 (Some(a), Some(b)) if components.is_empty() && a == b => (),
9405 (Some(a), Some(b)) if b == Component::CurDir => components.push(a),
9406 (Some(a), Some(_)) => {
9407 components.push(Component::ParentDir);
9408 for _ in base_components {
9409 components.push(Component::ParentDir);
9410 }
9411 components.push(a);
9412 components.extend(path_components.by_ref());
9413 break;
9414 }
9415 }
9416 }
9417 components.iter().map(|c| c.as_os_str()).collect()
9418}
9419
9420fn resolve_path(base: &Path, path: &Path) -> PathBuf {
9421 let mut result = base.to_path_buf();
9422 for component in path.components() {
9423 match component {
9424 Component::ParentDir => {
9425 result.pop();
9426 }
9427 Component::CurDir => (),
9428 _ => result.push(component),
9429 }
9430 }
9431 result
9432}
9433
9434impl Item for Buffer {
9435 fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
9436 File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
9437 }
9438
9439 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
9440 File::from_dyn(self.file()).map(|file| ProjectPath {
9441 worktree_id: file.worktree_id(cx),
9442 path: file.path().clone(),
9443 })
9444 }
9445}
9446
9447async fn wait_for_loading_buffer(
9448 mut receiver: postage::watch::Receiver<Option<Result<Model<Buffer>, Arc<anyhow::Error>>>>,
9449) -> Result<Model<Buffer>, Arc<anyhow::Error>> {
9450 loop {
9451 if let Some(result) = receiver.borrow().as_ref() {
9452 match result {
9453 Ok(buffer) => return Ok(buffer.to_owned()),
9454 Err(e) => return Err(e.to_owned()),
9455 }
9456 }
9457 receiver.next().await;
9458 }
9459}
9460
9461fn include_text(server: &lsp::LanguageServer) -> bool {
9462 server
9463 .capabilities()
9464 .text_document_sync
9465 .as_ref()
9466 .and_then(|sync| match sync {
9467 lsp::TextDocumentSyncCapability::Kind(_) => None,
9468 lsp::TextDocumentSyncCapability::Options(options) => options.save.as_ref(),
9469 })
9470 .and_then(|save_options| match save_options {
9471 lsp::TextDocumentSyncSaveOptions::Supported(_) => None,
9472 lsp::TextDocumentSyncSaveOptions::SaveOptions(options) => options.include_text,
9473 })
9474 .unwrap_or(false)
9475}
9476
9477async fn load_shell_environment(dir: &Path) -> Result<HashMap<String, String>> {
9478 let marker = "ZED_SHELL_START";
9479 let shell = env::var("SHELL").context(
9480 "SHELL environment variable is not assigned so we can't source login environment variables",
9481 )?;
9482 let output = smol::process::Command::new(&shell)
9483 .args([
9484 "-i",
9485 "-c",
9486 // What we're doing here is to spawn a shell and then `cd` into
9487 // the project directory to get the env in there as if the user
9488 // `cd`'d into it. We do that because tools like direnv, asdf, ...
9489 // hook into `cd` and only set up the env after that.
9490 //
9491 // The `exit 0` is the result of hours of debugging, trying to find out
9492 // why running this command here, without `exit 0`, would mess
9493 // up signal process for our process so that `ctrl-c` doesn't work
9494 // anymore.
9495 // We still don't know why `$SHELL -l -i -c '/usr/bin/env -0'` would
9496 // do that, but it does, and `exit 0` helps.
9497 &format!("cd {dir:?}; echo {marker}; /usr/bin/env -0; exit 0;"),
9498 ])
9499 .output()
9500 .await
9501 .context("failed to spawn login shell to source login environment variables")?;
9502
9503 anyhow::ensure!(
9504 output.status.success(),
9505 "login shell exited with error {:?}",
9506 output.status
9507 );
9508
9509 let stdout = String::from_utf8_lossy(&output.stdout);
9510 let env_output_start = stdout.find(marker).ok_or_else(|| {
9511 anyhow!(
9512 "failed to parse output of `env` command in login shell: {}",
9513 stdout
9514 )
9515 })?;
9516
9517 let mut parsed_env = HashMap::default();
9518 let env_output = &stdout[env_output_start + marker.len()..];
9519 for line in env_output.split_terminator('\0') {
9520 if let Some(separator_index) = line.find('=') {
9521 let key = line[..separator_index].to_string();
9522 let value = line[separator_index + 1..].to_string();
9523 parsed_env.insert(key, value);
9524 }
9525 }
9526 Ok(parsed_env)
9527}