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