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