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