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