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