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