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