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