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