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 let this = match this.upgrade(cx) {
2713 Some(this) => this,
2714 None => return Err(anyhow!("failed to upgrade project handle")),
2715 };
2716
2717 this.update(cx, |this, cx| {
2718 this.insert_newly_running_language_server(
2719 language,
2720 adapter,
2721 language_server.clone(),
2722 server_id,
2723 key,
2724 cx,
2725 )
2726 })?;
2727
2728 Ok(Some(language_server))
2729 }
2730
2731 async fn setup_pending_language_server(
2732 this: WeakModelHandle<Self>,
2733 initialization_options: Option<serde_json::Value>,
2734 pending_server: PendingLanguageServer,
2735 adapter: Arc<CachedLspAdapter>,
2736 languages: Arc<LanguageRegistry>,
2737 server_id: LanguageServerId,
2738 cx: &mut AsyncAppContext,
2739 ) -> Result<Option<Arc<LanguageServer>>> {
2740 let workspace_config = cx.update(|cx| languages.workspace_configuration(cx)).await;
2741 let language_server = match pending_server.task.await? {
2742 Some(server) => server.initialize(initialization_options).await?,
2743 None => {
2744 return Ok(None);
2745 }
2746 };
2747
2748 language_server
2749 .on_notification::<lsp::notification::LogMessage, _>({
2750 move |params, mut cx| {
2751 if let Some(this) = this.upgrade(&cx) {
2752 this.update(&mut cx, |_, cx| {
2753 cx.emit(Event::LanguageServerLog(server_id, params.message))
2754 });
2755 }
2756 }
2757 })
2758 .detach();
2759
2760 language_server
2761 .on_notification::<lsp::notification::PublishDiagnostics, _>({
2762 let adapter = adapter.clone();
2763 move |mut params, cx| {
2764 let this = this;
2765 let adapter = adapter.clone();
2766 cx.spawn(|mut cx| async move {
2767 adapter.process_diagnostics(&mut params).await;
2768 if let Some(this) = this.upgrade(&cx) {
2769 this.update(&mut cx, |this, cx| {
2770 this.update_diagnostics(
2771 server_id,
2772 params,
2773 &adapter.disk_based_diagnostic_sources,
2774 cx,
2775 )
2776 .log_err();
2777 });
2778 }
2779 })
2780 .detach();
2781 }
2782 })
2783 .detach();
2784
2785 language_server
2786 .on_request::<lsp::request::WorkspaceConfiguration, _, _>({
2787 let languages = languages.clone();
2788 move |params, mut cx| {
2789 let languages = languages.clone();
2790 async move {
2791 let workspace_config =
2792 cx.update(|cx| languages.workspace_configuration(cx)).await;
2793 Ok(params
2794 .items
2795 .into_iter()
2796 .map(|item| {
2797 if let Some(section) = &item.section {
2798 workspace_config
2799 .get(section)
2800 .cloned()
2801 .unwrap_or(serde_json::Value::Null)
2802 } else {
2803 workspace_config.clone()
2804 }
2805 })
2806 .collect())
2807 }
2808 }
2809 })
2810 .detach();
2811
2812 // Even though we don't have handling for these requests, respond to them to
2813 // avoid stalling any language server like `gopls` which waits for a response
2814 // to these requests when initializing.
2815 language_server
2816 .on_request::<lsp::request::WorkDoneProgressCreate, _, _>(
2817 move |params, mut cx| async move {
2818 if let Some(this) = this.upgrade(&cx) {
2819 this.update(&mut cx, |this, _| {
2820 if let Some(status) = this.language_server_statuses.get_mut(&server_id)
2821 {
2822 if let lsp::NumberOrString::String(token) = params.token {
2823 status.progress_tokens.insert(token);
2824 }
2825 }
2826 });
2827 }
2828 Ok(())
2829 },
2830 )
2831 .detach();
2832 language_server
2833 .on_request::<lsp::request::RegisterCapability, _, _>({
2834 move |params, mut cx| async move {
2835 let this = this
2836 .upgrade(&cx)
2837 .ok_or_else(|| anyhow!("project dropped"))?;
2838 for reg in params.registrations {
2839 if reg.method == "workspace/didChangeWatchedFiles" {
2840 if let Some(options) = reg.register_options {
2841 let options = serde_json::from_value(options)?;
2842 this.update(&mut cx, |this, cx| {
2843 this.on_lsp_did_change_watched_files(server_id, options, cx);
2844 });
2845 }
2846 }
2847 }
2848 Ok(())
2849 }
2850 })
2851 .detach();
2852
2853 language_server
2854 .on_request::<lsp::request::ApplyWorkspaceEdit, _, _>({
2855 let adapter = adapter.clone();
2856 move |params, cx| {
2857 Self::on_lsp_workspace_edit(this, params, server_id, adapter.clone(), cx)
2858 }
2859 })
2860 .detach();
2861
2862 language_server
2863 .on_request::<lsp::request::InlayHintRefreshRequest, _, _>({
2864 move |(), mut cx| async move {
2865 let this = this
2866 .upgrade(&cx)
2867 .ok_or_else(|| anyhow!("project dropped"))?;
2868 this.update(&mut cx, |project, cx| {
2869 cx.emit(Event::RefreshInlays);
2870 project.remote_id().map(|project_id| {
2871 project.client.send(proto::RefreshInlayHints { project_id })
2872 })
2873 })
2874 .transpose()?;
2875 Ok(())
2876 }
2877 })
2878 .detach();
2879
2880 let disk_based_diagnostics_progress_token =
2881 adapter.disk_based_diagnostics_progress_token.clone();
2882
2883 language_server
2884 .on_notification::<lsp::notification::Progress, _>(move |params, mut cx| {
2885 if let Some(this) = this.upgrade(&cx) {
2886 this.update(&mut cx, |this, cx| {
2887 this.on_lsp_progress(
2888 params,
2889 server_id,
2890 disk_based_diagnostics_progress_token.clone(),
2891 cx,
2892 );
2893 });
2894 }
2895 })
2896 .detach();
2897
2898 language_server
2899 .notify::<lsp::notification::DidChangeConfiguration>(
2900 lsp::DidChangeConfigurationParams {
2901 settings: workspace_config,
2902 },
2903 )
2904 .ok();
2905
2906 Ok(Some(language_server))
2907 }
2908
2909 fn insert_newly_running_language_server(
2910 &mut self,
2911 language: Arc<Language>,
2912 adapter: Arc<CachedLspAdapter>,
2913 language_server: Arc<LanguageServer>,
2914 server_id: LanguageServerId,
2915 key: (WorktreeId, LanguageServerName),
2916 cx: &mut ModelContext<Self>,
2917 ) -> Result<()> {
2918 // If the language server for this key doesn't match the server id, don't store the
2919 // server. Which will cause it to be dropped, killing the process
2920 if self
2921 .language_server_ids
2922 .get(&key)
2923 .map(|id| id != &server_id)
2924 .unwrap_or(false)
2925 {
2926 return Ok(());
2927 }
2928
2929 // Update language_servers collection with Running variant of LanguageServerState
2930 // indicating that the server is up and running and ready
2931 self.language_servers.insert(
2932 server_id,
2933 LanguageServerState::Running {
2934 adapter: adapter.clone(),
2935 language: language.clone(),
2936 watched_paths: Default::default(),
2937 server: language_server.clone(),
2938 simulate_disk_based_diagnostics_completion: None,
2939 },
2940 );
2941
2942 self.language_server_statuses.insert(
2943 server_id,
2944 LanguageServerStatus {
2945 name: language_server.name().to_string(),
2946 pending_work: Default::default(),
2947 has_pending_diagnostic_updates: false,
2948 progress_tokens: Default::default(),
2949 },
2950 );
2951
2952 cx.emit(Event::LanguageServerAdded(server_id));
2953
2954 if let Some(project_id) = self.remote_id() {
2955 self.client.send(proto::StartLanguageServer {
2956 project_id,
2957 server: Some(proto::LanguageServer {
2958 id: server_id.0 as u64,
2959 name: language_server.name().to_string(),
2960 }),
2961 })?;
2962 }
2963
2964 // Tell the language server about every open buffer in the worktree that matches the language.
2965 for buffer in self.opened_buffers.values() {
2966 if let Some(buffer_handle) = buffer.upgrade(cx) {
2967 let buffer = buffer_handle.read(cx);
2968 let file = match File::from_dyn(buffer.file()) {
2969 Some(file) => file,
2970 None => continue,
2971 };
2972 let language = match buffer.language() {
2973 Some(language) => language,
2974 None => continue,
2975 };
2976
2977 if file.worktree.read(cx).id() != key.0
2978 || !language.lsp_adapters().iter().any(|a| a.name == key.1)
2979 {
2980 continue;
2981 }
2982
2983 let file = match file.as_local() {
2984 Some(file) => file,
2985 None => continue,
2986 };
2987
2988 let versions = self
2989 .buffer_snapshots
2990 .entry(buffer.remote_id())
2991 .or_default()
2992 .entry(server_id)
2993 .or_insert_with(|| {
2994 vec![LspBufferSnapshot {
2995 version: 0,
2996 snapshot: buffer.text_snapshot(),
2997 }]
2998 });
2999
3000 let snapshot = versions.last().unwrap();
3001 let version = snapshot.version;
3002 let initial_snapshot = &snapshot.snapshot;
3003 let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
3004 language_server.notify::<lsp::notification::DidOpenTextDocument>(
3005 lsp::DidOpenTextDocumentParams {
3006 text_document: lsp::TextDocumentItem::new(
3007 uri,
3008 adapter
3009 .language_ids
3010 .get(language.name().as_ref())
3011 .cloned()
3012 .unwrap_or_default(),
3013 version,
3014 initial_snapshot.text(),
3015 ),
3016 },
3017 )?;
3018
3019 buffer_handle.update(cx, |buffer, cx| {
3020 buffer.set_completion_triggers(
3021 language_server
3022 .capabilities()
3023 .completion_provider
3024 .as_ref()
3025 .and_then(|provider| provider.trigger_characters.clone())
3026 .unwrap_or_default(),
3027 cx,
3028 )
3029 });
3030 }
3031 }
3032
3033 cx.notify();
3034 Ok(())
3035 }
3036
3037 // Returns a list of all of the worktrees which no longer have a language server and the root path
3038 // for the stopped server
3039 fn stop_language_server(
3040 &mut self,
3041 worktree_id: WorktreeId,
3042 adapter_name: LanguageServerName,
3043 cx: &mut ModelContext<Self>,
3044 ) -> Task<(Option<PathBuf>, Vec<WorktreeId>)> {
3045 let key = (worktree_id, adapter_name);
3046 if let Some(server_id) = self.language_server_ids.remove(&key) {
3047 log::info!("stopping language server {}", key.1 .0);
3048
3049 // Remove other entries for this language server as well
3050 let mut orphaned_worktrees = vec![worktree_id];
3051 let other_keys = self.language_server_ids.keys().cloned().collect::<Vec<_>>();
3052 for other_key in other_keys {
3053 if self.language_server_ids.get(&other_key) == Some(&server_id) {
3054 self.language_server_ids.remove(&other_key);
3055 orphaned_worktrees.push(other_key.0);
3056 }
3057 }
3058
3059 for buffer in self.opened_buffers.values() {
3060 if let Some(buffer) = buffer.upgrade(cx) {
3061 buffer.update(cx, |buffer, cx| {
3062 buffer.update_diagnostics(server_id, Default::default(), cx);
3063 });
3064 }
3065 }
3066 for worktree in &self.worktrees {
3067 if let Some(worktree) = worktree.upgrade(cx) {
3068 worktree.update(cx, |worktree, cx| {
3069 if let Some(worktree) = worktree.as_local_mut() {
3070 worktree.clear_diagnostics_for_language_server(server_id, cx);
3071 }
3072 });
3073 }
3074 }
3075
3076 self.language_server_statuses.remove(&server_id);
3077 cx.notify();
3078
3079 let server_state = self.language_servers.remove(&server_id);
3080 cx.emit(Event::LanguageServerRemoved(server_id));
3081 cx.spawn_weak(|this, mut cx| async move {
3082 let mut root_path = None;
3083
3084 let server = match server_state {
3085 Some(LanguageServerState::Starting(task)) => task.await,
3086 Some(LanguageServerState::Running { server, .. }) => Some(server),
3087 None => None,
3088 };
3089
3090 if let Some(server) = server {
3091 root_path = Some(server.root_path().clone());
3092 if let Some(shutdown) = server.shutdown() {
3093 shutdown.await;
3094 }
3095 }
3096
3097 if let Some(this) = this.upgrade(&cx) {
3098 this.update(&mut cx, |this, cx| {
3099 this.language_server_statuses.remove(&server_id);
3100 cx.notify();
3101 });
3102 }
3103
3104 (root_path, orphaned_worktrees)
3105 })
3106 } else {
3107 Task::ready((None, Vec::new()))
3108 }
3109 }
3110
3111 pub fn restart_language_servers_for_buffers(
3112 &mut self,
3113 buffers: impl IntoIterator<Item = ModelHandle<Buffer>>,
3114 cx: &mut ModelContext<Self>,
3115 ) -> Option<()> {
3116 let language_server_lookup_info: HashSet<(ModelHandle<Worktree>, Arc<Language>)> = buffers
3117 .into_iter()
3118 .filter_map(|buffer| {
3119 let buffer = buffer.read(cx);
3120 let file = File::from_dyn(buffer.file())?;
3121 let full_path = file.full_path(cx);
3122 let language = self
3123 .languages
3124 .language_for_file(&full_path, Some(buffer.as_rope()))
3125 .now_or_never()?
3126 .ok()?;
3127 Some((file.worktree.clone(), language))
3128 })
3129 .collect();
3130 for (worktree, language) in language_server_lookup_info {
3131 self.restart_language_servers(worktree, language, cx);
3132 }
3133
3134 None
3135 }
3136
3137 // TODO This will break in the case where the adapter's root paths and worktrees are not equal
3138 fn restart_language_servers(
3139 &mut self,
3140 worktree: ModelHandle<Worktree>,
3141 language: Arc<Language>,
3142 cx: &mut ModelContext<Self>,
3143 ) {
3144 let worktree_id = worktree.read(cx).id();
3145 let fallback_path = worktree.read(cx).abs_path();
3146
3147 let mut stops = Vec::new();
3148 for adapter in language.lsp_adapters() {
3149 stops.push(self.stop_language_server(worktree_id, adapter.name.clone(), cx));
3150 }
3151
3152 if stops.is_empty() {
3153 return;
3154 }
3155 let mut stops = stops.into_iter();
3156
3157 cx.spawn_weak(|this, mut cx| async move {
3158 let (original_root_path, mut orphaned_worktrees) = stops.next().unwrap().await;
3159 for stop in stops {
3160 let (_, worktrees) = stop.await;
3161 orphaned_worktrees.extend_from_slice(&worktrees);
3162 }
3163
3164 let this = match this.upgrade(&cx) {
3165 Some(this) => this,
3166 None => return,
3167 };
3168
3169 this.update(&mut cx, |this, cx| {
3170 // Attempt to restart using original server path. Fallback to passed in
3171 // path if we could not retrieve the root path
3172 let root_path = original_root_path
3173 .map(|path_buf| Arc::from(path_buf.as_path()))
3174 .unwrap_or(fallback_path);
3175
3176 this.start_language_servers(&worktree, root_path, language.clone(), cx);
3177
3178 // Lookup new server ids and set them for each of the orphaned worktrees
3179 for adapter in language.lsp_adapters() {
3180 if let Some(new_server_id) = this
3181 .language_server_ids
3182 .get(&(worktree_id, adapter.name.clone()))
3183 .cloned()
3184 {
3185 for &orphaned_worktree in &orphaned_worktrees {
3186 this.language_server_ids
3187 .insert((orphaned_worktree, adapter.name.clone()), new_server_id);
3188 }
3189 }
3190 }
3191 });
3192 })
3193 .detach();
3194 }
3195
3196 fn check_errored_server(
3197 language: Arc<Language>,
3198 adapter: Arc<CachedLspAdapter>,
3199 server_id: LanguageServerId,
3200 installation_test_binary: Option<LanguageServerBinary>,
3201 cx: &mut ModelContext<Self>,
3202 ) {
3203 if !adapter.can_be_reinstalled() {
3204 log::info!(
3205 "Validation check requested for {:?} but it cannot be reinstalled",
3206 adapter.name.0
3207 );
3208 return;
3209 }
3210
3211 cx.spawn(|this, mut cx| async move {
3212 log::info!("About to spawn test binary");
3213
3214 // A lack of test binary counts as a failure
3215 let process = installation_test_binary.and_then(|binary| {
3216 smol::process::Command::new(&binary.path)
3217 .current_dir(&binary.path)
3218 .args(binary.arguments)
3219 .stdin(Stdio::piped())
3220 .stdout(Stdio::piped())
3221 .stderr(Stdio::inherit())
3222 .kill_on_drop(true)
3223 .spawn()
3224 .ok()
3225 });
3226
3227 const PROCESS_TIMEOUT: Duration = Duration::from_secs(5);
3228 let mut timeout = cx.background().timer(PROCESS_TIMEOUT).fuse();
3229
3230 let mut errored = false;
3231 if let Some(mut process) = process {
3232 futures::select! {
3233 status = process.status().fuse() => match status {
3234 Ok(status) => errored = !status.success(),
3235 Err(_) => errored = true,
3236 },
3237
3238 _ = timeout => {
3239 log::info!("test binary time-ed out, this counts as a success");
3240 _ = process.kill();
3241 }
3242 }
3243 } else {
3244 log::warn!("test binary failed to launch");
3245 errored = true;
3246 }
3247
3248 if errored {
3249 log::warn!("test binary check failed");
3250 let task = this.update(&mut cx, move |this, mut cx| {
3251 this.reinstall_language_server(language, adapter, server_id, &mut cx)
3252 });
3253
3254 if let Some(task) = task {
3255 task.await;
3256 }
3257 }
3258 })
3259 .detach();
3260 }
3261
3262 fn on_lsp_progress(
3263 &mut self,
3264 progress: lsp::ProgressParams,
3265 language_server_id: LanguageServerId,
3266 disk_based_diagnostics_progress_token: Option<String>,
3267 cx: &mut ModelContext<Self>,
3268 ) {
3269 let token = match progress.token {
3270 lsp::NumberOrString::String(token) => token,
3271 lsp::NumberOrString::Number(token) => {
3272 log::info!("skipping numeric progress token {}", token);
3273 return;
3274 }
3275 };
3276 let lsp::ProgressParamsValue::WorkDone(progress) = progress.value;
3277 let language_server_status =
3278 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
3279 status
3280 } else {
3281 return;
3282 };
3283
3284 if !language_server_status.progress_tokens.contains(&token) {
3285 return;
3286 }
3287
3288 let is_disk_based_diagnostics_progress = disk_based_diagnostics_progress_token
3289 .as_ref()
3290 .map_or(false, |disk_based_token| {
3291 token.starts_with(disk_based_token)
3292 });
3293
3294 match progress {
3295 lsp::WorkDoneProgress::Begin(report) => {
3296 if is_disk_based_diagnostics_progress {
3297 language_server_status.has_pending_diagnostic_updates = true;
3298 self.disk_based_diagnostics_started(language_server_id, cx);
3299 self.buffer_ordered_messages_tx
3300 .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
3301 language_server_id,
3302 message: proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(Default::default())
3303 })
3304 .ok();
3305 } else {
3306 self.on_lsp_work_start(
3307 language_server_id,
3308 token.clone(),
3309 LanguageServerProgress {
3310 message: report.message.clone(),
3311 percentage: report.percentage.map(|p| p as usize),
3312 last_update_at: Instant::now(),
3313 },
3314 cx,
3315 );
3316 self.buffer_ordered_messages_tx
3317 .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
3318 language_server_id,
3319 message: proto::update_language_server::Variant::WorkStart(
3320 proto::LspWorkStart {
3321 token,
3322 message: report.message,
3323 percentage: report.percentage.map(|p| p as u32),
3324 },
3325 ),
3326 })
3327 .ok();
3328 }
3329 }
3330 lsp::WorkDoneProgress::Report(report) => {
3331 if !is_disk_based_diagnostics_progress {
3332 self.on_lsp_work_progress(
3333 language_server_id,
3334 token.clone(),
3335 LanguageServerProgress {
3336 message: report.message.clone(),
3337 percentage: report.percentage.map(|p| p as usize),
3338 last_update_at: Instant::now(),
3339 },
3340 cx,
3341 );
3342 self.buffer_ordered_messages_tx
3343 .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
3344 language_server_id,
3345 message: proto::update_language_server::Variant::WorkProgress(
3346 proto::LspWorkProgress {
3347 token,
3348 message: report.message,
3349 percentage: report.percentage.map(|p| p as u32),
3350 },
3351 ),
3352 })
3353 .ok();
3354 }
3355 }
3356 lsp::WorkDoneProgress::End(_) => {
3357 language_server_status.progress_tokens.remove(&token);
3358
3359 if is_disk_based_diagnostics_progress {
3360 language_server_status.has_pending_diagnostic_updates = false;
3361 self.disk_based_diagnostics_finished(language_server_id, cx);
3362 self.buffer_ordered_messages_tx
3363 .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
3364 language_server_id,
3365 message:
3366 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
3367 Default::default(),
3368 ),
3369 })
3370 .ok();
3371 } else {
3372 self.on_lsp_work_end(language_server_id, token.clone(), cx);
3373 self.buffer_ordered_messages_tx
3374 .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
3375 language_server_id,
3376 message: proto::update_language_server::Variant::WorkEnd(
3377 proto::LspWorkEnd { token },
3378 ),
3379 })
3380 .ok();
3381 }
3382 }
3383 }
3384 }
3385
3386 fn on_lsp_work_start(
3387 &mut self,
3388 language_server_id: LanguageServerId,
3389 token: String,
3390 progress: LanguageServerProgress,
3391 cx: &mut ModelContext<Self>,
3392 ) {
3393 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
3394 status.pending_work.insert(token, progress);
3395 cx.notify();
3396 }
3397 }
3398
3399 fn on_lsp_work_progress(
3400 &mut self,
3401 language_server_id: LanguageServerId,
3402 token: String,
3403 progress: LanguageServerProgress,
3404 cx: &mut ModelContext<Self>,
3405 ) {
3406 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
3407 let entry = status
3408 .pending_work
3409 .entry(token)
3410 .or_insert(LanguageServerProgress {
3411 message: Default::default(),
3412 percentage: Default::default(),
3413 last_update_at: progress.last_update_at,
3414 });
3415 if progress.message.is_some() {
3416 entry.message = progress.message;
3417 }
3418 if progress.percentage.is_some() {
3419 entry.percentage = progress.percentage;
3420 }
3421 entry.last_update_at = progress.last_update_at;
3422 cx.notify();
3423 }
3424 }
3425
3426 fn on_lsp_work_end(
3427 &mut self,
3428 language_server_id: LanguageServerId,
3429 token: String,
3430 cx: &mut ModelContext<Self>,
3431 ) {
3432 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
3433 cx.emit(Event::RefreshInlays);
3434 status.pending_work.remove(&token);
3435 cx.notify();
3436 }
3437 }
3438
3439 fn on_lsp_did_change_watched_files(
3440 &mut self,
3441 language_server_id: LanguageServerId,
3442 params: DidChangeWatchedFilesRegistrationOptions,
3443 cx: &mut ModelContext<Self>,
3444 ) {
3445 if let Some(LanguageServerState::Running { watched_paths, .. }) =
3446 self.language_servers.get_mut(&language_server_id)
3447 {
3448 let mut builders = HashMap::default();
3449 for watcher in params.watchers {
3450 for worktree in &self.worktrees {
3451 if let Some(worktree) = worktree.upgrade(cx) {
3452 let glob_is_inside_worktree = worktree.update(cx, |tree, _| {
3453 if let Some(abs_path) = tree.abs_path().to_str() {
3454 let relative_glob_pattern = match &watcher.glob_pattern {
3455 lsp::GlobPattern::String(s) => s
3456 .strip_prefix(abs_path)
3457 .and_then(|s| s.strip_prefix(std::path::MAIN_SEPARATOR)),
3458 lsp::GlobPattern::Relative(rp) => {
3459 let base_uri = match &rp.base_uri {
3460 lsp::OneOf::Left(workspace_folder) => {
3461 &workspace_folder.uri
3462 }
3463 lsp::OneOf::Right(base_uri) => base_uri,
3464 };
3465 base_uri.to_file_path().ok().and_then(|file_path| {
3466 (file_path.to_str() == Some(abs_path))
3467 .then_some(rp.pattern.as_str())
3468 })
3469 }
3470 };
3471 if let Some(relative_glob_pattern) = relative_glob_pattern {
3472 let literal_prefix =
3473 glob_literal_prefix(&relative_glob_pattern);
3474 tree.as_local_mut()
3475 .unwrap()
3476 .add_path_prefix_to_scan(Path::new(literal_prefix).into());
3477 if let Some(glob) = Glob::new(relative_glob_pattern).log_err() {
3478 builders
3479 .entry(tree.id())
3480 .or_insert_with(|| GlobSetBuilder::new())
3481 .add(glob);
3482 }
3483 return true;
3484 }
3485 }
3486 false
3487 });
3488 if glob_is_inside_worktree {
3489 break;
3490 }
3491 }
3492 }
3493 }
3494
3495 watched_paths.clear();
3496 for (worktree_id, builder) in builders {
3497 if let Ok(globset) = builder.build() {
3498 watched_paths.insert(worktree_id, globset);
3499 }
3500 }
3501
3502 cx.notify();
3503 }
3504 }
3505
3506 async fn on_lsp_workspace_edit(
3507 this: WeakModelHandle<Self>,
3508 params: lsp::ApplyWorkspaceEditParams,
3509 server_id: LanguageServerId,
3510 adapter: Arc<CachedLspAdapter>,
3511 mut cx: AsyncAppContext,
3512 ) -> Result<lsp::ApplyWorkspaceEditResponse> {
3513 let this = this
3514 .upgrade(&cx)
3515 .ok_or_else(|| anyhow!("project project closed"))?;
3516 let language_server = this
3517 .read_with(&cx, |this, _| this.language_server_for_id(server_id))
3518 .ok_or_else(|| anyhow!("language server not found"))?;
3519 let transaction = Self::deserialize_workspace_edit(
3520 this.clone(),
3521 params.edit,
3522 true,
3523 adapter.clone(),
3524 language_server.clone(),
3525 &mut cx,
3526 )
3527 .await
3528 .log_err();
3529 this.update(&mut cx, |this, _| {
3530 if let Some(transaction) = transaction {
3531 this.last_workspace_edits_by_language_server
3532 .insert(server_id, transaction);
3533 }
3534 });
3535 Ok(lsp::ApplyWorkspaceEditResponse {
3536 applied: true,
3537 failed_change: None,
3538 failure_reason: None,
3539 })
3540 }
3541
3542 pub fn language_server_statuses(
3543 &self,
3544 ) -> impl DoubleEndedIterator<Item = &LanguageServerStatus> {
3545 self.language_server_statuses.values()
3546 }
3547
3548 pub fn update_diagnostics(
3549 &mut self,
3550 language_server_id: LanguageServerId,
3551 mut params: lsp::PublishDiagnosticsParams,
3552 disk_based_sources: &[String],
3553 cx: &mut ModelContext<Self>,
3554 ) -> Result<()> {
3555 let abs_path = params
3556 .uri
3557 .to_file_path()
3558 .map_err(|_| anyhow!("URI is not a file"))?;
3559 let mut diagnostics = Vec::default();
3560 let mut primary_diagnostic_group_ids = HashMap::default();
3561 let mut sources_by_group_id = HashMap::default();
3562 let mut supporting_diagnostics = HashMap::default();
3563
3564 // Ensure that primary diagnostics are always the most severe
3565 params.diagnostics.sort_by_key(|item| item.severity);
3566
3567 for diagnostic in ¶ms.diagnostics {
3568 let source = diagnostic.source.as_ref();
3569 let code = diagnostic.code.as_ref().map(|code| match code {
3570 lsp::NumberOrString::Number(code) => code.to_string(),
3571 lsp::NumberOrString::String(code) => code.clone(),
3572 });
3573 let range = range_from_lsp(diagnostic.range);
3574 let is_supporting = diagnostic
3575 .related_information
3576 .as_ref()
3577 .map_or(false, |infos| {
3578 infos.iter().any(|info| {
3579 primary_diagnostic_group_ids.contains_key(&(
3580 source,
3581 code.clone(),
3582 range_from_lsp(info.location.range),
3583 ))
3584 })
3585 });
3586
3587 let is_unnecessary = diagnostic.tags.as_ref().map_or(false, |tags| {
3588 tags.iter().any(|tag| *tag == DiagnosticTag::UNNECESSARY)
3589 });
3590
3591 if is_supporting {
3592 supporting_diagnostics.insert(
3593 (source, code.clone(), range),
3594 (diagnostic.severity, is_unnecessary),
3595 );
3596 } else {
3597 let group_id = post_inc(&mut self.next_diagnostic_group_id);
3598 let is_disk_based =
3599 source.map_or(false, |source| disk_based_sources.contains(source));
3600
3601 sources_by_group_id.insert(group_id, source);
3602 primary_diagnostic_group_ids
3603 .insert((source, code.clone(), range.clone()), group_id);
3604
3605 diagnostics.push(DiagnosticEntry {
3606 range,
3607 diagnostic: Diagnostic {
3608 source: diagnostic.source.clone(),
3609 code: code.clone(),
3610 severity: diagnostic.severity.unwrap_or(DiagnosticSeverity::ERROR),
3611 message: diagnostic.message.clone(),
3612 group_id,
3613 is_primary: true,
3614 is_valid: true,
3615 is_disk_based,
3616 is_unnecessary,
3617 },
3618 });
3619 if let Some(infos) = &diagnostic.related_information {
3620 for info in infos {
3621 if info.location.uri == params.uri && !info.message.is_empty() {
3622 let range = range_from_lsp(info.location.range);
3623 diagnostics.push(DiagnosticEntry {
3624 range,
3625 diagnostic: Diagnostic {
3626 source: diagnostic.source.clone(),
3627 code: code.clone(),
3628 severity: DiagnosticSeverity::INFORMATION,
3629 message: info.message.clone(),
3630 group_id,
3631 is_primary: false,
3632 is_valid: true,
3633 is_disk_based,
3634 is_unnecessary: false,
3635 },
3636 });
3637 }
3638 }
3639 }
3640 }
3641 }
3642
3643 for entry in &mut diagnostics {
3644 let diagnostic = &mut entry.diagnostic;
3645 if !diagnostic.is_primary {
3646 let source = *sources_by_group_id.get(&diagnostic.group_id).unwrap();
3647 if let Some(&(severity, is_unnecessary)) = supporting_diagnostics.get(&(
3648 source,
3649 diagnostic.code.clone(),
3650 entry.range.clone(),
3651 )) {
3652 if let Some(severity) = severity {
3653 diagnostic.severity = severity;
3654 }
3655 diagnostic.is_unnecessary = is_unnecessary;
3656 }
3657 }
3658 }
3659
3660 self.update_diagnostic_entries(
3661 language_server_id,
3662 abs_path,
3663 params.version,
3664 diagnostics,
3665 cx,
3666 )?;
3667 Ok(())
3668 }
3669
3670 pub fn update_diagnostic_entries(
3671 &mut self,
3672 server_id: LanguageServerId,
3673 abs_path: PathBuf,
3674 version: Option<i32>,
3675 diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
3676 cx: &mut ModelContext<Project>,
3677 ) -> Result<(), anyhow::Error> {
3678 let (worktree, relative_path) = self
3679 .find_local_worktree(&abs_path, cx)
3680 .ok_or_else(|| anyhow!("no worktree found for diagnostics path {abs_path:?}"))?;
3681
3682 let project_path = ProjectPath {
3683 worktree_id: worktree.read(cx).id(),
3684 path: relative_path.into(),
3685 };
3686
3687 if let Some(buffer) = self.get_open_buffer(&project_path, cx) {
3688 self.update_buffer_diagnostics(&buffer, server_id, version, diagnostics.clone(), cx)?;
3689 }
3690
3691 let updated = worktree.update(cx, |worktree, cx| {
3692 worktree
3693 .as_local_mut()
3694 .ok_or_else(|| anyhow!("not a local worktree"))?
3695 .update_diagnostics(server_id, project_path.path.clone(), diagnostics, cx)
3696 })?;
3697 if updated {
3698 cx.emit(Event::DiagnosticsUpdated {
3699 language_server_id: server_id,
3700 path: project_path,
3701 });
3702 }
3703 Ok(())
3704 }
3705
3706 fn update_buffer_diagnostics(
3707 &mut self,
3708 buffer: &ModelHandle<Buffer>,
3709 server_id: LanguageServerId,
3710 version: Option<i32>,
3711 mut diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
3712 cx: &mut ModelContext<Self>,
3713 ) -> Result<()> {
3714 fn compare_diagnostics(a: &Diagnostic, b: &Diagnostic) -> Ordering {
3715 Ordering::Equal
3716 .then_with(|| b.is_primary.cmp(&a.is_primary))
3717 .then_with(|| a.is_disk_based.cmp(&b.is_disk_based))
3718 .then_with(|| a.severity.cmp(&b.severity))
3719 .then_with(|| a.message.cmp(&b.message))
3720 }
3721
3722 let snapshot = self.buffer_snapshot_for_lsp_version(buffer, server_id, version, cx)?;
3723
3724 diagnostics.sort_unstable_by(|a, b| {
3725 Ordering::Equal
3726 .then_with(|| a.range.start.cmp(&b.range.start))
3727 .then_with(|| b.range.end.cmp(&a.range.end))
3728 .then_with(|| compare_diagnostics(&a.diagnostic, &b.diagnostic))
3729 });
3730
3731 let mut sanitized_diagnostics = Vec::new();
3732 let edits_since_save = Patch::new(
3733 snapshot
3734 .edits_since::<Unclipped<PointUtf16>>(buffer.read(cx).saved_version())
3735 .collect(),
3736 );
3737 for entry in diagnostics {
3738 let start;
3739 let end;
3740 if entry.diagnostic.is_disk_based {
3741 // Some diagnostics are based on files on disk instead of buffers'
3742 // current contents. Adjust these diagnostics' ranges to reflect
3743 // any unsaved edits.
3744 start = edits_since_save.old_to_new(entry.range.start);
3745 end = edits_since_save.old_to_new(entry.range.end);
3746 } else {
3747 start = entry.range.start;
3748 end = entry.range.end;
3749 }
3750
3751 let mut range = snapshot.clip_point_utf16(start, Bias::Left)
3752 ..snapshot.clip_point_utf16(end, Bias::Right);
3753
3754 // Expand empty ranges by one codepoint
3755 if range.start == range.end {
3756 // This will be go to the next boundary when being clipped
3757 range.end.column += 1;
3758 range.end = snapshot.clip_point_utf16(Unclipped(range.end), Bias::Right);
3759 if range.start == range.end && range.end.column > 0 {
3760 range.start.column -= 1;
3761 range.end = snapshot.clip_point_utf16(Unclipped(range.end), Bias::Left);
3762 }
3763 }
3764
3765 sanitized_diagnostics.push(DiagnosticEntry {
3766 range,
3767 diagnostic: entry.diagnostic,
3768 });
3769 }
3770 drop(edits_since_save);
3771
3772 let set = DiagnosticSet::new(sanitized_diagnostics, &snapshot);
3773 buffer.update(cx, |buffer, cx| {
3774 buffer.update_diagnostics(server_id, set, cx)
3775 });
3776 Ok(())
3777 }
3778
3779 pub fn reload_buffers(
3780 &self,
3781 buffers: HashSet<ModelHandle<Buffer>>,
3782 push_to_history: bool,
3783 cx: &mut ModelContext<Self>,
3784 ) -> Task<Result<ProjectTransaction>> {
3785 let mut local_buffers = Vec::new();
3786 let mut remote_buffers = None;
3787 for buffer_handle in buffers {
3788 let buffer = buffer_handle.read(cx);
3789 if buffer.is_dirty() {
3790 if let Some(file) = File::from_dyn(buffer.file()) {
3791 if file.is_local() {
3792 local_buffers.push(buffer_handle);
3793 } else {
3794 remote_buffers.get_or_insert(Vec::new()).push(buffer_handle);
3795 }
3796 }
3797 }
3798 }
3799
3800 let remote_buffers = self.remote_id().zip(remote_buffers);
3801 let client = self.client.clone();
3802
3803 cx.spawn(|this, mut cx| async move {
3804 let mut project_transaction = ProjectTransaction::default();
3805
3806 if let Some((project_id, remote_buffers)) = remote_buffers {
3807 let response = client
3808 .request(proto::ReloadBuffers {
3809 project_id,
3810 buffer_ids: remote_buffers
3811 .iter()
3812 .map(|buffer| buffer.read_with(&cx, |buffer, _| buffer.remote_id()))
3813 .collect(),
3814 })
3815 .await?
3816 .transaction
3817 .ok_or_else(|| anyhow!("missing transaction"))?;
3818 project_transaction = this
3819 .update(&mut cx, |this, cx| {
3820 this.deserialize_project_transaction(response, push_to_history, cx)
3821 })
3822 .await?;
3823 }
3824
3825 for buffer in local_buffers {
3826 let transaction = buffer
3827 .update(&mut cx, |buffer, cx| buffer.reload(cx))
3828 .await?;
3829 buffer.update(&mut cx, |buffer, cx| {
3830 if let Some(transaction) = transaction {
3831 if !push_to_history {
3832 buffer.forget_transaction(transaction.id);
3833 }
3834 project_transaction.0.insert(cx.handle(), transaction);
3835 }
3836 });
3837 }
3838
3839 Ok(project_transaction)
3840 })
3841 }
3842
3843 pub fn format(
3844 &self,
3845 buffers: HashSet<ModelHandle<Buffer>>,
3846 push_to_history: bool,
3847 trigger: FormatTrigger,
3848 cx: &mut ModelContext<Project>,
3849 ) -> Task<Result<ProjectTransaction>> {
3850 if self.is_local() {
3851 let mut buffers_with_paths_and_servers = buffers
3852 .into_iter()
3853 .filter_map(|buffer_handle| {
3854 let buffer = buffer_handle.read(cx);
3855 let file = File::from_dyn(buffer.file())?;
3856 let buffer_abs_path = file.as_local().map(|f| f.abs_path(cx));
3857 let server = self
3858 .primary_language_servers_for_buffer(buffer, cx)
3859 .map(|s| s.1.clone());
3860 Some((buffer_handle, buffer_abs_path, server))
3861 })
3862 .collect::<Vec<_>>();
3863
3864 cx.spawn(|this, mut cx| async move {
3865 // Do not allow multiple concurrent formatting requests for the
3866 // same buffer.
3867 this.update(&mut cx, |this, cx| {
3868 buffers_with_paths_and_servers.retain(|(buffer, _, _)| {
3869 this.buffers_being_formatted
3870 .insert(buffer.read(cx).remote_id())
3871 });
3872 });
3873
3874 let _cleanup = defer({
3875 let this = this.clone();
3876 let mut cx = cx.clone();
3877 let buffers = &buffers_with_paths_and_servers;
3878 move || {
3879 this.update(&mut cx, |this, cx| {
3880 for (buffer, _, _) in buffers {
3881 this.buffers_being_formatted
3882 .remove(&buffer.read(cx).remote_id());
3883 }
3884 });
3885 }
3886 });
3887
3888 let mut project_transaction = ProjectTransaction::default();
3889 for (buffer, buffer_abs_path, language_server) in &buffers_with_paths_and_servers {
3890 let settings = buffer.read_with(&cx, |buffer, cx| {
3891 language_settings(buffer.language(), buffer.file(), cx).clone()
3892 });
3893
3894 let remove_trailing_whitespace = settings.remove_trailing_whitespace_on_save;
3895 let ensure_final_newline = settings.ensure_final_newline_on_save;
3896 let format_on_save = settings.format_on_save.clone();
3897 let formatter = settings.formatter.clone();
3898 let tab_size = settings.tab_size;
3899
3900 // First, format buffer's whitespace according to the settings.
3901 let trailing_whitespace_diff = if remove_trailing_whitespace {
3902 Some(
3903 buffer
3904 .read_with(&cx, |b, cx| b.remove_trailing_whitespace(cx))
3905 .await,
3906 )
3907 } else {
3908 None
3909 };
3910 let whitespace_transaction_id = buffer.update(&mut cx, |buffer, cx| {
3911 buffer.finalize_last_transaction();
3912 buffer.start_transaction();
3913 if let Some(diff) = trailing_whitespace_diff {
3914 buffer.apply_diff(diff, cx);
3915 }
3916 if ensure_final_newline {
3917 buffer.ensure_final_newline(cx);
3918 }
3919 buffer.end_transaction(cx)
3920 });
3921
3922 // Currently, formatting operations are represented differently depending on
3923 // whether they come from a language server or an external command.
3924 enum FormatOperation {
3925 Lsp(Vec<(Range<Anchor>, String)>),
3926 External(Diff),
3927 }
3928
3929 // Apply language-specific formatting using either a language server
3930 // or external command.
3931 let mut format_operation = None;
3932 match (formatter, format_on_save) {
3933 (_, FormatOnSave::Off) if trigger == FormatTrigger::Save => {}
3934
3935 (Formatter::LanguageServer, FormatOnSave::On | FormatOnSave::Off)
3936 | (_, FormatOnSave::LanguageServer) => {
3937 if let Some((language_server, buffer_abs_path)) =
3938 language_server.as_ref().zip(buffer_abs_path.as_ref())
3939 {
3940 format_operation = Some(FormatOperation::Lsp(
3941 Self::format_via_lsp(
3942 &this,
3943 &buffer,
3944 buffer_abs_path,
3945 &language_server,
3946 tab_size,
3947 &mut cx,
3948 )
3949 .await
3950 .context("failed to format via language server")?,
3951 ));
3952 }
3953 }
3954
3955 (
3956 Formatter::External { command, arguments },
3957 FormatOnSave::On | FormatOnSave::Off,
3958 )
3959 | (_, FormatOnSave::External { command, arguments }) => {
3960 if let Some(buffer_abs_path) = buffer_abs_path {
3961 format_operation = Self::format_via_external_command(
3962 &buffer,
3963 &buffer_abs_path,
3964 &command,
3965 &arguments,
3966 &mut cx,
3967 )
3968 .await
3969 .context(format!(
3970 "failed to format via external command {:?}",
3971 command
3972 ))?
3973 .map(FormatOperation::External);
3974 }
3975 }
3976 };
3977
3978 buffer.update(&mut cx, |b, cx| {
3979 // If the buffer had its whitespace formatted and was edited while the language-specific
3980 // formatting was being computed, avoid applying the language-specific formatting, because
3981 // it can't be grouped with the whitespace formatting in the undo history.
3982 if let Some(transaction_id) = whitespace_transaction_id {
3983 if b.peek_undo_stack()
3984 .map_or(true, |e| e.transaction_id() != transaction_id)
3985 {
3986 format_operation.take();
3987 }
3988 }
3989
3990 // Apply any language-specific formatting, and group the two formatting operations
3991 // in the buffer's undo history.
3992 if let Some(operation) = format_operation {
3993 match operation {
3994 FormatOperation::Lsp(edits) => {
3995 b.edit(edits, None, cx);
3996 }
3997 FormatOperation::External(diff) => {
3998 b.apply_diff(diff, cx);
3999 }
4000 }
4001
4002 if let Some(transaction_id) = whitespace_transaction_id {
4003 b.group_until_transaction(transaction_id);
4004 }
4005 }
4006
4007 if let Some(transaction) = b.finalize_last_transaction().cloned() {
4008 if !push_to_history {
4009 b.forget_transaction(transaction.id);
4010 }
4011 project_transaction.0.insert(buffer.clone(), transaction);
4012 }
4013 });
4014 }
4015
4016 Ok(project_transaction)
4017 })
4018 } else {
4019 let remote_id = self.remote_id();
4020 let client = self.client.clone();
4021 cx.spawn(|this, mut cx| async move {
4022 let mut project_transaction = ProjectTransaction::default();
4023 if let Some(project_id) = remote_id {
4024 let response = client
4025 .request(proto::FormatBuffers {
4026 project_id,
4027 trigger: trigger as i32,
4028 buffer_ids: buffers
4029 .iter()
4030 .map(|buffer| buffer.read_with(&cx, |buffer, _| buffer.remote_id()))
4031 .collect(),
4032 })
4033 .await?
4034 .transaction
4035 .ok_or_else(|| anyhow!("missing transaction"))?;
4036 project_transaction = this
4037 .update(&mut cx, |this, cx| {
4038 this.deserialize_project_transaction(response, push_to_history, cx)
4039 })
4040 .await?;
4041 }
4042 Ok(project_transaction)
4043 })
4044 }
4045 }
4046
4047 async fn format_via_lsp(
4048 this: &ModelHandle<Self>,
4049 buffer: &ModelHandle<Buffer>,
4050 abs_path: &Path,
4051 language_server: &Arc<LanguageServer>,
4052 tab_size: NonZeroU32,
4053 cx: &mut AsyncAppContext,
4054 ) -> Result<Vec<(Range<Anchor>, String)>> {
4055 let uri = lsp::Url::from_file_path(abs_path)
4056 .map_err(|_| anyhow!("failed to convert abs path to uri"))?;
4057 let text_document = lsp::TextDocumentIdentifier::new(uri);
4058 let capabilities = &language_server.capabilities();
4059
4060 let formatting_provider = capabilities.document_formatting_provider.as_ref();
4061 let range_formatting_provider = capabilities.document_range_formatting_provider.as_ref();
4062
4063 let lsp_edits = if matches!(formatting_provider, Some(p) if *p != OneOf::Left(false)) {
4064 language_server
4065 .request::<lsp::request::Formatting>(lsp::DocumentFormattingParams {
4066 text_document,
4067 options: lsp_command::lsp_formatting_options(tab_size.get()),
4068 work_done_progress_params: Default::default(),
4069 })
4070 .await?
4071 } else if matches!(range_formatting_provider, Some(p) if *p != OneOf::Left(false)) {
4072 let buffer_start = lsp::Position::new(0, 0);
4073 let buffer_end = buffer.read_with(cx, |b, _| point_to_lsp(b.max_point_utf16()));
4074
4075 language_server
4076 .request::<lsp::request::RangeFormatting>(lsp::DocumentRangeFormattingParams {
4077 text_document,
4078 range: lsp::Range::new(buffer_start, buffer_end),
4079 options: lsp_command::lsp_formatting_options(tab_size.get()),
4080 work_done_progress_params: Default::default(),
4081 })
4082 .await?
4083 } else {
4084 None
4085 };
4086
4087 if let Some(lsp_edits) = lsp_edits {
4088 this.update(cx, |this, cx| {
4089 this.edits_from_lsp(buffer, lsp_edits, language_server.server_id(), None, cx)
4090 })
4091 .await
4092 } else {
4093 Ok(Vec::new())
4094 }
4095 }
4096
4097 async fn format_via_external_command(
4098 buffer: &ModelHandle<Buffer>,
4099 buffer_abs_path: &Path,
4100 command: &str,
4101 arguments: &[String],
4102 cx: &mut AsyncAppContext,
4103 ) -> Result<Option<Diff>> {
4104 let working_dir_path = buffer.read_with(cx, |buffer, cx| {
4105 let file = File::from_dyn(buffer.file())?;
4106 let worktree = file.worktree.read(cx).as_local()?;
4107 let mut worktree_path = worktree.abs_path().to_path_buf();
4108 if worktree.root_entry()?.is_file() {
4109 worktree_path.pop();
4110 }
4111 Some(worktree_path)
4112 });
4113
4114 if let Some(working_dir_path) = working_dir_path {
4115 let mut child =
4116 smol::process::Command::new(command)
4117 .args(arguments.iter().map(|arg| {
4118 arg.replace("{buffer_path}", &buffer_abs_path.to_string_lossy())
4119 }))
4120 .current_dir(&working_dir_path)
4121 .stdin(smol::process::Stdio::piped())
4122 .stdout(smol::process::Stdio::piped())
4123 .stderr(smol::process::Stdio::piped())
4124 .spawn()?;
4125 let stdin = child
4126 .stdin
4127 .as_mut()
4128 .ok_or_else(|| anyhow!("failed to acquire stdin"))?;
4129 let text = buffer.read_with(cx, |buffer, _| buffer.as_rope().clone());
4130 for chunk in text.chunks() {
4131 stdin.write_all(chunk.as_bytes()).await?;
4132 }
4133 stdin.flush().await?;
4134
4135 let output = child.output().await?;
4136 if !output.status.success() {
4137 return Err(anyhow!(
4138 "command failed with exit code {:?}:\nstdout: {}\nstderr: {}",
4139 output.status.code(),
4140 String::from_utf8_lossy(&output.stdout),
4141 String::from_utf8_lossy(&output.stderr),
4142 ));
4143 }
4144
4145 let stdout = String::from_utf8(output.stdout)?;
4146 Ok(Some(
4147 buffer
4148 .read_with(cx, |buffer, cx| buffer.diff(stdout, cx))
4149 .await,
4150 ))
4151 } else {
4152 Ok(None)
4153 }
4154 }
4155
4156 pub fn definition<T: ToPointUtf16>(
4157 &self,
4158 buffer: &ModelHandle<Buffer>,
4159 position: T,
4160 cx: &mut ModelContext<Self>,
4161 ) -> Task<Result<Vec<LocationLink>>> {
4162 let position = position.to_point_utf16(buffer.read(cx));
4163 self.request_lsp(buffer.clone(), GetDefinition { position }, cx)
4164 }
4165
4166 pub fn type_definition<T: ToPointUtf16>(
4167 &self,
4168 buffer: &ModelHandle<Buffer>,
4169 position: T,
4170 cx: &mut ModelContext<Self>,
4171 ) -> Task<Result<Vec<LocationLink>>> {
4172 let position = position.to_point_utf16(buffer.read(cx));
4173 self.request_lsp(buffer.clone(), GetTypeDefinition { position }, cx)
4174 }
4175
4176 pub fn references<T: ToPointUtf16>(
4177 &self,
4178 buffer: &ModelHandle<Buffer>,
4179 position: T,
4180 cx: &mut ModelContext<Self>,
4181 ) -> Task<Result<Vec<Location>>> {
4182 let position = position.to_point_utf16(buffer.read(cx));
4183 self.request_lsp(buffer.clone(), GetReferences { position }, cx)
4184 }
4185
4186 pub fn document_highlights<T: ToPointUtf16>(
4187 &self,
4188 buffer: &ModelHandle<Buffer>,
4189 position: T,
4190 cx: &mut ModelContext<Self>,
4191 ) -> Task<Result<Vec<DocumentHighlight>>> {
4192 let position = position.to_point_utf16(buffer.read(cx));
4193 self.request_lsp(buffer.clone(), GetDocumentHighlights { position }, cx)
4194 }
4195
4196 pub fn symbols(&self, query: &str, cx: &mut ModelContext<Self>) -> Task<Result<Vec<Symbol>>> {
4197 if self.is_local() {
4198 let mut requests = Vec::new();
4199 for ((worktree_id, _), server_id) in self.language_server_ids.iter() {
4200 let worktree_id = *worktree_id;
4201 let worktree_handle = self.worktree_for_id(worktree_id, cx);
4202 let worktree = match worktree_handle.and_then(|tree| tree.read(cx).as_local()) {
4203 Some(worktree) => worktree,
4204 None => continue,
4205 };
4206 let worktree_abs_path = worktree.abs_path().clone();
4207
4208 let (adapter, language, server) = match self.language_servers.get(server_id) {
4209 Some(LanguageServerState::Running {
4210 adapter,
4211 language,
4212 server,
4213 ..
4214 }) => (adapter.clone(), language.clone(), server),
4215
4216 _ => continue,
4217 };
4218
4219 requests.push(
4220 server
4221 .request::<lsp::request::WorkspaceSymbolRequest>(
4222 lsp::WorkspaceSymbolParams {
4223 query: query.to_string(),
4224 ..Default::default()
4225 },
4226 )
4227 .log_err()
4228 .map(move |response| {
4229 let lsp_symbols = response.flatten().map(|symbol_response| match symbol_response {
4230 lsp::WorkspaceSymbolResponse::Flat(flat_responses) => {
4231 flat_responses.into_iter().map(|lsp_symbol| {
4232 (lsp_symbol.name, lsp_symbol.kind, lsp_symbol.location)
4233 }).collect::<Vec<_>>()
4234 }
4235 lsp::WorkspaceSymbolResponse::Nested(nested_responses) => {
4236 nested_responses.into_iter().filter_map(|lsp_symbol| {
4237 let location = match lsp_symbol.location {
4238 OneOf::Left(location) => location,
4239 OneOf::Right(_) => {
4240 error!("Unexpected: client capabilities forbid symbol resolutions in workspace.symbol.resolveSupport");
4241 return None
4242 }
4243 };
4244 Some((lsp_symbol.name, lsp_symbol.kind, location))
4245 }).collect::<Vec<_>>()
4246 }
4247 }).unwrap_or_default();
4248
4249 (
4250 adapter,
4251 language,
4252 worktree_id,
4253 worktree_abs_path,
4254 lsp_symbols,
4255 )
4256 }),
4257 );
4258 }
4259
4260 cx.spawn_weak(|this, cx| async move {
4261 let responses = futures::future::join_all(requests).await;
4262 let this = match this.upgrade(&cx) {
4263 Some(this) => this,
4264 None => return Ok(Vec::new()),
4265 };
4266
4267 let symbols = this.read_with(&cx, |this, cx| {
4268 let mut symbols = Vec::new();
4269 for (
4270 adapter,
4271 adapter_language,
4272 source_worktree_id,
4273 worktree_abs_path,
4274 lsp_symbols,
4275 ) in responses
4276 {
4277 symbols.extend(lsp_symbols.into_iter().filter_map(
4278 |(symbol_name, symbol_kind, symbol_location)| {
4279 let abs_path = symbol_location.uri.to_file_path().ok()?;
4280 let mut worktree_id = source_worktree_id;
4281 let path;
4282 if let Some((worktree, rel_path)) =
4283 this.find_local_worktree(&abs_path, cx)
4284 {
4285 worktree_id = worktree.read(cx).id();
4286 path = rel_path;
4287 } else {
4288 path = relativize_path(&worktree_abs_path, &abs_path);
4289 }
4290
4291 let project_path = ProjectPath {
4292 worktree_id,
4293 path: path.into(),
4294 };
4295 let signature = this.symbol_signature(&project_path);
4296 let adapter_language = adapter_language.clone();
4297 let language = this
4298 .languages
4299 .language_for_file(&project_path.path, None)
4300 .unwrap_or_else(move |_| adapter_language);
4301 let language_server_name = adapter.name.clone();
4302 Some(async move {
4303 let language = language.await;
4304 let label =
4305 language.label_for_symbol(&symbol_name, symbol_kind).await;
4306
4307 Symbol {
4308 language_server_name,
4309 source_worktree_id,
4310 path: project_path,
4311 label: label.unwrap_or_else(|| {
4312 CodeLabel::plain(symbol_name.clone(), None)
4313 }),
4314 kind: symbol_kind,
4315 name: symbol_name,
4316 range: range_from_lsp(symbol_location.range),
4317 signature,
4318 }
4319 })
4320 },
4321 ));
4322 }
4323
4324 symbols
4325 });
4326
4327 Ok(futures::future::join_all(symbols).await)
4328 })
4329 } else if let Some(project_id) = self.remote_id() {
4330 let request = self.client.request(proto::GetProjectSymbols {
4331 project_id,
4332 query: query.to_string(),
4333 });
4334 cx.spawn_weak(|this, cx| async move {
4335 let response = request.await?;
4336 let mut symbols = Vec::new();
4337 if let Some(this) = this.upgrade(&cx) {
4338 let new_symbols = this.read_with(&cx, |this, _| {
4339 response
4340 .symbols
4341 .into_iter()
4342 .map(|symbol| this.deserialize_symbol(symbol))
4343 .collect::<Vec<_>>()
4344 });
4345 symbols = futures::future::join_all(new_symbols)
4346 .await
4347 .into_iter()
4348 .filter_map(|symbol| symbol.log_err())
4349 .collect::<Vec<_>>();
4350 }
4351 Ok(symbols)
4352 })
4353 } else {
4354 Task::ready(Ok(Default::default()))
4355 }
4356 }
4357
4358 pub fn open_buffer_for_symbol(
4359 &mut self,
4360 symbol: &Symbol,
4361 cx: &mut ModelContext<Self>,
4362 ) -> Task<Result<ModelHandle<Buffer>>> {
4363 if self.is_local() {
4364 let language_server_id = if let Some(id) = self.language_server_ids.get(&(
4365 symbol.source_worktree_id,
4366 symbol.language_server_name.clone(),
4367 )) {
4368 *id
4369 } else {
4370 return Task::ready(Err(anyhow!(
4371 "language server for worktree and language not found"
4372 )));
4373 };
4374
4375 let worktree_abs_path = if let Some(worktree_abs_path) = self
4376 .worktree_for_id(symbol.path.worktree_id, cx)
4377 .and_then(|worktree| worktree.read(cx).as_local())
4378 .map(|local_worktree| local_worktree.abs_path())
4379 {
4380 worktree_abs_path
4381 } else {
4382 return Task::ready(Err(anyhow!("worktree not found for symbol")));
4383 };
4384 let symbol_abs_path = worktree_abs_path.join(&symbol.path.path);
4385 let symbol_uri = if let Ok(uri) = lsp::Url::from_file_path(symbol_abs_path) {
4386 uri
4387 } else {
4388 return Task::ready(Err(anyhow!("invalid symbol path")));
4389 };
4390
4391 self.open_local_buffer_via_lsp(
4392 symbol_uri,
4393 language_server_id,
4394 symbol.language_server_name.clone(),
4395 cx,
4396 )
4397 } else if let Some(project_id) = self.remote_id() {
4398 let request = self.client.request(proto::OpenBufferForSymbol {
4399 project_id,
4400 symbol: Some(serialize_symbol(symbol)),
4401 });
4402 cx.spawn(|this, mut cx| async move {
4403 let response = request.await?;
4404 this.update(&mut cx, |this, cx| {
4405 this.wait_for_remote_buffer(response.buffer_id, cx)
4406 })
4407 .await
4408 })
4409 } else {
4410 Task::ready(Err(anyhow!("project does not have a remote id")))
4411 }
4412 }
4413
4414 pub fn hover<T: ToPointUtf16>(
4415 &self,
4416 buffer: &ModelHandle<Buffer>,
4417 position: T,
4418 cx: &mut ModelContext<Self>,
4419 ) -> Task<Result<Option<Hover>>> {
4420 let position = position.to_point_utf16(buffer.read(cx));
4421 self.request_lsp(buffer.clone(), GetHover { position }, cx)
4422 }
4423
4424 pub fn completions<T: ToPointUtf16>(
4425 &self,
4426 buffer: &ModelHandle<Buffer>,
4427 position: T,
4428 cx: &mut ModelContext<Self>,
4429 ) -> Task<Result<Vec<Completion>>> {
4430 let position = position.to_point_utf16(buffer.read(cx));
4431 self.request_lsp(buffer.clone(), GetCompletions { position }, cx)
4432 }
4433
4434 pub fn apply_additional_edits_for_completion(
4435 &self,
4436 buffer_handle: ModelHandle<Buffer>,
4437 completion: Completion,
4438 push_to_history: bool,
4439 cx: &mut ModelContext<Self>,
4440 ) -> Task<Result<Option<Transaction>>> {
4441 let buffer = buffer_handle.read(cx);
4442 let buffer_id = buffer.remote_id();
4443
4444 if self.is_local() {
4445 let lang_server = match self.primary_language_servers_for_buffer(buffer, cx) {
4446 Some((_, server)) => server.clone(),
4447 _ => return Task::ready(Ok(Default::default())),
4448 };
4449
4450 cx.spawn(|this, mut cx| async move {
4451 let additional_text_edits = lang_server
4452 .request::<lsp::request::ResolveCompletionItem>(completion.lsp_completion)
4453 .await?
4454 .additional_text_edits;
4455 if let Some(edits) = additional_text_edits {
4456 let edits = this
4457 .update(&mut cx, |this, cx| {
4458 this.edits_from_lsp(
4459 &buffer_handle,
4460 edits,
4461 lang_server.server_id(),
4462 None,
4463 cx,
4464 )
4465 })
4466 .await?;
4467
4468 buffer_handle.update(&mut cx, |buffer, cx| {
4469 buffer.finalize_last_transaction();
4470 buffer.start_transaction();
4471
4472 for (range, text) in edits {
4473 let primary = &completion.old_range;
4474 let start_within = primary.start.cmp(&range.start, buffer).is_le()
4475 && primary.end.cmp(&range.start, buffer).is_ge();
4476 let end_within = range.start.cmp(&primary.end, buffer).is_le()
4477 && range.end.cmp(&primary.end, buffer).is_ge();
4478
4479 //Skip additional edits which overlap with the primary completion edit
4480 //https://github.com/zed-industries/zed/pull/1871
4481 if !start_within && !end_within {
4482 buffer.edit([(range, text)], None, cx);
4483 }
4484 }
4485
4486 let transaction = if buffer.end_transaction(cx).is_some() {
4487 let transaction = buffer.finalize_last_transaction().unwrap().clone();
4488 if !push_to_history {
4489 buffer.forget_transaction(transaction.id);
4490 }
4491 Some(transaction)
4492 } else {
4493 None
4494 };
4495 Ok(transaction)
4496 })
4497 } else {
4498 Ok(None)
4499 }
4500 })
4501 } else if let Some(project_id) = self.remote_id() {
4502 let client = self.client.clone();
4503 cx.spawn(|_, mut cx| async move {
4504 let response = client
4505 .request(proto::ApplyCompletionAdditionalEdits {
4506 project_id,
4507 buffer_id,
4508 completion: Some(language::proto::serialize_completion(&completion)),
4509 })
4510 .await?;
4511
4512 if let Some(transaction) = response.transaction {
4513 let transaction = language::proto::deserialize_transaction(transaction)?;
4514 buffer_handle
4515 .update(&mut cx, |buffer, _| {
4516 buffer.wait_for_edits(transaction.edit_ids.iter().copied())
4517 })
4518 .await?;
4519 if push_to_history {
4520 buffer_handle.update(&mut cx, |buffer, _| {
4521 buffer.push_transaction(transaction.clone(), Instant::now());
4522 });
4523 }
4524 Ok(Some(transaction))
4525 } else {
4526 Ok(None)
4527 }
4528 })
4529 } else {
4530 Task::ready(Err(anyhow!("project does not have a remote id")))
4531 }
4532 }
4533
4534 pub fn code_actions<T: Clone + ToOffset>(
4535 &self,
4536 buffer_handle: &ModelHandle<Buffer>,
4537 range: Range<T>,
4538 cx: &mut ModelContext<Self>,
4539 ) -> Task<Result<Vec<CodeAction>>> {
4540 let buffer = buffer_handle.read(cx);
4541 let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
4542 self.request_lsp(buffer_handle.clone(), GetCodeActions { range }, cx)
4543 }
4544
4545 pub fn apply_code_action(
4546 &self,
4547 buffer_handle: ModelHandle<Buffer>,
4548 mut action: CodeAction,
4549 push_to_history: bool,
4550 cx: &mut ModelContext<Self>,
4551 ) -> Task<Result<ProjectTransaction>> {
4552 if self.is_local() {
4553 let buffer = buffer_handle.read(cx);
4554 let (lsp_adapter, lang_server) = if let Some((adapter, server)) =
4555 self.language_server_for_buffer(buffer, action.server_id, cx)
4556 {
4557 (adapter.clone(), server.clone())
4558 } else {
4559 return Task::ready(Ok(Default::default()));
4560 };
4561 let range = action.range.to_point_utf16(buffer);
4562
4563 cx.spawn(|this, mut cx| async move {
4564 if let Some(lsp_range) = action
4565 .lsp_action
4566 .data
4567 .as_mut()
4568 .and_then(|d| d.get_mut("codeActionParams"))
4569 .and_then(|d| d.get_mut("range"))
4570 {
4571 *lsp_range = serde_json::to_value(&range_to_lsp(range)).unwrap();
4572 action.lsp_action = lang_server
4573 .request::<lsp::request::CodeActionResolveRequest>(action.lsp_action)
4574 .await?;
4575 } else {
4576 let actions = this
4577 .update(&mut cx, |this, cx| {
4578 this.code_actions(&buffer_handle, action.range, cx)
4579 })
4580 .await?;
4581 action.lsp_action = actions
4582 .into_iter()
4583 .find(|a| a.lsp_action.title == action.lsp_action.title)
4584 .ok_or_else(|| anyhow!("code action is outdated"))?
4585 .lsp_action;
4586 }
4587
4588 if let Some(edit) = action.lsp_action.edit {
4589 if edit.changes.is_some() || edit.document_changes.is_some() {
4590 return Self::deserialize_workspace_edit(
4591 this,
4592 edit,
4593 push_to_history,
4594 lsp_adapter.clone(),
4595 lang_server.clone(),
4596 &mut cx,
4597 )
4598 .await;
4599 }
4600 }
4601
4602 if let Some(command) = action.lsp_action.command {
4603 this.update(&mut cx, |this, _| {
4604 this.last_workspace_edits_by_language_server
4605 .remove(&lang_server.server_id());
4606 });
4607
4608 let result = lang_server
4609 .request::<lsp::request::ExecuteCommand>(lsp::ExecuteCommandParams {
4610 command: command.command,
4611 arguments: command.arguments.unwrap_or_default(),
4612 ..Default::default()
4613 })
4614 .await;
4615
4616 if let Err(err) = result {
4617 // TODO: LSP ERROR
4618 return Err(err);
4619 }
4620
4621 return Ok(this.update(&mut cx, |this, _| {
4622 this.last_workspace_edits_by_language_server
4623 .remove(&lang_server.server_id())
4624 .unwrap_or_default()
4625 }));
4626 }
4627
4628 Ok(ProjectTransaction::default())
4629 })
4630 } else if let Some(project_id) = self.remote_id() {
4631 let client = self.client.clone();
4632 let request = proto::ApplyCodeAction {
4633 project_id,
4634 buffer_id: buffer_handle.read(cx).remote_id(),
4635 action: Some(language::proto::serialize_code_action(&action)),
4636 };
4637 cx.spawn(|this, mut cx| async move {
4638 let response = client
4639 .request(request)
4640 .await?
4641 .transaction
4642 .ok_or_else(|| anyhow!("missing transaction"))?;
4643 this.update(&mut cx, |this, cx| {
4644 this.deserialize_project_transaction(response, push_to_history, cx)
4645 })
4646 .await
4647 })
4648 } else {
4649 Task::ready(Err(anyhow!("project does not have a remote id")))
4650 }
4651 }
4652
4653 fn apply_on_type_formatting(
4654 &self,
4655 buffer: ModelHandle<Buffer>,
4656 position: Anchor,
4657 trigger: String,
4658 cx: &mut ModelContext<Self>,
4659 ) -> Task<Result<Option<Transaction>>> {
4660 if self.is_local() {
4661 cx.spawn(|this, mut cx| async move {
4662 // Do not allow multiple concurrent formatting requests for the
4663 // same buffer.
4664 this.update(&mut cx, |this, cx| {
4665 this.buffers_being_formatted
4666 .insert(buffer.read(cx).remote_id())
4667 });
4668
4669 let _cleanup = defer({
4670 let this = this.clone();
4671 let mut cx = cx.clone();
4672 let closure_buffer = buffer.clone();
4673 move || {
4674 this.update(&mut cx, |this, cx| {
4675 this.buffers_being_formatted
4676 .remove(&closure_buffer.read(cx).remote_id());
4677 });
4678 }
4679 });
4680
4681 buffer
4682 .update(&mut cx, |buffer, _| {
4683 buffer.wait_for_edits(Some(position.timestamp))
4684 })
4685 .await?;
4686 this.update(&mut cx, |this, cx| {
4687 let position = position.to_point_utf16(buffer.read(cx));
4688 this.on_type_format(buffer, position, trigger, false, cx)
4689 })
4690 .await
4691 })
4692 } else if let Some(project_id) = self.remote_id() {
4693 let client = self.client.clone();
4694 let request = proto::OnTypeFormatting {
4695 project_id,
4696 buffer_id: buffer.read(cx).remote_id(),
4697 position: Some(serialize_anchor(&position)),
4698 trigger,
4699 version: serialize_version(&buffer.read(cx).version()),
4700 };
4701 cx.spawn(|_, _| async move {
4702 client
4703 .request(request)
4704 .await?
4705 .transaction
4706 .map(language::proto::deserialize_transaction)
4707 .transpose()
4708 })
4709 } else {
4710 Task::ready(Err(anyhow!("project does not have a remote id")))
4711 }
4712 }
4713
4714 async fn deserialize_edits(
4715 this: ModelHandle<Self>,
4716 buffer_to_edit: ModelHandle<Buffer>,
4717 edits: Vec<lsp::TextEdit>,
4718 push_to_history: bool,
4719 _: Arc<CachedLspAdapter>,
4720 language_server: Arc<LanguageServer>,
4721 cx: &mut AsyncAppContext,
4722 ) -> Result<Option<Transaction>> {
4723 let edits = this
4724 .update(cx, |this, cx| {
4725 this.edits_from_lsp(
4726 &buffer_to_edit,
4727 edits,
4728 language_server.server_id(),
4729 None,
4730 cx,
4731 )
4732 })
4733 .await?;
4734
4735 let transaction = buffer_to_edit.update(cx, |buffer, cx| {
4736 buffer.finalize_last_transaction();
4737 buffer.start_transaction();
4738 for (range, text) in edits {
4739 buffer.edit([(range, text)], None, cx);
4740 }
4741
4742 if buffer.end_transaction(cx).is_some() {
4743 let transaction = buffer.finalize_last_transaction().unwrap().clone();
4744 if !push_to_history {
4745 buffer.forget_transaction(transaction.id);
4746 }
4747 Some(transaction)
4748 } else {
4749 None
4750 }
4751 });
4752
4753 Ok(transaction)
4754 }
4755
4756 async fn deserialize_workspace_edit(
4757 this: ModelHandle<Self>,
4758 edit: lsp::WorkspaceEdit,
4759 push_to_history: bool,
4760 lsp_adapter: Arc<CachedLspAdapter>,
4761 language_server: Arc<LanguageServer>,
4762 cx: &mut AsyncAppContext,
4763 ) -> Result<ProjectTransaction> {
4764 let fs = this.read_with(cx, |this, _| this.fs.clone());
4765 let mut operations = Vec::new();
4766 if let Some(document_changes) = edit.document_changes {
4767 match document_changes {
4768 lsp::DocumentChanges::Edits(edits) => {
4769 operations.extend(edits.into_iter().map(lsp::DocumentChangeOperation::Edit))
4770 }
4771 lsp::DocumentChanges::Operations(ops) => operations = ops,
4772 }
4773 } else if let Some(changes) = edit.changes {
4774 operations.extend(changes.into_iter().map(|(uri, edits)| {
4775 lsp::DocumentChangeOperation::Edit(lsp::TextDocumentEdit {
4776 text_document: lsp::OptionalVersionedTextDocumentIdentifier {
4777 uri,
4778 version: None,
4779 },
4780 edits: edits.into_iter().map(OneOf::Left).collect(),
4781 })
4782 }));
4783 }
4784
4785 let mut project_transaction = ProjectTransaction::default();
4786 for operation in operations {
4787 match operation {
4788 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Create(op)) => {
4789 let abs_path = op
4790 .uri
4791 .to_file_path()
4792 .map_err(|_| anyhow!("can't convert URI to path"))?;
4793
4794 if let Some(parent_path) = abs_path.parent() {
4795 fs.create_dir(parent_path).await?;
4796 }
4797 if abs_path.ends_with("/") {
4798 fs.create_dir(&abs_path).await?;
4799 } else {
4800 fs.create_file(&abs_path, op.options.map(Into::into).unwrap_or_default())
4801 .await?;
4802 }
4803 }
4804
4805 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Rename(op)) => {
4806 let source_abs_path = op
4807 .old_uri
4808 .to_file_path()
4809 .map_err(|_| anyhow!("can't convert URI to path"))?;
4810 let target_abs_path = op
4811 .new_uri
4812 .to_file_path()
4813 .map_err(|_| anyhow!("can't convert URI to path"))?;
4814 fs.rename(
4815 &source_abs_path,
4816 &target_abs_path,
4817 op.options.map(Into::into).unwrap_or_default(),
4818 )
4819 .await?;
4820 }
4821
4822 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Delete(op)) => {
4823 let abs_path = op
4824 .uri
4825 .to_file_path()
4826 .map_err(|_| anyhow!("can't convert URI to path"))?;
4827 let options = op.options.map(Into::into).unwrap_or_default();
4828 if abs_path.ends_with("/") {
4829 fs.remove_dir(&abs_path, options).await?;
4830 } else {
4831 fs.remove_file(&abs_path, options).await?;
4832 }
4833 }
4834
4835 lsp::DocumentChangeOperation::Edit(op) => {
4836 let buffer_to_edit = this
4837 .update(cx, |this, cx| {
4838 this.open_local_buffer_via_lsp(
4839 op.text_document.uri,
4840 language_server.server_id(),
4841 lsp_adapter.name.clone(),
4842 cx,
4843 )
4844 })
4845 .await?;
4846
4847 let edits = this
4848 .update(cx, |this, cx| {
4849 let edits = op.edits.into_iter().map(|edit| match edit {
4850 OneOf::Left(edit) => edit,
4851 OneOf::Right(edit) => edit.text_edit,
4852 });
4853 this.edits_from_lsp(
4854 &buffer_to_edit,
4855 edits,
4856 language_server.server_id(),
4857 op.text_document.version,
4858 cx,
4859 )
4860 })
4861 .await?;
4862
4863 let transaction = buffer_to_edit.update(cx, |buffer, cx| {
4864 buffer.finalize_last_transaction();
4865 buffer.start_transaction();
4866 for (range, text) in edits {
4867 buffer.edit([(range, text)], None, cx);
4868 }
4869 let transaction = if buffer.end_transaction(cx).is_some() {
4870 let transaction = buffer.finalize_last_transaction().unwrap().clone();
4871 if !push_to_history {
4872 buffer.forget_transaction(transaction.id);
4873 }
4874 Some(transaction)
4875 } else {
4876 None
4877 };
4878
4879 transaction
4880 });
4881 if let Some(transaction) = transaction {
4882 project_transaction.0.insert(buffer_to_edit, transaction);
4883 }
4884 }
4885 }
4886 }
4887
4888 Ok(project_transaction)
4889 }
4890
4891 pub fn prepare_rename<T: ToPointUtf16>(
4892 &self,
4893 buffer: ModelHandle<Buffer>,
4894 position: T,
4895 cx: &mut ModelContext<Self>,
4896 ) -> Task<Result<Option<Range<Anchor>>>> {
4897 let position = position.to_point_utf16(buffer.read(cx));
4898 self.request_lsp(buffer, PrepareRename { position }, cx)
4899 }
4900
4901 pub fn perform_rename<T: ToPointUtf16>(
4902 &self,
4903 buffer: ModelHandle<Buffer>,
4904 position: T,
4905 new_name: String,
4906 push_to_history: bool,
4907 cx: &mut ModelContext<Self>,
4908 ) -> Task<Result<ProjectTransaction>> {
4909 let position = position.to_point_utf16(buffer.read(cx));
4910 self.request_lsp(
4911 buffer,
4912 PerformRename {
4913 position,
4914 new_name,
4915 push_to_history,
4916 },
4917 cx,
4918 )
4919 }
4920
4921 pub fn on_type_format<T: ToPointUtf16>(
4922 &self,
4923 buffer: ModelHandle<Buffer>,
4924 position: T,
4925 trigger: String,
4926 push_to_history: bool,
4927 cx: &mut ModelContext<Self>,
4928 ) -> Task<Result<Option<Transaction>>> {
4929 let (position, tab_size) = buffer.read_with(cx, |buffer, cx| {
4930 let position = position.to_point_utf16(buffer);
4931 (
4932 position,
4933 language_settings(buffer.language_at(position).as_ref(), buffer.file(), cx)
4934 .tab_size,
4935 )
4936 });
4937 self.request_lsp(
4938 buffer.clone(),
4939 OnTypeFormatting {
4940 position,
4941 trigger,
4942 options: lsp_command::lsp_formatting_options(tab_size.get()).into(),
4943 push_to_history,
4944 },
4945 cx,
4946 )
4947 }
4948
4949 pub fn inlay_hints<T: ToOffset>(
4950 &self,
4951 buffer_handle: ModelHandle<Buffer>,
4952 range: Range<T>,
4953 cx: &mut ModelContext<Self>,
4954 ) -> Task<Result<Vec<InlayHint>>> {
4955 let buffer = buffer_handle.read(cx);
4956 let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
4957 let range_start = range.start;
4958 let range_end = range.end;
4959 let buffer_id = buffer.remote_id();
4960 let buffer_version = buffer.version().clone();
4961 let lsp_request = InlayHints { range };
4962
4963 if self.is_local() {
4964 let lsp_request_task = self.request_lsp(buffer_handle.clone(), lsp_request, cx);
4965 cx.spawn(|_, mut cx| async move {
4966 buffer_handle
4967 .update(&mut cx, |buffer, _| {
4968 buffer.wait_for_edits(vec![range_start.timestamp, range_end.timestamp])
4969 })
4970 .await
4971 .context("waiting for inlay hint request range edits")?;
4972 lsp_request_task.await.context("inlay hints LSP request")
4973 })
4974 } else if let Some(project_id) = self.remote_id() {
4975 let client = self.client.clone();
4976 let request = proto::InlayHints {
4977 project_id,
4978 buffer_id,
4979 start: Some(serialize_anchor(&range_start)),
4980 end: Some(serialize_anchor(&range_end)),
4981 version: serialize_version(&buffer_version),
4982 };
4983 cx.spawn(|project, cx| async move {
4984 let response = client
4985 .request(request)
4986 .await
4987 .context("inlay hints proto request")?;
4988 let hints_request_result = LspCommand::response_from_proto(
4989 lsp_request,
4990 response,
4991 project,
4992 buffer_handle.clone(),
4993 cx,
4994 )
4995 .await;
4996
4997 hints_request_result.context("inlay hints proto response conversion")
4998 })
4999 } else {
5000 Task::ready(Err(anyhow!("project does not have a remote id")))
5001 }
5002 }
5003
5004 #[allow(clippy::type_complexity)]
5005 pub fn search(
5006 &self,
5007 query: SearchQuery,
5008 cx: &mut ModelContext<Self>,
5009 ) -> Task<Result<HashMap<ModelHandle<Buffer>, Vec<Range<Anchor>>>>> {
5010 if self.is_local() {
5011 let snapshots = self
5012 .visible_worktrees(cx)
5013 .filter_map(|tree| {
5014 let tree = tree.read(cx).as_local()?;
5015 Some(tree.snapshot())
5016 })
5017 .collect::<Vec<_>>();
5018
5019 let background = cx.background().clone();
5020 let path_count: usize = snapshots.iter().map(|s| s.visible_file_count()).sum();
5021 if path_count == 0 {
5022 return Task::ready(Ok(Default::default()));
5023 }
5024 let workers = background.num_cpus().min(path_count);
5025 let (matching_paths_tx, mut matching_paths_rx) = smol::channel::bounded(1024);
5026 cx.background()
5027 .spawn({
5028 let fs = self.fs.clone();
5029 let background = cx.background().clone();
5030 let query = query.clone();
5031 async move {
5032 let fs = &fs;
5033 let query = &query;
5034 let matching_paths_tx = &matching_paths_tx;
5035 let paths_per_worker = (path_count + workers - 1) / workers;
5036 let snapshots = &snapshots;
5037 background
5038 .scoped(|scope| {
5039 for worker_ix in 0..workers {
5040 let worker_start_ix = worker_ix * paths_per_worker;
5041 let worker_end_ix = worker_start_ix + paths_per_worker;
5042 scope.spawn(async move {
5043 let mut snapshot_start_ix = 0;
5044 let mut abs_path = PathBuf::new();
5045 for snapshot in snapshots {
5046 let snapshot_end_ix =
5047 snapshot_start_ix + snapshot.visible_file_count();
5048 if worker_end_ix <= snapshot_start_ix {
5049 break;
5050 } else if worker_start_ix > snapshot_end_ix {
5051 snapshot_start_ix = snapshot_end_ix;
5052 continue;
5053 } else {
5054 let start_in_snapshot = worker_start_ix
5055 .saturating_sub(snapshot_start_ix);
5056 let end_in_snapshot =
5057 cmp::min(worker_end_ix, snapshot_end_ix)
5058 - snapshot_start_ix;
5059
5060 for entry in snapshot
5061 .files(false, start_in_snapshot)
5062 .take(end_in_snapshot - start_in_snapshot)
5063 {
5064 if matching_paths_tx.is_closed() {
5065 break;
5066 }
5067 let matches = if query
5068 .file_matches(Some(&entry.path))
5069 {
5070 abs_path.clear();
5071 abs_path.push(&snapshot.abs_path());
5072 abs_path.push(&entry.path);
5073 if let Some(file) =
5074 fs.open_sync(&abs_path).await.log_err()
5075 {
5076 query.detect(file).unwrap_or(false)
5077 } else {
5078 false
5079 }
5080 } else {
5081 false
5082 };
5083
5084 if matches {
5085 let project_path =
5086 (snapshot.id(), entry.path.clone());
5087 if matching_paths_tx
5088 .send(project_path)
5089 .await
5090 .is_err()
5091 {
5092 break;
5093 }
5094 }
5095 }
5096
5097 snapshot_start_ix = snapshot_end_ix;
5098 }
5099 }
5100 });
5101 }
5102 })
5103 .await;
5104 }
5105 })
5106 .detach();
5107
5108 let (buffers_tx, buffers_rx) = smol::channel::bounded(1024);
5109 let open_buffers = self
5110 .opened_buffers
5111 .values()
5112 .filter_map(|b| b.upgrade(cx))
5113 .collect::<HashSet<_>>();
5114 cx.spawn(|this, cx| async move {
5115 for buffer in &open_buffers {
5116 let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
5117 buffers_tx.send((buffer.clone(), snapshot)).await?;
5118 }
5119
5120 let open_buffers = Rc::new(RefCell::new(open_buffers));
5121 while let Some(project_path) = matching_paths_rx.next().await {
5122 if buffers_tx.is_closed() {
5123 break;
5124 }
5125
5126 let this = this.clone();
5127 let open_buffers = open_buffers.clone();
5128 let buffers_tx = buffers_tx.clone();
5129 cx.spawn(|mut cx| async move {
5130 if let Some(buffer) = this
5131 .update(&mut cx, |this, cx| this.open_buffer(project_path, cx))
5132 .await
5133 .log_err()
5134 {
5135 if open_buffers.borrow_mut().insert(buffer.clone()) {
5136 let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
5137 buffers_tx.send((buffer, snapshot)).await?;
5138 }
5139 }
5140
5141 Ok::<_, anyhow::Error>(())
5142 })
5143 .detach();
5144 }
5145
5146 Ok::<_, anyhow::Error>(())
5147 })
5148 .detach_and_log_err(cx);
5149
5150 let background = cx.background().clone();
5151 cx.background().spawn(async move {
5152 let query = &query;
5153 let mut matched_buffers = Vec::new();
5154 for _ in 0..workers {
5155 matched_buffers.push(HashMap::default());
5156 }
5157 background
5158 .scoped(|scope| {
5159 for worker_matched_buffers in matched_buffers.iter_mut() {
5160 let mut buffers_rx = buffers_rx.clone();
5161 scope.spawn(async move {
5162 while let Some((buffer, snapshot)) = buffers_rx.next().await {
5163 let buffer_matches = if query.file_matches(
5164 snapshot.file().map(|file| file.path().as_ref()),
5165 ) {
5166 query
5167 .search(snapshot.as_rope())
5168 .await
5169 .iter()
5170 .map(|range| {
5171 snapshot.anchor_before(range.start)
5172 ..snapshot.anchor_after(range.end)
5173 })
5174 .collect()
5175 } else {
5176 Vec::new()
5177 };
5178 if !buffer_matches.is_empty() {
5179 worker_matched_buffers
5180 .insert(buffer.clone(), buffer_matches);
5181 }
5182 }
5183 });
5184 }
5185 })
5186 .await;
5187 Ok(matched_buffers.into_iter().flatten().collect())
5188 })
5189 } else if let Some(project_id) = self.remote_id() {
5190 let request = self.client.request(query.to_proto(project_id));
5191 cx.spawn(|this, mut cx| async move {
5192 let response = request.await?;
5193 let mut result = HashMap::default();
5194 for location in response.locations {
5195 let target_buffer = this
5196 .update(&mut cx, |this, cx| {
5197 this.wait_for_remote_buffer(location.buffer_id, cx)
5198 })
5199 .await?;
5200 let start = location
5201 .start
5202 .and_then(deserialize_anchor)
5203 .ok_or_else(|| anyhow!("missing target start"))?;
5204 let end = location
5205 .end
5206 .and_then(deserialize_anchor)
5207 .ok_or_else(|| anyhow!("missing target end"))?;
5208 result
5209 .entry(target_buffer)
5210 .or_insert(Vec::new())
5211 .push(start..end)
5212 }
5213 Ok(result)
5214 })
5215 } else {
5216 Task::ready(Ok(Default::default()))
5217 }
5218 }
5219
5220 // TODO: Wire this up to allow selecting a server?
5221 fn request_lsp<R: LspCommand>(
5222 &self,
5223 buffer_handle: ModelHandle<Buffer>,
5224 request: R,
5225 cx: &mut ModelContext<Self>,
5226 ) -> Task<Result<R::Response>>
5227 where
5228 <R::LspRequest as lsp::request::Request>::Result: Send,
5229 {
5230 let buffer = buffer_handle.read(cx);
5231 if self.is_local() {
5232 let file = File::from_dyn(buffer.file()).and_then(File::as_local);
5233 if let Some((file, language_server)) = file.zip(
5234 self.primary_language_servers_for_buffer(buffer, cx)
5235 .map(|(_, server)| server.clone()),
5236 ) {
5237 let lsp_params = request.to_lsp(&file.abs_path(cx), buffer, &language_server, cx);
5238 return cx.spawn(|this, cx| async move {
5239 if !request.check_capabilities(language_server.capabilities()) {
5240 return Ok(Default::default());
5241 }
5242
5243 let result = language_server.request::<R::LspRequest>(lsp_params).await;
5244 let response = match result {
5245 Ok(response) => response,
5246
5247 Err(err) => {
5248 log::warn!(
5249 "Generic lsp request to {} failed: {}",
5250 language_server.name(),
5251 err
5252 );
5253 return Err(err);
5254 }
5255 };
5256
5257 request
5258 .response_from_lsp(
5259 response,
5260 this,
5261 buffer_handle,
5262 language_server.server_id(),
5263 cx,
5264 )
5265 .await
5266 });
5267 }
5268 } else if let Some(project_id) = self.remote_id() {
5269 let rpc = self.client.clone();
5270 let message = request.to_proto(project_id, buffer);
5271 return cx.spawn_weak(|this, cx| async move {
5272 // Ensure the project is still alive by the time the task
5273 // is scheduled.
5274 this.upgrade(&cx)
5275 .ok_or_else(|| anyhow!("project dropped"))?;
5276
5277 let response = rpc.request(message).await?;
5278
5279 let this = this
5280 .upgrade(&cx)
5281 .ok_or_else(|| anyhow!("project dropped"))?;
5282 if this.read_with(&cx, |this, _| this.is_read_only()) {
5283 Err(anyhow!("disconnected before completing request"))
5284 } else {
5285 request
5286 .response_from_proto(response, this, buffer_handle, cx)
5287 .await
5288 }
5289 });
5290 }
5291 Task::ready(Ok(Default::default()))
5292 }
5293
5294 pub fn find_or_create_local_worktree(
5295 &mut self,
5296 abs_path: impl AsRef<Path>,
5297 visible: bool,
5298 cx: &mut ModelContext<Self>,
5299 ) -> Task<Result<(ModelHandle<Worktree>, PathBuf)>> {
5300 let abs_path = abs_path.as_ref();
5301 if let Some((tree, relative_path)) = self.find_local_worktree(abs_path, cx) {
5302 Task::ready(Ok((tree, relative_path)))
5303 } else {
5304 let worktree = self.create_local_worktree(abs_path, visible, cx);
5305 cx.foreground()
5306 .spawn(async move { Ok((worktree.await?, PathBuf::new())) })
5307 }
5308 }
5309
5310 pub fn find_local_worktree(
5311 &self,
5312 abs_path: &Path,
5313 cx: &AppContext,
5314 ) -> Option<(ModelHandle<Worktree>, PathBuf)> {
5315 for tree in &self.worktrees {
5316 if let Some(tree) = tree.upgrade(cx) {
5317 if let Some(relative_path) = tree
5318 .read(cx)
5319 .as_local()
5320 .and_then(|t| abs_path.strip_prefix(t.abs_path()).ok())
5321 {
5322 return Some((tree.clone(), relative_path.into()));
5323 }
5324 }
5325 }
5326 None
5327 }
5328
5329 pub fn is_shared(&self) -> bool {
5330 match &self.client_state {
5331 Some(ProjectClientState::Local { .. }) => true,
5332 _ => false,
5333 }
5334 }
5335
5336 fn create_local_worktree(
5337 &mut self,
5338 abs_path: impl AsRef<Path>,
5339 visible: bool,
5340 cx: &mut ModelContext<Self>,
5341 ) -> Task<Result<ModelHandle<Worktree>>> {
5342 let fs = self.fs.clone();
5343 let client = self.client.clone();
5344 let next_entry_id = self.next_entry_id.clone();
5345 let path: Arc<Path> = abs_path.as_ref().into();
5346 let task = self
5347 .loading_local_worktrees
5348 .entry(path.clone())
5349 .or_insert_with(|| {
5350 cx.spawn(|project, mut cx| {
5351 async move {
5352 let worktree = Worktree::local(
5353 client.clone(),
5354 path.clone(),
5355 visible,
5356 fs,
5357 next_entry_id,
5358 &mut cx,
5359 )
5360 .await;
5361
5362 project.update(&mut cx, |project, _| {
5363 project.loading_local_worktrees.remove(&path);
5364 });
5365
5366 let worktree = worktree?;
5367 project.update(&mut cx, |project, cx| project.add_worktree(&worktree, cx));
5368 Ok(worktree)
5369 }
5370 .map_err(Arc::new)
5371 })
5372 .shared()
5373 })
5374 .clone();
5375 cx.foreground().spawn(async move {
5376 match task.await {
5377 Ok(worktree) => Ok(worktree),
5378 Err(err) => Err(anyhow!("{}", err)),
5379 }
5380 })
5381 }
5382
5383 pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut ModelContext<Self>) {
5384 self.worktrees.retain(|worktree| {
5385 if let Some(worktree) = worktree.upgrade(cx) {
5386 let id = worktree.read(cx).id();
5387 if id == id_to_remove {
5388 cx.emit(Event::WorktreeRemoved(id));
5389 false
5390 } else {
5391 true
5392 }
5393 } else {
5394 false
5395 }
5396 });
5397 self.metadata_changed(cx);
5398 }
5399
5400 fn add_worktree(&mut self, worktree: &ModelHandle<Worktree>, cx: &mut ModelContext<Self>) {
5401 cx.observe(worktree, |_, _, cx| cx.notify()).detach();
5402 if worktree.read(cx).is_local() {
5403 cx.subscribe(worktree, |this, worktree, event, cx| match event {
5404 worktree::Event::UpdatedEntries(changes) => {
5405 this.update_local_worktree_buffers(&worktree, changes, cx);
5406 this.update_local_worktree_language_servers(&worktree, changes, cx);
5407 this.update_local_worktree_settings(&worktree, changes, cx);
5408 cx.emit(Event::WorktreeUpdatedEntries(
5409 worktree.read(cx).id(),
5410 changes.clone(),
5411 ));
5412 }
5413 worktree::Event::UpdatedGitRepositories(updated_repos) => {
5414 this.update_local_worktree_buffers_git_repos(worktree, updated_repos, cx)
5415 }
5416 })
5417 .detach();
5418 }
5419
5420 let push_strong_handle = {
5421 let worktree = worktree.read(cx);
5422 self.is_shared() || worktree.is_visible() || worktree.is_remote()
5423 };
5424 if push_strong_handle {
5425 self.worktrees
5426 .push(WorktreeHandle::Strong(worktree.clone()));
5427 } else {
5428 self.worktrees
5429 .push(WorktreeHandle::Weak(worktree.downgrade()));
5430 }
5431
5432 let handle_id = worktree.id();
5433 cx.observe_release(worktree, move |this, worktree, cx| {
5434 let _ = this.remove_worktree(worktree.id(), cx);
5435 cx.update_global::<SettingsStore, _, _>(|store, cx| {
5436 store.clear_local_settings(handle_id, cx).log_err()
5437 });
5438 })
5439 .detach();
5440
5441 cx.emit(Event::WorktreeAdded);
5442 self.metadata_changed(cx);
5443 }
5444
5445 fn update_local_worktree_buffers(
5446 &mut self,
5447 worktree_handle: &ModelHandle<Worktree>,
5448 changes: &[(Arc<Path>, ProjectEntryId, PathChange)],
5449 cx: &mut ModelContext<Self>,
5450 ) {
5451 let snapshot = worktree_handle.read(cx).snapshot();
5452
5453 let mut renamed_buffers = Vec::new();
5454 for (path, entry_id, _) in changes {
5455 let worktree_id = worktree_handle.read(cx).id();
5456 let project_path = ProjectPath {
5457 worktree_id,
5458 path: path.clone(),
5459 };
5460
5461 let buffer_id = match self.local_buffer_ids_by_entry_id.get(entry_id) {
5462 Some(&buffer_id) => buffer_id,
5463 None => match self.local_buffer_ids_by_path.get(&project_path) {
5464 Some(&buffer_id) => buffer_id,
5465 None => continue,
5466 },
5467 };
5468
5469 let open_buffer = self.opened_buffers.get(&buffer_id);
5470 let buffer = if let Some(buffer) = open_buffer.and_then(|buffer| buffer.upgrade(cx)) {
5471 buffer
5472 } else {
5473 self.opened_buffers.remove(&buffer_id);
5474 self.local_buffer_ids_by_path.remove(&project_path);
5475 self.local_buffer_ids_by_entry_id.remove(entry_id);
5476 continue;
5477 };
5478
5479 buffer.update(cx, |buffer, cx| {
5480 if let Some(old_file) = File::from_dyn(buffer.file()) {
5481 if old_file.worktree != *worktree_handle {
5482 return;
5483 }
5484
5485 let new_file = if let Some(entry) = snapshot.entry_for_id(old_file.entry_id) {
5486 File {
5487 is_local: true,
5488 entry_id: entry.id,
5489 mtime: entry.mtime,
5490 path: entry.path.clone(),
5491 worktree: worktree_handle.clone(),
5492 is_deleted: false,
5493 }
5494 } else if let Some(entry) = snapshot.entry_for_path(old_file.path().as_ref()) {
5495 File {
5496 is_local: true,
5497 entry_id: entry.id,
5498 mtime: entry.mtime,
5499 path: entry.path.clone(),
5500 worktree: worktree_handle.clone(),
5501 is_deleted: false,
5502 }
5503 } else {
5504 File {
5505 is_local: true,
5506 entry_id: old_file.entry_id,
5507 path: old_file.path().clone(),
5508 mtime: old_file.mtime(),
5509 worktree: worktree_handle.clone(),
5510 is_deleted: true,
5511 }
5512 };
5513
5514 let old_path = old_file.abs_path(cx);
5515 if new_file.abs_path(cx) != old_path {
5516 renamed_buffers.push((cx.handle(), old_file.clone()));
5517 self.local_buffer_ids_by_path.remove(&project_path);
5518 self.local_buffer_ids_by_path.insert(
5519 ProjectPath {
5520 worktree_id,
5521 path: path.clone(),
5522 },
5523 buffer_id,
5524 );
5525 }
5526
5527 if new_file.entry_id != *entry_id {
5528 self.local_buffer_ids_by_entry_id.remove(entry_id);
5529 self.local_buffer_ids_by_entry_id
5530 .insert(new_file.entry_id, buffer_id);
5531 }
5532
5533 if new_file != *old_file {
5534 if let Some(project_id) = self.remote_id() {
5535 self.client
5536 .send(proto::UpdateBufferFile {
5537 project_id,
5538 buffer_id: buffer_id as u64,
5539 file: Some(new_file.to_proto()),
5540 })
5541 .log_err();
5542 }
5543
5544 buffer.file_updated(Arc::new(new_file), cx).detach();
5545 }
5546 }
5547 });
5548 }
5549
5550 for (buffer, old_file) in renamed_buffers {
5551 self.unregister_buffer_from_language_servers(&buffer, &old_file, cx);
5552 self.detect_language_for_buffer(&buffer, cx);
5553 self.register_buffer_with_language_servers(&buffer, cx);
5554 }
5555 }
5556
5557 fn update_local_worktree_language_servers(
5558 &mut self,
5559 worktree_handle: &ModelHandle<Worktree>,
5560 changes: &[(Arc<Path>, ProjectEntryId, PathChange)],
5561 cx: &mut ModelContext<Self>,
5562 ) {
5563 if changes.is_empty() {
5564 return;
5565 }
5566
5567 let worktree_id = worktree_handle.read(cx).id();
5568 let mut language_server_ids = self
5569 .language_server_ids
5570 .iter()
5571 .filter_map(|((server_worktree_id, _), server_id)| {
5572 (*server_worktree_id == worktree_id).then_some(*server_id)
5573 })
5574 .collect::<Vec<_>>();
5575 language_server_ids.sort();
5576 language_server_ids.dedup();
5577
5578 let abs_path = worktree_handle.read(cx).abs_path();
5579 for server_id in &language_server_ids {
5580 if let Some(LanguageServerState::Running {
5581 server,
5582 watched_paths,
5583 ..
5584 }) = self.language_servers.get(server_id)
5585 {
5586 if let Some(watched_paths) = watched_paths.get(&worktree_id) {
5587 let params = lsp::DidChangeWatchedFilesParams {
5588 changes: changes
5589 .iter()
5590 .filter_map(|(path, _, change)| {
5591 if !watched_paths.is_match(&path) {
5592 return None;
5593 }
5594 let typ = match change {
5595 PathChange::Loaded => return None,
5596 PathChange::Added => lsp::FileChangeType::CREATED,
5597 PathChange::Removed => lsp::FileChangeType::DELETED,
5598 PathChange::Updated => lsp::FileChangeType::CHANGED,
5599 PathChange::AddedOrUpdated => lsp::FileChangeType::CHANGED,
5600 };
5601 Some(lsp::FileEvent {
5602 uri: lsp::Url::from_file_path(abs_path.join(path)).unwrap(),
5603 typ,
5604 })
5605 })
5606 .collect(),
5607 };
5608
5609 if !params.changes.is_empty() {
5610 server
5611 .notify::<lsp::notification::DidChangeWatchedFiles>(params)
5612 .log_err();
5613 }
5614 }
5615 }
5616 }
5617 }
5618
5619 fn update_local_worktree_buffers_git_repos(
5620 &mut self,
5621 worktree_handle: ModelHandle<Worktree>,
5622 changed_repos: &UpdatedGitRepositoriesSet,
5623 cx: &mut ModelContext<Self>,
5624 ) {
5625 debug_assert!(worktree_handle.read(cx).is_local());
5626
5627 // Identify the loading buffers whose containing repository that has changed.
5628 let future_buffers = self
5629 .loading_buffers_by_path
5630 .iter()
5631 .filter_map(|(project_path, receiver)| {
5632 if project_path.worktree_id != worktree_handle.read(cx).id() {
5633 return None;
5634 }
5635 let path = &project_path.path;
5636 changed_repos
5637 .iter()
5638 .find(|(work_dir, _)| path.starts_with(work_dir))?;
5639 let receiver = receiver.clone();
5640 let path = path.clone();
5641 Some(async move {
5642 wait_for_loading_buffer(receiver)
5643 .await
5644 .ok()
5645 .map(|buffer| (buffer, path))
5646 })
5647 })
5648 .collect::<FuturesUnordered<_>>();
5649
5650 // Identify the current buffers whose containing repository has changed.
5651 let current_buffers = self
5652 .opened_buffers
5653 .values()
5654 .filter_map(|buffer| {
5655 let buffer = buffer.upgrade(cx)?;
5656 let file = File::from_dyn(buffer.read(cx).file())?;
5657 if file.worktree != worktree_handle {
5658 return None;
5659 }
5660 let path = file.path();
5661 changed_repos
5662 .iter()
5663 .find(|(work_dir, _)| path.starts_with(work_dir))?;
5664 Some((buffer, path.clone()))
5665 })
5666 .collect::<Vec<_>>();
5667
5668 if future_buffers.len() + current_buffers.len() == 0 {
5669 return;
5670 }
5671
5672 let remote_id = self.remote_id();
5673 let client = self.client.clone();
5674 cx.spawn_weak(move |_, mut cx| async move {
5675 // Wait for all of the buffers to load.
5676 let future_buffers = future_buffers.collect::<Vec<_>>().await;
5677
5678 // Reload the diff base for every buffer whose containing git repository has changed.
5679 let snapshot =
5680 worktree_handle.read_with(&cx, |tree, _| tree.as_local().unwrap().snapshot());
5681 let diff_bases_by_buffer = cx
5682 .background()
5683 .spawn(async move {
5684 future_buffers
5685 .into_iter()
5686 .filter_map(|e| e)
5687 .chain(current_buffers)
5688 .filter_map(|(buffer, path)| {
5689 let (work_directory, repo) =
5690 snapshot.repository_and_work_directory_for_path(&path)?;
5691 let repo = snapshot.get_local_repo(&repo)?;
5692 let relative_path = path.strip_prefix(&work_directory).ok()?;
5693 let base_text = repo.repo_ptr.lock().load_index_text(&relative_path);
5694 Some((buffer, base_text))
5695 })
5696 .collect::<Vec<_>>()
5697 })
5698 .await;
5699
5700 // Assign the new diff bases on all of the buffers.
5701 for (buffer, diff_base) in diff_bases_by_buffer {
5702 let buffer_id = buffer.update(&mut cx, |buffer, cx| {
5703 buffer.set_diff_base(diff_base.clone(), cx);
5704 buffer.remote_id()
5705 });
5706 if let Some(project_id) = remote_id {
5707 client
5708 .send(proto::UpdateDiffBase {
5709 project_id,
5710 buffer_id,
5711 diff_base,
5712 })
5713 .log_err();
5714 }
5715 }
5716 })
5717 .detach();
5718 }
5719
5720 fn update_local_worktree_settings(
5721 &mut self,
5722 worktree: &ModelHandle<Worktree>,
5723 changes: &UpdatedEntriesSet,
5724 cx: &mut ModelContext<Self>,
5725 ) {
5726 let project_id = self.remote_id();
5727 let worktree_id = worktree.id();
5728 let worktree = worktree.read(cx).as_local().unwrap();
5729 let remote_worktree_id = worktree.id();
5730
5731 let mut settings_contents = Vec::new();
5732 for (path, _, change) in changes.iter() {
5733 if path.ends_with(&*LOCAL_SETTINGS_RELATIVE_PATH) {
5734 let settings_dir = Arc::from(
5735 path.ancestors()
5736 .nth(LOCAL_SETTINGS_RELATIVE_PATH.components().count())
5737 .unwrap(),
5738 );
5739 let fs = self.fs.clone();
5740 let removed = *change == PathChange::Removed;
5741 let abs_path = worktree.absolutize(path);
5742 settings_contents.push(async move {
5743 (settings_dir, (!removed).then_some(fs.load(&abs_path).await))
5744 });
5745 }
5746 }
5747
5748 if settings_contents.is_empty() {
5749 return;
5750 }
5751
5752 let client = self.client.clone();
5753 cx.spawn_weak(move |_, mut cx| async move {
5754 let settings_contents: Vec<(Arc<Path>, _)> =
5755 futures::future::join_all(settings_contents).await;
5756 cx.update(|cx| {
5757 cx.update_global::<SettingsStore, _, _>(|store, cx| {
5758 for (directory, file_content) in settings_contents {
5759 let file_content = file_content.and_then(|content| content.log_err());
5760 store
5761 .set_local_settings(
5762 worktree_id,
5763 directory.clone(),
5764 file_content.as_ref().map(String::as_str),
5765 cx,
5766 )
5767 .log_err();
5768 if let Some(remote_id) = project_id {
5769 client
5770 .send(proto::UpdateWorktreeSettings {
5771 project_id: remote_id,
5772 worktree_id: remote_worktree_id.to_proto(),
5773 path: directory.to_string_lossy().into_owned(),
5774 content: file_content,
5775 })
5776 .log_err();
5777 }
5778 }
5779 });
5780 });
5781 })
5782 .detach();
5783 }
5784
5785 pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
5786 let new_active_entry = entry.and_then(|project_path| {
5787 let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
5788 let entry = worktree.read(cx).entry_for_path(project_path.path)?;
5789 Some(entry.id)
5790 });
5791 if new_active_entry != self.active_entry {
5792 self.active_entry = new_active_entry;
5793 cx.emit(Event::ActiveEntryChanged(new_active_entry));
5794 }
5795 }
5796
5797 pub fn language_servers_running_disk_based_diagnostics(
5798 &self,
5799 ) -> impl Iterator<Item = LanguageServerId> + '_ {
5800 self.language_server_statuses
5801 .iter()
5802 .filter_map(|(id, status)| {
5803 if status.has_pending_diagnostic_updates {
5804 Some(*id)
5805 } else {
5806 None
5807 }
5808 })
5809 }
5810
5811 pub fn diagnostic_summary(&self, cx: &AppContext) -> DiagnosticSummary {
5812 let mut summary = DiagnosticSummary::default();
5813 for (_, _, path_summary) in self.diagnostic_summaries(cx) {
5814 summary.error_count += path_summary.error_count;
5815 summary.warning_count += path_summary.warning_count;
5816 }
5817 summary
5818 }
5819
5820 pub fn diagnostic_summaries<'a>(
5821 &'a self,
5822 cx: &'a AppContext,
5823 ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
5824 self.visible_worktrees(cx).flat_map(move |worktree| {
5825 let worktree = worktree.read(cx);
5826 let worktree_id = worktree.id();
5827 worktree
5828 .diagnostic_summaries()
5829 .map(move |(path, server_id, summary)| {
5830 (ProjectPath { worktree_id, path }, server_id, summary)
5831 })
5832 })
5833 }
5834
5835 pub fn disk_based_diagnostics_started(
5836 &mut self,
5837 language_server_id: LanguageServerId,
5838 cx: &mut ModelContext<Self>,
5839 ) {
5840 cx.emit(Event::DiskBasedDiagnosticsStarted { language_server_id });
5841 }
5842
5843 pub fn disk_based_diagnostics_finished(
5844 &mut self,
5845 language_server_id: LanguageServerId,
5846 cx: &mut ModelContext<Self>,
5847 ) {
5848 cx.emit(Event::DiskBasedDiagnosticsFinished { language_server_id });
5849 }
5850
5851 pub fn active_entry(&self) -> Option<ProjectEntryId> {
5852 self.active_entry
5853 }
5854
5855 pub fn entry_for_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<Entry> {
5856 self.worktree_for_id(path.worktree_id, cx)?
5857 .read(cx)
5858 .entry_for_path(&path.path)
5859 .cloned()
5860 }
5861
5862 pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &AppContext) -> Option<ProjectPath> {
5863 let worktree = self.worktree_for_entry(entry_id, cx)?;
5864 let worktree = worktree.read(cx);
5865 let worktree_id = worktree.id();
5866 let path = worktree.entry_for_id(entry_id)?.path.clone();
5867 Some(ProjectPath { worktree_id, path })
5868 }
5869
5870 pub fn absolute_path(&self, project_path: &ProjectPath, cx: &AppContext) -> Option<PathBuf> {
5871 let workspace_root = self
5872 .worktree_for_id(project_path.worktree_id, cx)?
5873 .read(cx)
5874 .abs_path();
5875 let project_path = project_path.path.as_ref();
5876
5877 Some(if project_path == Path::new("") {
5878 workspace_root.to_path_buf()
5879 } else {
5880 workspace_root.join(project_path)
5881 })
5882 }
5883
5884 // RPC message handlers
5885
5886 async fn handle_unshare_project(
5887 this: ModelHandle<Self>,
5888 _: TypedEnvelope<proto::UnshareProject>,
5889 _: Arc<Client>,
5890 mut cx: AsyncAppContext,
5891 ) -> Result<()> {
5892 this.update(&mut cx, |this, cx| {
5893 if this.is_local() {
5894 this.unshare(cx)?;
5895 } else {
5896 this.disconnected_from_host(cx);
5897 }
5898 Ok(())
5899 })
5900 }
5901
5902 async fn handle_add_collaborator(
5903 this: ModelHandle<Self>,
5904 mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
5905 _: Arc<Client>,
5906 mut cx: AsyncAppContext,
5907 ) -> Result<()> {
5908 let collaborator = envelope
5909 .payload
5910 .collaborator
5911 .take()
5912 .ok_or_else(|| anyhow!("empty collaborator"))?;
5913
5914 let collaborator = Collaborator::from_proto(collaborator)?;
5915 this.update(&mut cx, |this, cx| {
5916 this.shared_buffers.remove(&collaborator.peer_id);
5917 this.collaborators
5918 .insert(collaborator.peer_id, collaborator);
5919 cx.notify();
5920 });
5921
5922 Ok(())
5923 }
5924
5925 async fn handle_update_project_collaborator(
5926 this: ModelHandle<Self>,
5927 envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
5928 _: Arc<Client>,
5929 mut cx: AsyncAppContext,
5930 ) -> Result<()> {
5931 let old_peer_id = envelope
5932 .payload
5933 .old_peer_id
5934 .ok_or_else(|| anyhow!("missing old peer id"))?;
5935 let new_peer_id = envelope
5936 .payload
5937 .new_peer_id
5938 .ok_or_else(|| anyhow!("missing new peer id"))?;
5939 this.update(&mut cx, |this, cx| {
5940 let collaborator = this
5941 .collaborators
5942 .remove(&old_peer_id)
5943 .ok_or_else(|| anyhow!("received UpdateProjectCollaborator for unknown peer"))?;
5944 let is_host = collaborator.replica_id == 0;
5945 this.collaborators.insert(new_peer_id, collaborator);
5946
5947 let buffers = this.shared_buffers.remove(&old_peer_id);
5948 log::info!(
5949 "peer {} became {}. moving buffers {:?}",
5950 old_peer_id,
5951 new_peer_id,
5952 &buffers
5953 );
5954 if let Some(buffers) = buffers {
5955 this.shared_buffers.insert(new_peer_id, buffers);
5956 }
5957
5958 if is_host {
5959 this.opened_buffers
5960 .retain(|_, buffer| !matches!(buffer, OpenBuffer::Operations(_)));
5961 this.buffer_ordered_messages_tx
5962 .unbounded_send(BufferOrderedMessage::Resync)
5963 .unwrap();
5964 }
5965
5966 cx.emit(Event::CollaboratorUpdated {
5967 old_peer_id,
5968 new_peer_id,
5969 });
5970 cx.notify();
5971 Ok(())
5972 })
5973 }
5974
5975 async fn handle_remove_collaborator(
5976 this: ModelHandle<Self>,
5977 envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
5978 _: Arc<Client>,
5979 mut cx: AsyncAppContext,
5980 ) -> Result<()> {
5981 this.update(&mut cx, |this, cx| {
5982 let peer_id = envelope
5983 .payload
5984 .peer_id
5985 .ok_or_else(|| anyhow!("invalid peer id"))?;
5986 let replica_id = this
5987 .collaborators
5988 .remove(&peer_id)
5989 .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
5990 .replica_id;
5991 for buffer in this.opened_buffers.values() {
5992 if let Some(buffer) = buffer.upgrade(cx) {
5993 buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
5994 }
5995 }
5996 this.shared_buffers.remove(&peer_id);
5997
5998 cx.emit(Event::CollaboratorLeft(peer_id));
5999 cx.notify();
6000 Ok(())
6001 })
6002 }
6003
6004 async fn handle_update_project(
6005 this: ModelHandle<Self>,
6006 envelope: TypedEnvelope<proto::UpdateProject>,
6007 _: Arc<Client>,
6008 mut cx: AsyncAppContext,
6009 ) -> Result<()> {
6010 this.update(&mut cx, |this, cx| {
6011 // Don't handle messages that were sent before the response to us joining the project
6012 if envelope.message_id > this.join_project_response_message_id {
6013 this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
6014 }
6015 Ok(())
6016 })
6017 }
6018
6019 async fn handle_update_worktree(
6020 this: ModelHandle<Self>,
6021 envelope: TypedEnvelope<proto::UpdateWorktree>,
6022 _: Arc<Client>,
6023 mut cx: AsyncAppContext,
6024 ) -> Result<()> {
6025 this.update(&mut cx, |this, cx| {
6026 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
6027 if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
6028 worktree.update(cx, |worktree, _| {
6029 let worktree = worktree.as_remote_mut().unwrap();
6030 worktree.update_from_remote(envelope.payload);
6031 });
6032 }
6033 Ok(())
6034 })
6035 }
6036
6037 async fn handle_update_worktree_settings(
6038 this: ModelHandle<Self>,
6039 envelope: TypedEnvelope<proto::UpdateWorktreeSettings>,
6040 _: Arc<Client>,
6041 mut cx: AsyncAppContext,
6042 ) -> Result<()> {
6043 this.update(&mut cx, |this, cx| {
6044 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
6045 if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
6046 cx.update_global::<SettingsStore, _, _>(|store, cx| {
6047 store
6048 .set_local_settings(
6049 worktree.id(),
6050 PathBuf::from(&envelope.payload.path).into(),
6051 envelope.payload.content.as_ref().map(String::as_str),
6052 cx,
6053 )
6054 .log_err();
6055 });
6056 }
6057 Ok(())
6058 })
6059 }
6060
6061 async fn handle_create_project_entry(
6062 this: ModelHandle<Self>,
6063 envelope: TypedEnvelope<proto::CreateProjectEntry>,
6064 _: Arc<Client>,
6065 mut cx: AsyncAppContext,
6066 ) -> Result<proto::ProjectEntryResponse> {
6067 let worktree = this.update(&mut cx, |this, cx| {
6068 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
6069 this.worktree_for_id(worktree_id, cx)
6070 .ok_or_else(|| anyhow!("worktree not found"))
6071 })?;
6072 let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
6073 let entry = worktree
6074 .update(&mut cx, |worktree, cx| {
6075 let worktree = worktree.as_local_mut().unwrap();
6076 let path = PathBuf::from(envelope.payload.path);
6077 worktree.create_entry(path, envelope.payload.is_directory, cx)
6078 })
6079 .await?;
6080 Ok(proto::ProjectEntryResponse {
6081 entry: Some((&entry).into()),
6082 worktree_scan_id: worktree_scan_id as u64,
6083 })
6084 }
6085
6086 async fn handle_rename_project_entry(
6087 this: ModelHandle<Self>,
6088 envelope: TypedEnvelope<proto::RenameProjectEntry>,
6089 _: Arc<Client>,
6090 mut cx: AsyncAppContext,
6091 ) -> Result<proto::ProjectEntryResponse> {
6092 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
6093 let worktree = this.read_with(&cx, |this, cx| {
6094 this.worktree_for_entry(entry_id, cx)
6095 .ok_or_else(|| anyhow!("worktree not found"))
6096 })?;
6097 let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
6098 let entry = worktree
6099 .update(&mut cx, |worktree, cx| {
6100 let new_path = PathBuf::from(envelope.payload.new_path);
6101 worktree
6102 .as_local_mut()
6103 .unwrap()
6104 .rename_entry(entry_id, new_path, cx)
6105 .ok_or_else(|| anyhow!("invalid entry"))
6106 })?
6107 .await?;
6108 Ok(proto::ProjectEntryResponse {
6109 entry: Some((&entry).into()),
6110 worktree_scan_id: worktree_scan_id as u64,
6111 })
6112 }
6113
6114 async fn handle_copy_project_entry(
6115 this: ModelHandle<Self>,
6116 envelope: TypedEnvelope<proto::CopyProjectEntry>,
6117 _: Arc<Client>,
6118 mut cx: AsyncAppContext,
6119 ) -> Result<proto::ProjectEntryResponse> {
6120 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
6121 let worktree = this.read_with(&cx, |this, cx| {
6122 this.worktree_for_entry(entry_id, cx)
6123 .ok_or_else(|| anyhow!("worktree not found"))
6124 })?;
6125 let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
6126 let entry = worktree
6127 .update(&mut cx, |worktree, cx| {
6128 let new_path = PathBuf::from(envelope.payload.new_path);
6129 worktree
6130 .as_local_mut()
6131 .unwrap()
6132 .copy_entry(entry_id, new_path, cx)
6133 .ok_or_else(|| anyhow!("invalid entry"))
6134 })?
6135 .await?;
6136 Ok(proto::ProjectEntryResponse {
6137 entry: Some((&entry).into()),
6138 worktree_scan_id: worktree_scan_id as u64,
6139 })
6140 }
6141
6142 async fn handle_delete_project_entry(
6143 this: ModelHandle<Self>,
6144 envelope: TypedEnvelope<proto::DeleteProjectEntry>,
6145 _: Arc<Client>,
6146 mut cx: AsyncAppContext,
6147 ) -> Result<proto::ProjectEntryResponse> {
6148 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
6149
6150 this.update(&mut cx, |_, cx| cx.emit(Event::DeletedEntry(entry_id)));
6151
6152 let worktree = this.read_with(&cx, |this, cx| {
6153 this.worktree_for_entry(entry_id, cx)
6154 .ok_or_else(|| anyhow!("worktree not found"))
6155 })?;
6156 let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
6157 worktree
6158 .update(&mut cx, |worktree, cx| {
6159 worktree
6160 .as_local_mut()
6161 .unwrap()
6162 .delete_entry(entry_id, cx)
6163 .ok_or_else(|| anyhow!("invalid entry"))
6164 })?
6165 .await?;
6166 Ok(proto::ProjectEntryResponse {
6167 entry: None,
6168 worktree_scan_id: worktree_scan_id as u64,
6169 })
6170 }
6171
6172 async fn handle_expand_project_entry(
6173 this: ModelHandle<Self>,
6174 envelope: TypedEnvelope<proto::ExpandProjectEntry>,
6175 _: Arc<Client>,
6176 mut cx: AsyncAppContext,
6177 ) -> Result<proto::ExpandProjectEntryResponse> {
6178 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
6179 let worktree = this
6180 .read_with(&cx, |this, cx| this.worktree_for_entry(entry_id, cx))
6181 .ok_or_else(|| anyhow!("invalid request"))?;
6182 worktree
6183 .update(&mut cx, |worktree, cx| {
6184 worktree
6185 .as_local_mut()
6186 .unwrap()
6187 .expand_entry(entry_id, cx)
6188 .ok_or_else(|| anyhow!("invalid entry"))
6189 })?
6190 .await?;
6191 let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id()) as u64;
6192 Ok(proto::ExpandProjectEntryResponse { worktree_scan_id })
6193 }
6194
6195 async fn handle_update_diagnostic_summary(
6196 this: ModelHandle<Self>,
6197 envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
6198 _: Arc<Client>,
6199 mut cx: AsyncAppContext,
6200 ) -> Result<()> {
6201 this.update(&mut cx, |this, cx| {
6202 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
6203 if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
6204 if let Some(summary) = envelope.payload.summary {
6205 let project_path = ProjectPath {
6206 worktree_id,
6207 path: Path::new(&summary.path).into(),
6208 };
6209 worktree.update(cx, |worktree, _| {
6210 worktree
6211 .as_remote_mut()
6212 .unwrap()
6213 .update_diagnostic_summary(project_path.path.clone(), &summary);
6214 });
6215 cx.emit(Event::DiagnosticsUpdated {
6216 language_server_id: LanguageServerId(summary.language_server_id as usize),
6217 path: project_path,
6218 });
6219 }
6220 }
6221 Ok(())
6222 })
6223 }
6224
6225 async fn handle_start_language_server(
6226 this: ModelHandle<Self>,
6227 envelope: TypedEnvelope<proto::StartLanguageServer>,
6228 _: Arc<Client>,
6229 mut cx: AsyncAppContext,
6230 ) -> Result<()> {
6231 let server = envelope
6232 .payload
6233 .server
6234 .ok_or_else(|| anyhow!("invalid server"))?;
6235 this.update(&mut cx, |this, cx| {
6236 this.language_server_statuses.insert(
6237 LanguageServerId(server.id as usize),
6238 LanguageServerStatus {
6239 name: server.name,
6240 pending_work: Default::default(),
6241 has_pending_diagnostic_updates: false,
6242 progress_tokens: Default::default(),
6243 },
6244 );
6245 cx.notify();
6246 });
6247 Ok(())
6248 }
6249
6250 async fn handle_update_language_server(
6251 this: ModelHandle<Self>,
6252 envelope: TypedEnvelope<proto::UpdateLanguageServer>,
6253 _: Arc<Client>,
6254 mut cx: AsyncAppContext,
6255 ) -> Result<()> {
6256 this.update(&mut cx, |this, cx| {
6257 let language_server_id = LanguageServerId(envelope.payload.language_server_id as usize);
6258
6259 match envelope
6260 .payload
6261 .variant
6262 .ok_or_else(|| anyhow!("invalid variant"))?
6263 {
6264 proto::update_language_server::Variant::WorkStart(payload) => {
6265 this.on_lsp_work_start(
6266 language_server_id,
6267 payload.token,
6268 LanguageServerProgress {
6269 message: payload.message,
6270 percentage: payload.percentage.map(|p| p as usize),
6271 last_update_at: Instant::now(),
6272 },
6273 cx,
6274 );
6275 }
6276
6277 proto::update_language_server::Variant::WorkProgress(payload) => {
6278 this.on_lsp_work_progress(
6279 language_server_id,
6280 payload.token,
6281 LanguageServerProgress {
6282 message: payload.message,
6283 percentage: payload.percentage.map(|p| p as usize),
6284 last_update_at: Instant::now(),
6285 },
6286 cx,
6287 );
6288 }
6289
6290 proto::update_language_server::Variant::WorkEnd(payload) => {
6291 this.on_lsp_work_end(language_server_id, payload.token, cx);
6292 }
6293
6294 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(_) => {
6295 this.disk_based_diagnostics_started(language_server_id, cx);
6296 }
6297
6298 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(_) => {
6299 this.disk_based_diagnostics_finished(language_server_id, cx)
6300 }
6301 }
6302
6303 Ok(())
6304 })
6305 }
6306
6307 async fn handle_update_buffer(
6308 this: ModelHandle<Self>,
6309 envelope: TypedEnvelope<proto::UpdateBuffer>,
6310 _: Arc<Client>,
6311 mut cx: AsyncAppContext,
6312 ) -> Result<proto::Ack> {
6313 this.update(&mut cx, |this, cx| {
6314 let payload = envelope.payload.clone();
6315 let buffer_id = payload.buffer_id;
6316 let ops = payload
6317 .operations
6318 .into_iter()
6319 .map(language::proto::deserialize_operation)
6320 .collect::<Result<Vec<_>, _>>()?;
6321 let is_remote = this.is_remote();
6322 match this.opened_buffers.entry(buffer_id) {
6323 hash_map::Entry::Occupied(mut e) => match e.get_mut() {
6324 OpenBuffer::Strong(buffer) => {
6325 buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx))?;
6326 }
6327 OpenBuffer::Operations(operations) => operations.extend_from_slice(&ops),
6328 OpenBuffer::Weak(_) => {}
6329 },
6330 hash_map::Entry::Vacant(e) => {
6331 assert!(
6332 is_remote,
6333 "received buffer update from {:?}",
6334 envelope.original_sender_id
6335 );
6336 e.insert(OpenBuffer::Operations(ops));
6337 }
6338 }
6339 Ok(proto::Ack {})
6340 })
6341 }
6342
6343 async fn handle_create_buffer_for_peer(
6344 this: ModelHandle<Self>,
6345 envelope: TypedEnvelope<proto::CreateBufferForPeer>,
6346 _: Arc<Client>,
6347 mut cx: AsyncAppContext,
6348 ) -> Result<()> {
6349 this.update(&mut cx, |this, cx| {
6350 match envelope
6351 .payload
6352 .variant
6353 .ok_or_else(|| anyhow!("missing variant"))?
6354 {
6355 proto::create_buffer_for_peer::Variant::State(mut state) => {
6356 let mut buffer_file = None;
6357 if let Some(file) = state.file.take() {
6358 let worktree_id = WorktreeId::from_proto(file.worktree_id);
6359 let worktree = this.worktree_for_id(worktree_id, cx).ok_or_else(|| {
6360 anyhow!("no worktree found for id {}", file.worktree_id)
6361 })?;
6362 buffer_file = Some(Arc::new(File::from_proto(file, worktree.clone(), cx)?)
6363 as Arc<dyn language::File>);
6364 }
6365
6366 let buffer_id = state.id;
6367 let buffer = cx.add_model(|_| {
6368 Buffer::from_proto(this.replica_id(), state, buffer_file).unwrap()
6369 });
6370 this.incomplete_remote_buffers
6371 .insert(buffer_id, Some(buffer));
6372 }
6373 proto::create_buffer_for_peer::Variant::Chunk(chunk) => {
6374 let buffer = this
6375 .incomplete_remote_buffers
6376 .get(&chunk.buffer_id)
6377 .cloned()
6378 .flatten()
6379 .ok_or_else(|| {
6380 anyhow!(
6381 "received chunk for buffer {} without initial state",
6382 chunk.buffer_id
6383 )
6384 })?;
6385 let operations = chunk
6386 .operations
6387 .into_iter()
6388 .map(language::proto::deserialize_operation)
6389 .collect::<Result<Vec<_>>>()?;
6390 buffer.update(cx, |buffer, cx| buffer.apply_ops(operations, cx))?;
6391
6392 if chunk.is_last {
6393 this.incomplete_remote_buffers.remove(&chunk.buffer_id);
6394 this.register_buffer(&buffer, cx)?;
6395 }
6396 }
6397 }
6398
6399 Ok(())
6400 })
6401 }
6402
6403 async fn handle_update_diff_base(
6404 this: ModelHandle<Self>,
6405 envelope: TypedEnvelope<proto::UpdateDiffBase>,
6406 _: Arc<Client>,
6407 mut cx: AsyncAppContext,
6408 ) -> Result<()> {
6409 this.update(&mut cx, |this, cx| {
6410 let buffer_id = envelope.payload.buffer_id;
6411 let diff_base = envelope.payload.diff_base;
6412 if let Some(buffer) = this
6413 .opened_buffers
6414 .get_mut(&buffer_id)
6415 .and_then(|b| b.upgrade(cx))
6416 .or_else(|| {
6417 this.incomplete_remote_buffers
6418 .get(&buffer_id)
6419 .cloned()
6420 .flatten()
6421 })
6422 {
6423 buffer.update(cx, |buffer, cx| buffer.set_diff_base(diff_base, cx));
6424 }
6425 Ok(())
6426 })
6427 }
6428
6429 async fn handle_update_buffer_file(
6430 this: ModelHandle<Self>,
6431 envelope: TypedEnvelope<proto::UpdateBufferFile>,
6432 _: Arc<Client>,
6433 mut cx: AsyncAppContext,
6434 ) -> Result<()> {
6435 let buffer_id = envelope.payload.buffer_id;
6436
6437 this.update(&mut cx, |this, cx| {
6438 let payload = envelope.payload.clone();
6439 if let Some(buffer) = this
6440 .opened_buffers
6441 .get(&buffer_id)
6442 .and_then(|b| b.upgrade(cx))
6443 .or_else(|| {
6444 this.incomplete_remote_buffers
6445 .get(&buffer_id)
6446 .cloned()
6447 .flatten()
6448 })
6449 {
6450 let file = payload.file.ok_or_else(|| anyhow!("invalid file"))?;
6451 let worktree = this
6452 .worktree_for_id(WorktreeId::from_proto(file.worktree_id), cx)
6453 .ok_or_else(|| anyhow!("no such worktree"))?;
6454 let file = File::from_proto(file, worktree, cx)?;
6455 buffer.update(cx, |buffer, cx| {
6456 buffer.file_updated(Arc::new(file), cx).detach();
6457 });
6458 this.detect_language_for_buffer(&buffer, cx);
6459 }
6460 Ok(())
6461 })
6462 }
6463
6464 async fn handle_save_buffer(
6465 this: ModelHandle<Self>,
6466 envelope: TypedEnvelope<proto::SaveBuffer>,
6467 _: Arc<Client>,
6468 mut cx: AsyncAppContext,
6469 ) -> Result<proto::BufferSaved> {
6470 let buffer_id = envelope.payload.buffer_id;
6471 let (project_id, buffer) = this.update(&mut cx, |this, cx| {
6472 let project_id = this.remote_id().ok_or_else(|| anyhow!("not connected"))?;
6473 let buffer = this
6474 .opened_buffers
6475 .get(&buffer_id)
6476 .and_then(|buffer| buffer.upgrade(cx))
6477 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
6478 anyhow::Ok((project_id, buffer))
6479 })?;
6480 buffer
6481 .update(&mut cx, |buffer, _| {
6482 buffer.wait_for_version(deserialize_version(&envelope.payload.version))
6483 })
6484 .await?;
6485 let buffer_id = buffer.read_with(&cx, |buffer, _| buffer.remote_id());
6486
6487 this.update(&mut cx, |this, cx| this.save_buffer(buffer.clone(), cx))
6488 .await?;
6489 Ok(buffer.read_with(&cx, |buffer, _| proto::BufferSaved {
6490 project_id,
6491 buffer_id,
6492 version: serialize_version(buffer.saved_version()),
6493 mtime: Some(buffer.saved_mtime().into()),
6494 fingerprint: language::proto::serialize_fingerprint(buffer.saved_version_fingerprint()),
6495 }))
6496 }
6497
6498 async fn handle_reload_buffers(
6499 this: ModelHandle<Self>,
6500 envelope: TypedEnvelope<proto::ReloadBuffers>,
6501 _: Arc<Client>,
6502 mut cx: AsyncAppContext,
6503 ) -> Result<proto::ReloadBuffersResponse> {
6504 let sender_id = envelope.original_sender_id()?;
6505 let reload = this.update(&mut cx, |this, cx| {
6506 let mut buffers = HashSet::default();
6507 for buffer_id in &envelope.payload.buffer_ids {
6508 buffers.insert(
6509 this.opened_buffers
6510 .get(buffer_id)
6511 .and_then(|buffer| buffer.upgrade(cx))
6512 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
6513 );
6514 }
6515 Ok::<_, anyhow::Error>(this.reload_buffers(buffers, false, cx))
6516 })?;
6517
6518 let project_transaction = reload.await?;
6519 let project_transaction = this.update(&mut cx, |this, cx| {
6520 this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
6521 });
6522 Ok(proto::ReloadBuffersResponse {
6523 transaction: Some(project_transaction),
6524 })
6525 }
6526
6527 async fn handle_synchronize_buffers(
6528 this: ModelHandle<Self>,
6529 envelope: TypedEnvelope<proto::SynchronizeBuffers>,
6530 _: Arc<Client>,
6531 mut cx: AsyncAppContext,
6532 ) -> Result<proto::SynchronizeBuffersResponse> {
6533 let project_id = envelope.payload.project_id;
6534 let mut response = proto::SynchronizeBuffersResponse {
6535 buffers: Default::default(),
6536 };
6537
6538 this.update(&mut cx, |this, cx| {
6539 let Some(guest_id) = envelope.original_sender_id else {
6540 error!("missing original_sender_id on SynchronizeBuffers request");
6541 return;
6542 };
6543
6544 this.shared_buffers.entry(guest_id).or_default().clear();
6545 for buffer in envelope.payload.buffers {
6546 let buffer_id = buffer.id;
6547 let remote_version = language::proto::deserialize_version(&buffer.version);
6548 if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
6549 this.shared_buffers
6550 .entry(guest_id)
6551 .or_default()
6552 .insert(buffer_id);
6553
6554 let buffer = buffer.read(cx);
6555 response.buffers.push(proto::BufferVersion {
6556 id: buffer_id,
6557 version: language::proto::serialize_version(&buffer.version),
6558 });
6559
6560 let operations = buffer.serialize_ops(Some(remote_version), cx);
6561 let client = this.client.clone();
6562 if let Some(file) = buffer.file() {
6563 client
6564 .send(proto::UpdateBufferFile {
6565 project_id,
6566 buffer_id: buffer_id as u64,
6567 file: Some(file.to_proto()),
6568 })
6569 .log_err();
6570 }
6571
6572 client
6573 .send(proto::UpdateDiffBase {
6574 project_id,
6575 buffer_id: buffer_id as u64,
6576 diff_base: buffer.diff_base().map(Into::into),
6577 })
6578 .log_err();
6579
6580 client
6581 .send(proto::BufferReloaded {
6582 project_id,
6583 buffer_id,
6584 version: language::proto::serialize_version(buffer.saved_version()),
6585 mtime: Some(buffer.saved_mtime().into()),
6586 fingerprint: language::proto::serialize_fingerprint(
6587 buffer.saved_version_fingerprint(),
6588 ),
6589 line_ending: language::proto::serialize_line_ending(
6590 buffer.line_ending(),
6591 ) as i32,
6592 })
6593 .log_err();
6594
6595 cx.background()
6596 .spawn(
6597 async move {
6598 let operations = operations.await;
6599 for chunk in split_operations(operations) {
6600 client
6601 .request(proto::UpdateBuffer {
6602 project_id,
6603 buffer_id,
6604 operations: chunk,
6605 })
6606 .await?;
6607 }
6608 anyhow::Ok(())
6609 }
6610 .log_err(),
6611 )
6612 .detach();
6613 }
6614 }
6615 });
6616
6617 Ok(response)
6618 }
6619
6620 async fn handle_format_buffers(
6621 this: ModelHandle<Self>,
6622 envelope: TypedEnvelope<proto::FormatBuffers>,
6623 _: Arc<Client>,
6624 mut cx: AsyncAppContext,
6625 ) -> Result<proto::FormatBuffersResponse> {
6626 let sender_id = envelope.original_sender_id()?;
6627 let format = this.update(&mut cx, |this, cx| {
6628 let mut buffers = HashSet::default();
6629 for buffer_id in &envelope.payload.buffer_ids {
6630 buffers.insert(
6631 this.opened_buffers
6632 .get(buffer_id)
6633 .and_then(|buffer| buffer.upgrade(cx))
6634 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
6635 );
6636 }
6637 let trigger = FormatTrigger::from_proto(envelope.payload.trigger);
6638 Ok::<_, anyhow::Error>(this.format(buffers, false, trigger, cx))
6639 })?;
6640
6641 let project_transaction = format.await?;
6642 let project_transaction = this.update(&mut cx, |this, cx| {
6643 this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
6644 });
6645 Ok(proto::FormatBuffersResponse {
6646 transaction: Some(project_transaction),
6647 })
6648 }
6649
6650 async fn handle_apply_additional_edits_for_completion(
6651 this: ModelHandle<Self>,
6652 envelope: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
6653 _: Arc<Client>,
6654 mut cx: AsyncAppContext,
6655 ) -> Result<proto::ApplyCompletionAdditionalEditsResponse> {
6656 let (buffer, completion) = this.update(&mut cx, |this, cx| {
6657 let buffer = this
6658 .opened_buffers
6659 .get(&envelope.payload.buffer_id)
6660 .and_then(|buffer| buffer.upgrade(cx))
6661 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
6662 let language = buffer.read(cx).language();
6663 let completion = language::proto::deserialize_completion(
6664 envelope
6665 .payload
6666 .completion
6667 .ok_or_else(|| anyhow!("invalid completion"))?,
6668 language.cloned(),
6669 );
6670 Ok::<_, anyhow::Error>((buffer, completion))
6671 })?;
6672
6673 let completion = completion.await?;
6674
6675 let apply_additional_edits = this.update(&mut cx, |this, cx| {
6676 this.apply_additional_edits_for_completion(buffer, completion, false, cx)
6677 });
6678
6679 Ok(proto::ApplyCompletionAdditionalEditsResponse {
6680 transaction: apply_additional_edits
6681 .await?
6682 .as_ref()
6683 .map(language::proto::serialize_transaction),
6684 })
6685 }
6686
6687 async fn handle_apply_code_action(
6688 this: ModelHandle<Self>,
6689 envelope: TypedEnvelope<proto::ApplyCodeAction>,
6690 _: Arc<Client>,
6691 mut cx: AsyncAppContext,
6692 ) -> Result<proto::ApplyCodeActionResponse> {
6693 let sender_id = envelope.original_sender_id()?;
6694 let action = language::proto::deserialize_code_action(
6695 envelope
6696 .payload
6697 .action
6698 .ok_or_else(|| anyhow!("invalid action"))?,
6699 )?;
6700 let apply_code_action = this.update(&mut cx, |this, cx| {
6701 let buffer = this
6702 .opened_buffers
6703 .get(&envelope.payload.buffer_id)
6704 .and_then(|buffer| buffer.upgrade(cx))
6705 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
6706 Ok::<_, anyhow::Error>(this.apply_code_action(buffer, action, false, cx))
6707 })?;
6708
6709 let project_transaction = apply_code_action.await?;
6710 let project_transaction = this.update(&mut cx, |this, cx| {
6711 this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
6712 });
6713 Ok(proto::ApplyCodeActionResponse {
6714 transaction: Some(project_transaction),
6715 })
6716 }
6717
6718 async fn handle_on_type_formatting(
6719 this: ModelHandle<Self>,
6720 envelope: TypedEnvelope<proto::OnTypeFormatting>,
6721 _: Arc<Client>,
6722 mut cx: AsyncAppContext,
6723 ) -> Result<proto::OnTypeFormattingResponse> {
6724 let on_type_formatting = this.update(&mut cx, |this, cx| {
6725 let buffer = this
6726 .opened_buffers
6727 .get(&envelope.payload.buffer_id)
6728 .and_then(|buffer| buffer.upgrade(cx))
6729 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
6730 let position = envelope
6731 .payload
6732 .position
6733 .and_then(deserialize_anchor)
6734 .ok_or_else(|| anyhow!("invalid position"))?;
6735 Ok::<_, anyhow::Error>(this.apply_on_type_formatting(
6736 buffer,
6737 position,
6738 envelope.payload.trigger.clone(),
6739 cx,
6740 ))
6741 })?;
6742
6743 let transaction = on_type_formatting
6744 .await?
6745 .as_ref()
6746 .map(language::proto::serialize_transaction);
6747 Ok(proto::OnTypeFormattingResponse { transaction })
6748 }
6749
6750 async fn handle_inlay_hints(
6751 this: ModelHandle<Self>,
6752 envelope: TypedEnvelope<proto::InlayHints>,
6753 _: Arc<Client>,
6754 mut cx: AsyncAppContext,
6755 ) -> Result<proto::InlayHintsResponse> {
6756 let sender_id = envelope.original_sender_id()?;
6757 let buffer = this.update(&mut cx, |this, cx| {
6758 this.opened_buffers
6759 .get(&envelope.payload.buffer_id)
6760 .and_then(|buffer| buffer.upgrade(cx))
6761 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
6762 })?;
6763 let buffer_version = deserialize_version(&envelope.payload.version);
6764
6765 buffer
6766 .update(&mut cx, |buffer, _| {
6767 buffer.wait_for_version(buffer_version.clone())
6768 })
6769 .await
6770 .with_context(|| {
6771 format!(
6772 "waiting for version {:?} for buffer {}",
6773 buffer_version,
6774 buffer.id()
6775 )
6776 })?;
6777
6778 let start = envelope
6779 .payload
6780 .start
6781 .and_then(deserialize_anchor)
6782 .context("missing range start")?;
6783 let end = envelope
6784 .payload
6785 .end
6786 .and_then(deserialize_anchor)
6787 .context("missing range end")?;
6788 let buffer_hints = this
6789 .update(&mut cx, |project, cx| {
6790 project.inlay_hints(buffer, start..end, cx)
6791 })
6792 .await
6793 .context("inlay hints fetch")?;
6794
6795 Ok(this.update(&mut cx, |project, cx| {
6796 InlayHints::response_to_proto(buffer_hints, project, sender_id, &buffer_version, cx)
6797 }))
6798 }
6799
6800 async fn handle_refresh_inlay_hints(
6801 this: ModelHandle<Self>,
6802 _: TypedEnvelope<proto::RefreshInlayHints>,
6803 _: Arc<Client>,
6804 mut cx: AsyncAppContext,
6805 ) -> Result<proto::Ack> {
6806 this.update(&mut cx, |_, cx| {
6807 cx.emit(Event::RefreshInlays);
6808 });
6809 Ok(proto::Ack {})
6810 }
6811
6812 async fn handle_lsp_command<T: LspCommand>(
6813 this: ModelHandle<Self>,
6814 envelope: TypedEnvelope<T::ProtoRequest>,
6815 _: Arc<Client>,
6816 mut cx: AsyncAppContext,
6817 ) -> Result<<T::ProtoRequest as proto::RequestMessage>::Response>
6818 where
6819 <T::LspRequest as lsp::request::Request>::Result: Send,
6820 {
6821 let sender_id = envelope.original_sender_id()?;
6822 let buffer_id = T::buffer_id_from_proto(&envelope.payload);
6823 let buffer_handle = this.read_with(&cx, |this, _| {
6824 this.opened_buffers
6825 .get(&buffer_id)
6826 .and_then(|buffer| buffer.upgrade(&cx))
6827 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
6828 })?;
6829 let request = T::from_proto(
6830 envelope.payload,
6831 this.clone(),
6832 buffer_handle.clone(),
6833 cx.clone(),
6834 )
6835 .await?;
6836 let buffer_version = buffer_handle.read_with(&cx, |buffer, _| buffer.version());
6837 let response = this
6838 .update(&mut cx, |this, cx| {
6839 this.request_lsp(buffer_handle, request, cx)
6840 })
6841 .await?;
6842 this.update(&mut cx, |this, cx| {
6843 Ok(T::response_to_proto(
6844 response,
6845 this,
6846 sender_id,
6847 &buffer_version,
6848 cx,
6849 ))
6850 })
6851 }
6852
6853 async fn handle_get_project_symbols(
6854 this: ModelHandle<Self>,
6855 envelope: TypedEnvelope<proto::GetProjectSymbols>,
6856 _: Arc<Client>,
6857 mut cx: AsyncAppContext,
6858 ) -> Result<proto::GetProjectSymbolsResponse> {
6859 let symbols = this
6860 .update(&mut cx, |this, cx| {
6861 this.symbols(&envelope.payload.query, cx)
6862 })
6863 .await?;
6864
6865 Ok(proto::GetProjectSymbolsResponse {
6866 symbols: symbols.iter().map(serialize_symbol).collect(),
6867 })
6868 }
6869
6870 async fn handle_search_project(
6871 this: ModelHandle<Self>,
6872 envelope: TypedEnvelope<proto::SearchProject>,
6873 _: Arc<Client>,
6874 mut cx: AsyncAppContext,
6875 ) -> Result<proto::SearchProjectResponse> {
6876 let peer_id = envelope.original_sender_id()?;
6877 let query = SearchQuery::from_proto(envelope.payload)?;
6878 let result = this
6879 .update(&mut cx, |this, cx| this.search(query, cx))
6880 .await?;
6881
6882 this.update(&mut cx, |this, cx| {
6883 let mut locations = Vec::new();
6884 for (buffer, ranges) in result {
6885 for range in ranges {
6886 let start = serialize_anchor(&range.start);
6887 let end = serialize_anchor(&range.end);
6888 let buffer_id = this.create_buffer_for_peer(&buffer, peer_id, cx);
6889 locations.push(proto::Location {
6890 buffer_id,
6891 start: Some(start),
6892 end: Some(end),
6893 });
6894 }
6895 }
6896 Ok(proto::SearchProjectResponse { locations })
6897 })
6898 }
6899
6900 async fn handle_open_buffer_for_symbol(
6901 this: ModelHandle<Self>,
6902 envelope: TypedEnvelope<proto::OpenBufferForSymbol>,
6903 _: Arc<Client>,
6904 mut cx: AsyncAppContext,
6905 ) -> Result<proto::OpenBufferForSymbolResponse> {
6906 let peer_id = envelope.original_sender_id()?;
6907 let symbol = envelope
6908 .payload
6909 .symbol
6910 .ok_or_else(|| anyhow!("invalid symbol"))?;
6911 let symbol = this
6912 .read_with(&cx, |this, _| this.deserialize_symbol(symbol))
6913 .await?;
6914 let symbol = this.read_with(&cx, |this, _| {
6915 let signature = this.symbol_signature(&symbol.path);
6916 if signature == symbol.signature {
6917 Ok(symbol)
6918 } else {
6919 Err(anyhow!("invalid symbol signature"))
6920 }
6921 })?;
6922 let buffer = this
6923 .update(&mut cx, |this, cx| this.open_buffer_for_symbol(&symbol, cx))
6924 .await?;
6925
6926 Ok(proto::OpenBufferForSymbolResponse {
6927 buffer_id: this.update(&mut cx, |this, cx| {
6928 this.create_buffer_for_peer(&buffer, peer_id, cx)
6929 }),
6930 })
6931 }
6932
6933 fn symbol_signature(&self, project_path: &ProjectPath) -> [u8; 32] {
6934 let mut hasher = Sha256::new();
6935 hasher.update(project_path.worktree_id.to_proto().to_be_bytes());
6936 hasher.update(project_path.path.to_string_lossy().as_bytes());
6937 hasher.update(self.nonce.to_be_bytes());
6938 hasher.finalize().as_slice().try_into().unwrap()
6939 }
6940
6941 async fn handle_open_buffer_by_id(
6942 this: ModelHandle<Self>,
6943 envelope: TypedEnvelope<proto::OpenBufferById>,
6944 _: Arc<Client>,
6945 mut cx: AsyncAppContext,
6946 ) -> Result<proto::OpenBufferResponse> {
6947 let peer_id = envelope.original_sender_id()?;
6948 let buffer = this
6949 .update(&mut cx, |this, cx| {
6950 this.open_buffer_by_id(envelope.payload.id, cx)
6951 })
6952 .await?;
6953 this.update(&mut cx, |this, cx| {
6954 Ok(proto::OpenBufferResponse {
6955 buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx),
6956 })
6957 })
6958 }
6959
6960 async fn handle_open_buffer_by_path(
6961 this: ModelHandle<Self>,
6962 envelope: TypedEnvelope<proto::OpenBufferByPath>,
6963 _: Arc<Client>,
6964 mut cx: AsyncAppContext,
6965 ) -> Result<proto::OpenBufferResponse> {
6966 let peer_id = envelope.original_sender_id()?;
6967 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
6968 let open_buffer = this.update(&mut cx, |this, cx| {
6969 this.open_buffer(
6970 ProjectPath {
6971 worktree_id,
6972 path: PathBuf::from(envelope.payload.path).into(),
6973 },
6974 cx,
6975 )
6976 });
6977
6978 let buffer = open_buffer.await?;
6979 this.update(&mut cx, |this, cx| {
6980 Ok(proto::OpenBufferResponse {
6981 buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx),
6982 })
6983 })
6984 }
6985
6986 fn serialize_project_transaction_for_peer(
6987 &mut self,
6988 project_transaction: ProjectTransaction,
6989 peer_id: proto::PeerId,
6990 cx: &mut AppContext,
6991 ) -> proto::ProjectTransaction {
6992 let mut serialized_transaction = proto::ProjectTransaction {
6993 buffer_ids: Default::default(),
6994 transactions: Default::default(),
6995 };
6996 for (buffer, transaction) in project_transaction.0 {
6997 serialized_transaction
6998 .buffer_ids
6999 .push(self.create_buffer_for_peer(&buffer, peer_id, cx));
7000 serialized_transaction
7001 .transactions
7002 .push(language::proto::serialize_transaction(&transaction));
7003 }
7004 serialized_transaction
7005 }
7006
7007 fn deserialize_project_transaction(
7008 &mut self,
7009 message: proto::ProjectTransaction,
7010 push_to_history: bool,
7011 cx: &mut ModelContext<Self>,
7012 ) -> Task<Result<ProjectTransaction>> {
7013 cx.spawn(|this, mut cx| async move {
7014 let mut project_transaction = ProjectTransaction::default();
7015 for (buffer_id, transaction) in message.buffer_ids.into_iter().zip(message.transactions)
7016 {
7017 let buffer = this
7018 .update(&mut cx, |this, cx| {
7019 this.wait_for_remote_buffer(buffer_id, cx)
7020 })
7021 .await?;
7022 let transaction = language::proto::deserialize_transaction(transaction)?;
7023 project_transaction.0.insert(buffer, transaction);
7024 }
7025
7026 for (buffer, transaction) in &project_transaction.0 {
7027 buffer
7028 .update(&mut cx, |buffer, _| {
7029 buffer.wait_for_edits(transaction.edit_ids.iter().copied())
7030 })
7031 .await?;
7032
7033 if push_to_history {
7034 buffer.update(&mut cx, |buffer, _| {
7035 buffer.push_transaction(transaction.clone(), Instant::now());
7036 });
7037 }
7038 }
7039
7040 Ok(project_transaction)
7041 })
7042 }
7043
7044 fn create_buffer_for_peer(
7045 &mut self,
7046 buffer: &ModelHandle<Buffer>,
7047 peer_id: proto::PeerId,
7048 cx: &mut AppContext,
7049 ) -> u64 {
7050 let buffer_id = buffer.read(cx).remote_id();
7051 if let Some(ProjectClientState::Local { updates_tx, .. }) = &self.client_state {
7052 updates_tx
7053 .unbounded_send(LocalProjectUpdate::CreateBufferForPeer { peer_id, buffer_id })
7054 .ok();
7055 }
7056 buffer_id
7057 }
7058
7059 fn wait_for_remote_buffer(
7060 &mut self,
7061 id: u64,
7062 cx: &mut ModelContext<Self>,
7063 ) -> Task<Result<ModelHandle<Buffer>>> {
7064 let mut opened_buffer_rx = self.opened_buffer.1.clone();
7065
7066 cx.spawn_weak(|this, mut cx| async move {
7067 let buffer = loop {
7068 let Some(this) = this.upgrade(&cx) else {
7069 return Err(anyhow!("project dropped"));
7070 };
7071
7072 let buffer = this.read_with(&cx, |this, cx| {
7073 this.opened_buffers
7074 .get(&id)
7075 .and_then(|buffer| buffer.upgrade(cx))
7076 });
7077
7078 if let Some(buffer) = buffer {
7079 break buffer;
7080 } else if this.read_with(&cx, |this, _| this.is_read_only()) {
7081 return Err(anyhow!("disconnected before buffer {} could be opened", id));
7082 }
7083
7084 this.update(&mut cx, |this, _| {
7085 this.incomplete_remote_buffers.entry(id).or_default();
7086 });
7087 drop(this);
7088
7089 opened_buffer_rx
7090 .next()
7091 .await
7092 .ok_or_else(|| anyhow!("project dropped while waiting for buffer"))?;
7093 };
7094
7095 Ok(buffer)
7096 })
7097 }
7098
7099 fn synchronize_remote_buffers(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
7100 let project_id = match self.client_state.as_ref() {
7101 Some(ProjectClientState::Remote {
7102 sharing_has_stopped,
7103 remote_id,
7104 ..
7105 }) => {
7106 if *sharing_has_stopped {
7107 return Task::ready(Err(anyhow!(
7108 "can't synchronize remote buffers on a readonly project"
7109 )));
7110 } else {
7111 *remote_id
7112 }
7113 }
7114 Some(ProjectClientState::Local { .. }) | None => {
7115 return Task::ready(Err(anyhow!(
7116 "can't synchronize remote buffers on a local project"
7117 )))
7118 }
7119 };
7120
7121 let client = self.client.clone();
7122 cx.spawn(|this, cx| async move {
7123 let (buffers, incomplete_buffer_ids) = this.read_with(&cx, |this, cx| {
7124 let buffers = this
7125 .opened_buffers
7126 .iter()
7127 .filter_map(|(id, buffer)| {
7128 let buffer = buffer.upgrade(cx)?;
7129 Some(proto::BufferVersion {
7130 id: *id,
7131 version: language::proto::serialize_version(&buffer.read(cx).version),
7132 })
7133 })
7134 .collect();
7135 let incomplete_buffer_ids = this
7136 .incomplete_remote_buffers
7137 .keys()
7138 .copied()
7139 .collect::<Vec<_>>();
7140
7141 (buffers, incomplete_buffer_ids)
7142 });
7143 let response = client
7144 .request(proto::SynchronizeBuffers {
7145 project_id,
7146 buffers,
7147 })
7148 .await?;
7149
7150 let send_updates_for_buffers = response.buffers.into_iter().map(|buffer| {
7151 let client = client.clone();
7152 let buffer_id = buffer.id;
7153 let remote_version = language::proto::deserialize_version(&buffer.version);
7154 this.read_with(&cx, |this, cx| {
7155 if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
7156 let operations = buffer.read(cx).serialize_ops(Some(remote_version), cx);
7157 cx.background().spawn(async move {
7158 let operations = operations.await;
7159 for chunk in split_operations(operations) {
7160 client
7161 .request(proto::UpdateBuffer {
7162 project_id,
7163 buffer_id,
7164 operations: chunk,
7165 })
7166 .await?;
7167 }
7168 anyhow::Ok(())
7169 })
7170 } else {
7171 Task::ready(Ok(()))
7172 }
7173 })
7174 });
7175
7176 // Any incomplete buffers have open requests waiting. Request that the host sends
7177 // creates these buffers for us again to unblock any waiting futures.
7178 for id in incomplete_buffer_ids {
7179 cx.background()
7180 .spawn(client.request(proto::OpenBufferById { project_id, id }))
7181 .detach();
7182 }
7183
7184 futures::future::join_all(send_updates_for_buffers)
7185 .await
7186 .into_iter()
7187 .collect()
7188 })
7189 }
7190
7191 pub fn worktree_metadata_protos(&self, cx: &AppContext) -> Vec<proto::WorktreeMetadata> {
7192 self.worktrees(cx)
7193 .map(|worktree| {
7194 let worktree = worktree.read(cx);
7195 proto::WorktreeMetadata {
7196 id: worktree.id().to_proto(),
7197 root_name: worktree.root_name().into(),
7198 visible: worktree.is_visible(),
7199 abs_path: worktree.abs_path().to_string_lossy().into(),
7200 }
7201 })
7202 .collect()
7203 }
7204
7205 fn set_worktrees_from_proto(
7206 &mut self,
7207 worktrees: Vec<proto::WorktreeMetadata>,
7208 cx: &mut ModelContext<Project>,
7209 ) -> Result<()> {
7210 let replica_id = self.replica_id();
7211 let remote_id = self.remote_id().ok_or_else(|| anyhow!("invalid project"))?;
7212
7213 let mut old_worktrees_by_id = self
7214 .worktrees
7215 .drain(..)
7216 .filter_map(|worktree| {
7217 let worktree = worktree.upgrade(cx)?;
7218 Some((worktree.read(cx).id(), worktree))
7219 })
7220 .collect::<HashMap<_, _>>();
7221
7222 for worktree in worktrees {
7223 if let Some(old_worktree) =
7224 old_worktrees_by_id.remove(&WorktreeId::from_proto(worktree.id))
7225 {
7226 self.worktrees.push(WorktreeHandle::Strong(old_worktree));
7227 } else {
7228 let worktree =
7229 Worktree::remote(remote_id, replica_id, worktree, self.client.clone(), cx);
7230 let _ = self.add_worktree(&worktree, cx);
7231 }
7232 }
7233
7234 self.metadata_changed(cx);
7235 for id in old_worktrees_by_id.keys() {
7236 cx.emit(Event::WorktreeRemoved(*id));
7237 }
7238
7239 Ok(())
7240 }
7241
7242 fn set_collaborators_from_proto(
7243 &mut self,
7244 messages: Vec<proto::Collaborator>,
7245 cx: &mut ModelContext<Self>,
7246 ) -> Result<()> {
7247 let mut collaborators = HashMap::default();
7248 for message in messages {
7249 let collaborator = Collaborator::from_proto(message)?;
7250 collaborators.insert(collaborator.peer_id, collaborator);
7251 }
7252 for old_peer_id in self.collaborators.keys() {
7253 if !collaborators.contains_key(old_peer_id) {
7254 cx.emit(Event::CollaboratorLeft(*old_peer_id));
7255 }
7256 }
7257 self.collaborators = collaborators;
7258 Ok(())
7259 }
7260
7261 fn deserialize_symbol(
7262 &self,
7263 serialized_symbol: proto::Symbol,
7264 ) -> impl Future<Output = Result<Symbol>> {
7265 let languages = self.languages.clone();
7266 async move {
7267 let source_worktree_id = WorktreeId::from_proto(serialized_symbol.source_worktree_id);
7268 let worktree_id = WorktreeId::from_proto(serialized_symbol.worktree_id);
7269 let start = serialized_symbol
7270 .start
7271 .ok_or_else(|| anyhow!("invalid start"))?;
7272 let end = serialized_symbol
7273 .end
7274 .ok_or_else(|| anyhow!("invalid end"))?;
7275 let kind = unsafe { mem::transmute(serialized_symbol.kind) };
7276 let path = ProjectPath {
7277 worktree_id,
7278 path: PathBuf::from(serialized_symbol.path).into(),
7279 };
7280 let language = languages
7281 .language_for_file(&path.path, None)
7282 .await
7283 .log_err();
7284 Ok(Symbol {
7285 language_server_name: LanguageServerName(
7286 serialized_symbol.language_server_name.into(),
7287 ),
7288 source_worktree_id,
7289 path,
7290 label: {
7291 match language {
7292 Some(language) => {
7293 language
7294 .label_for_symbol(&serialized_symbol.name, kind)
7295 .await
7296 }
7297 None => None,
7298 }
7299 .unwrap_or_else(|| CodeLabel::plain(serialized_symbol.name.clone(), None))
7300 },
7301
7302 name: serialized_symbol.name,
7303 range: Unclipped(PointUtf16::new(start.row, start.column))
7304 ..Unclipped(PointUtf16::new(end.row, end.column)),
7305 kind,
7306 signature: serialized_symbol
7307 .signature
7308 .try_into()
7309 .map_err(|_| anyhow!("invalid signature"))?,
7310 })
7311 }
7312 }
7313
7314 async fn handle_buffer_saved(
7315 this: ModelHandle<Self>,
7316 envelope: TypedEnvelope<proto::BufferSaved>,
7317 _: Arc<Client>,
7318 mut cx: AsyncAppContext,
7319 ) -> Result<()> {
7320 let fingerprint = deserialize_fingerprint(&envelope.payload.fingerprint)?;
7321 let version = deserialize_version(&envelope.payload.version);
7322 let mtime = envelope
7323 .payload
7324 .mtime
7325 .ok_or_else(|| anyhow!("missing mtime"))?
7326 .into();
7327
7328 this.update(&mut cx, |this, cx| {
7329 let buffer = this
7330 .opened_buffers
7331 .get(&envelope.payload.buffer_id)
7332 .and_then(|buffer| buffer.upgrade(cx))
7333 .or_else(|| {
7334 this.incomplete_remote_buffers
7335 .get(&envelope.payload.buffer_id)
7336 .and_then(|b| b.clone())
7337 });
7338 if let Some(buffer) = buffer {
7339 buffer.update(cx, |buffer, cx| {
7340 buffer.did_save(version, fingerprint, mtime, cx);
7341 });
7342 }
7343 Ok(())
7344 })
7345 }
7346
7347 async fn handle_buffer_reloaded(
7348 this: ModelHandle<Self>,
7349 envelope: TypedEnvelope<proto::BufferReloaded>,
7350 _: Arc<Client>,
7351 mut cx: AsyncAppContext,
7352 ) -> Result<()> {
7353 let payload = envelope.payload;
7354 let version = deserialize_version(&payload.version);
7355 let fingerprint = deserialize_fingerprint(&payload.fingerprint)?;
7356 let line_ending = deserialize_line_ending(
7357 proto::LineEnding::from_i32(payload.line_ending)
7358 .ok_or_else(|| anyhow!("missing line ending"))?,
7359 );
7360 let mtime = payload
7361 .mtime
7362 .ok_or_else(|| anyhow!("missing mtime"))?
7363 .into();
7364 this.update(&mut cx, |this, cx| {
7365 let buffer = this
7366 .opened_buffers
7367 .get(&payload.buffer_id)
7368 .and_then(|buffer| buffer.upgrade(cx))
7369 .or_else(|| {
7370 this.incomplete_remote_buffers
7371 .get(&payload.buffer_id)
7372 .cloned()
7373 .flatten()
7374 });
7375 if let Some(buffer) = buffer {
7376 buffer.update(cx, |buffer, cx| {
7377 buffer.did_reload(version, fingerprint, line_ending, mtime, cx);
7378 });
7379 }
7380 Ok(())
7381 })
7382 }
7383
7384 #[allow(clippy::type_complexity)]
7385 fn edits_from_lsp(
7386 &mut self,
7387 buffer: &ModelHandle<Buffer>,
7388 lsp_edits: impl 'static + Send + IntoIterator<Item = lsp::TextEdit>,
7389 server_id: LanguageServerId,
7390 version: Option<i32>,
7391 cx: &mut ModelContext<Self>,
7392 ) -> Task<Result<Vec<(Range<Anchor>, String)>>> {
7393 let snapshot = self.buffer_snapshot_for_lsp_version(buffer, server_id, version, cx);
7394 cx.background().spawn(async move {
7395 let snapshot = snapshot?;
7396 let mut lsp_edits = lsp_edits
7397 .into_iter()
7398 .map(|edit| (range_from_lsp(edit.range), edit.new_text))
7399 .collect::<Vec<_>>();
7400 lsp_edits.sort_by_key(|(range, _)| range.start);
7401
7402 let mut lsp_edits = lsp_edits.into_iter().peekable();
7403 let mut edits = Vec::new();
7404 while let Some((range, mut new_text)) = lsp_edits.next() {
7405 // Clip invalid ranges provided by the language server.
7406 let mut range = snapshot.clip_point_utf16(range.start, Bias::Left)
7407 ..snapshot.clip_point_utf16(range.end, Bias::Left);
7408
7409 // Combine any LSP edits that are adjacent.
7410 //
7411 // Also, combine LSP edits that are separated from each other by only
7412 // a newline. This is important because for some code actions,
7413 // Rust-analyzer rewrites the entire buffer via a series of edits that
7414 // are separated by unchanged newline characters.
7415 //
7416 // In order for the diffing logic below to work properly, any edits that
7417 // cancel each other out must be combined into one.
7418 while let Some((next_range, next_text)) = lsp_edits.peek() {
7419 if next_range.start.0 > range.end {
7420 if next_range.start.0.row > range.end.row + 1
7421 || next_range.start.0.column > 0
7422 || snapshot.clip_point_utf16(
7423 Unclipped(PointUtf16::new(range.end.row, u32::MAX)),
7424 Bias::Left,
7425 ) > range.end
7426 {
7427 break;
7428 }
7429 new_text.push('\n');
7430 }
7431 range.end = snapshot.clip_point_utf16(next_range.end, Bias::Left);
7432 new_text.push_str(next_text);
7433 lsp_edits.next();
7434 }
7435
7436 // For multiline edits, perform a diff of the old and new text so that
7437 // we can identify the changes more precisely, preserving the locations
7438 // of any anchors positioned in the unchanged regions.
7439 if range.end.row > range.start.row {
7440 let mut offset = range.start.to_offset(&snapshot);
7441 let old_text = snapshot.text_for_range(range).collect::<String>();
7442
7443 let diff = TextDiff::from_lines(old_text.as_str(), &new_text);
7444 let mut moved_since_edit = true;
7445 for change in diff.iter_all_changes() {
7446 let tag = change.tag();
7447 let value = change.value();
7448 match tag {
7449 ChangeTag::Equal => {
7450 offset += value.len();
7451 moved_since_edit = true;
7452 }
7453 ChangeTag::Delete => {
7454 let start = snapshot.anchor_after(offset);
7455 let end = snapshot.anchor_before(offset + value.len());
7456 if moved_since_edit {
7457 edits.push((start..end, String::new()));
7458 } else {
7459 edits.last_mut().unwrap().0.end = end;
7460 }
7461 offset += value.len();
7462 moved_since_edit = false;
7463 }
7464 ChangeTag::Insert => {
7465 if moved_since_edit {
7466 let anchor = snapshot.anchor_after(offset);
7467 edits.push((anchor..anchor, value.to_string()));
7468 } else {
7469 edits.last_mut().unwrap().1.push_str(value);
7470 }
7471 moved_since_edit = false;
7472 }
7473 }
7474 }
7475 } else if range.end == range.start {
7476 let anchor = snapshot.anchor_after(range.start);
7477 edits.push((anchor..anchor, new_text));
7478 } else {
7479 let edit_start = snapshot.anchor_after(range.start);
7480 let edit_end = snapshot.anchor_before(range.end);
7481 edits.push((edit_start..edit_end, new_text));
7482 }
7483 }
7484
7485 Ok(edits)
7486 })
7487 }
7488
7489 fn buffer_snapshot_for_lsp_version(
7490 &mut self,
7491 buffer: &ModelHandle<Buffer>,
7492 server_id: LanguageServerId,
7493 version: Option<i32>,
7494 cx: &AppContext,
7495 ) -> Result<TextBufferSnapshot> {
7496 const OLD_VERSIONS_TO_RETAIN: i32 = 10;
7497
7498 if let Some(version) = version {
7499 let buffer_id = buffer.read(cx).remote_id();
7500 let snapshots = self
7501 .buffer_snapshots
7502 .get_mut(&buffer_id)
7503 .and_then(|m| m.get_mut(&server_id))
7504 .ok_or_else(|| {
7505 anyhow!("no snapshots found for buffer {buffer_id} and server {server_id}")
7506 })?;
7507
7508 let found_snapshot = snapshots
7509 .binary_search_by_key(&version, |e| e.version)
7510 .map(|ix| snapshots[ix].snapshot.clone())
7511 .map_err(|_| {
7512 anyhow!("snapshot not found for buffer {buffer_id} server {server_id} at version {version}")
7513 })?;
7514
7515 snapshots.retain(|snapshot| snapshot.version + OLD_VERSIONS_TO_RETAIN >= version);
7516 Ok(found_snapshot)
7517 } else {
7518 Ok((buffer.read(cx)).text_snapshot())
7519 }
7520 }
7521
7522 pub fn language_servers(
7523 &self,
7524 ) -> impl '_ + Iterator<Item = (LanguageServerId, LanguageServerName, WorktreeId)> {
7525 self.language_server_ids
7526 .iter()
7527 .map(|((worktree_id, server_name), server_id)| {
7528 (*server_id, server_name.clone(), *worktree_id)
7529 })
7530 }
7531
7532 pub fn language_server_for_id(&self, id: LanguageServerId) -> Option<Arc<LanguageServer>> {
7533 if let LanguageServerState::Running { server, .. } = self.language_servers.get(&id)? {
7534 Some(server.clone())
7535 } else {
7536 None
7537 }
7538 }
7539
7540 pub fn language_servers_for_buffer(
7541 &self,
7542 buffer: &Buffer,
7543 cx: &AppContext,
7544 ) -> impl Iterator<Item = (&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
7545 self.language_server_ids_for_buffer(buffer, cx)
7546 .into_iter()
7547 .filter_map(|server_id| match self.language_servers.get(&server_id)? {
7548 LanguageServerState::Running {
7549 adapter, server, ..
7550 } => Some((adapter, server)),
7551 _ => None,
7552 })
7553 }
7554
7555 fn primary_language_servers_for_buffer(
7556 &self,
7557 buffer: &Buffer,
7558 cx: &AppContext,
7559 ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
7560 self.language_servers_for_buffer(buffer, cx).next()
7561 }
7562
7563 fn language_server_for_buffer(
7564 &self,
7565 buffer: &Buffer,
7566 server_id: LanguageServerId,
7567 cx: &AppContext,
7568 ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
7569 self.language_servers_for_buffer(buffer, cx)
7570 .find(|(_, s)| s.server_id() == server_id)
7571 }
7572
7573 fn language_server_ids_for_buffer(
7574 &self,
7575 buffer: &Buffer,
7576 cx: &AppContext,
7577 ) -> Vec<LanguageServerId> {
7578 if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language()) {
7579 let worktree_id = file.worktree_id(cx);
7580 language
7581 .lsp_adapters()
7582 .iter()
7583 .flat_map(|adapter| {
7584 let key = (worktree_id, adapter.name.clone());
7585 self.language_server_ids.get(&key).copied()
7586 })
7587 .collect()
7588 } else {
7589 Vec::new()
7590 }
7591 }
7592}
7593
7594fn glob_literal_prefix<'a>(glob: &'a str) -> &'a str {
7595 let mut literal_end = 0;
7596 for (i, part) in glob.split(path::MAIN_SEPARATOR).enumerate() {
7597 if part.contains(&['*', '?', '{', '}']) {
7598 break;
7599 } else {
7600 if i > 0 {
7601 // Acount for separator prior to this part
7602 literal_end += path::MAIN_SEPARATOR.len_utf8();
7603 }
7604 literal_end += part.len();
7605 }
7606 }
7607 &glob[..literal_end]
7608}
7609
7610impl WorktreeHandle {
7611 pub fn upgrade(&self, cx: &AppContext) -> Option<ModelHandle<Worktree>> {
7612 match self {
7613 WorktreeHandle::Strong(handle) => Some(handle.clone()),
7614 WorktreeHandle::Weak(handle) => handle.upgrade(cx),
7615 }
7616 }
7617
7618 pub fn handle_id(&self) -> usize {
7619 match self {
7620 WorktreeHandle::Strong(handle) => handle.id(),
7621 WorktreeHandle::Weak(handle) => handle.id(),
7622 }
7623 }
7624}
7625
7626impl OpenBuffer {
7627 pub fn upgrade(&self, cx: &impl BorrowAppContext) -> Option<ModelHandle<Buffer>> {
7628 match self {
7629 OpenBuffer::Strong(handle) => Some(handle.clone()),
7630 OpenBuffer::Weak(handle) => handle.upgrade(cx),
7631 OpenBuffer::Operations(_) => None,
7632 }
7633 }
7634}
7635
7636pub struct PathMatchCandidateSet {
7637 pub snapshot: Snapshot,
7638 pub include_ignored: bool,
7639 pub include_root_name: bool,
7640}
7641
7642impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
7643 type Candidates = PathMatchCandidateSetIter<'a>;
7644
7645 fn id(&self) -> usize {
7646 self.snapshot.id().to_usize()
7647 }
7648
7649 fn len(&self) -> usize {
7650 if self.include_ignored {
7651 self.snapshot.file_count()
7652 } else {
7653 self.snapshot.visible_file_count()
7654 }
7655 }
7656
7657 fn prefix(&self) -> Arc<str> {
7658 if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
7659 self.snapshot.root_name().into()
7660 } else if self.include_root_name {
7661 format!("{}/", self.snapshot.root_name()).into()
7662 } else {
7663 "".into()
7664 }
7665 }
7666
7667 fn candidates(&'a self, start: usize) -> Self::Candidates {
7668 PathMatchCandidateSetIter {
7669 traversal: self.snapshot.files(self.include_ignored, start),
7670 }
7671 }
7672}
7673
7674pub struct PathMatchCandidateSetIter<'a> {
7675 traversal: Traversal<'a>,
7676}
7677
7678impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
7679 type Item = fuzzy::PathMatchCandidate<'a>;
7680
7681 fn next(&mut self) -> Option<Self::Item> {
7682 self.traversal.next().map(|entry| {
7683 if let EntryKind::File(char_bag) = entry.kind {
7684 fuzzy::PathMatchCandidate {
7685 path: &entry.path,
7686 char_bag,
7687 }
7688 } else {
7689 unreachable!()
7690 }
7691 })
7692 }
7693}
7694
7695impl Entity for Project {
7696 type Event = Event;
7697
7698 fn release(&mut self, cx: &mut gpui::AppContext) {
7699 match &self.client_state {
7700 Some(ProjectClientState::Local { .. }) => {
7701 let _ = self.unshare_internal(cx);
7702 }
7703 Some(ProjectClientState::Remote { remote_id, .. }) => {
7704 let _ = self.client.send(proto::LeaveProject {
7705 project_id: *remote_id,
7706 });
7707 self.disconnected_from_host_internal(cx);
7708 }
7709 _ => {}
7710 }
7711 }
7712
7713 fn app_will_quit(
7714 &mut self,
7715 _: &mut AppContext,
7716 ) -> Option<std::pin::Pin<Box<dyn 'static + Future<Output = ()>>>> {
7717 let shutdown_futures = self
7718 .language_servers
7719 .drain()
7720 .map(|(_, server_state)| async {
7721 use LanguageServerState::*;
7722 match server_state {
7723 Running { server, .. } => server.shutdown()?.await,
7724 Starting(task) => task.await?.shutdown()?.await,
7725 }
7726 })
7727 .collect::<Vec<_>>();
7728
7729 Some(
7730 async move {
7731 futures::future::join_all(shutdown_futures).await;
7732 }
7733 .boxed(),
7734 )
7735 }
7736}
7737
7738impl Collaborator {
7739 fn from_proto(message: proto::Collaborator) -> Result<Self> {
7740 Ok(Self {
7741 peer_id: message.peer_id.ok_or_else(|| anyhow!("invalid peer id"))?,
7742 replica_id: message.replica_id as ReplicaId,
7743 })
7744 }
7745}
7746
7747impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
7748 fn from((worktree_id, path): (WorktreeId, P)) -> Self {
7749 Self {
7750 worktree_id,
7751 path: path.as_ref().into(),
7752 }
7753 }
7754}
7755
7756impl ProjectLspAdapterDelegate {
7757 fn new(project: &Project, cx: &ModelContext<Project>) -> Arc<Self> {
7758 Arc::new(Self {
7759 project: cx.handle(),
7760 http_client: project.client.http_client(),
7761 })
7762 }
7763}
7764
7765impl LspAdapterDelegate for ProjectLspAdapterDelegate {
7766 fn show_notification(&self, message: &str, cx: &mut AppContext) {
7767 self.project
7768 .update(cx, |_, cx| cx.emit(Event::Notification(message.to_owned())));
7769 }
7770
7771 fn http_client(&self) -> Arc<dyn HttpClient> {
7772 self.http_client.clone()
7773 }
7774}
7775
7776fn split_operations(
7777 mut operations: Vec<proto::Operation>,
7778) -> impl Iterator<Item = Vec<proto::Operation>> {
7779 #[cfg(any(test, feature = "test-support"))]
7780 const CHUNK_SIZE: usize = 5;
7781
7782 #[cfg(not(any(test, feature = "test-support")))]
7783 const CHUNK_SIZE: usize = 100;
7784
7785 let mut done = false;
7786 std::iter::from_fn(move || {
7787 if done {
7788 return None;
7789 }
7790
7791 let operations = operations
7792 .drain(..cmp::min(CHUNK_SIZE, operations.len()))
7793 .collect::<Vec<_>>();
7794 if operations.is_empty() {
7795 done = true;
7796 }
7797 Some(operations)
7798 })
7799}
7800
7801fn serialize_symbol(symbol: &Symbol) -> proto::Symbol {
7802 proto::Symbol {
7803 language_server_name: symbol.language_server_name.0.to_string(),
7804 source_worktree_id: symbol.source_worktree_id.to_proto(),
7805 worktree_id: symbol.path.worktree_id.to_proto(),
7806 path: symbol.path.path.to_string_lossy().to_string(),
7807 name: symbol.name.clone(),
7808 kind: unsafe { mem::transmute(symbol.kind) },
7809 start: Some(proto::PointUtf16 {
7810 row: symbol.range.start.0.row,
7811 column: symbol.range.start.0.column,
7812 }),
7813 end: Some(proto::PointUtf16 {
7814 row: symbol.range.end.0.row,
7815 column: symbol.range.end.0.column,
7816 }),
7817 signature: symbol.signature.to_vec(),
7818 }
7819}
7820
7821fn relativize_path(base: &Path, path: &Path) -> PathBuf {
7822 let mut path_components = path.components();
7823 let mut base_components = base.components();
7824 let mut components: Vec<Component> = Vec::new();
7825 loop {
7826 match (path_components.next(), base_components.next()) {
7827 (None, None) => break,
7828 (Some(a), None) => {
7829 components.push(a);
7830 components.extend(path_components.by_ref());
7831 break;
7832 }
7833 (None, _) => components.push(Component::ParentDir),
7834 (Some(a), Some(b)) if components.is_empty() && a == b => (),
7835 (Some(a), Some(b)) if b == Component::CurDir => components.push(a),
7836 (Some(a), Some(_)) => {
7837 components.push(Component::ParentDir);
7838 for _ in base_components {
7839 components.push(Component::ParentDir);
7840 }
7841 components.push(a);
7842 components.extend(path_components.by_ref());
7843 break;
7844 }
7845 }
7846 }
7847 components.iter().map(|c| c.as_os_str()).collect()
7848}
7849
7850impl Item for Buffer {
7851 fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
7852 File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
7853 }
7854
7855 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
7856 File::from_dyn(self.file()).map(|file| ProjectPath {
7857 worktree_id: file.worktree_id(cx),
7858 path: file.path().clone(),
7859 })
7860 }
7861}
7862
7863async fn wait_for_loading_buffer(
7864 mut receiver: postage::watch::Receiver<Option<Result<ModelHandle<Buffer>, Arc<anyhow::Error>>>>,
7865) -> Result<ModelHandle<Buffer>, Arc<anyhow::Error>> {
7866 loop {
7867 if let Some(result) = receiver.borrow().as_ref() {
7868 match result {
7869 Ok(buffer) => return Ok(buffer.to_owned()),
7870 Err(e) => return Err(e.to_owned()),
7871 }
7872 }
7873 receiver.next().await;
7874 }
7875}