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