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