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