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