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