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