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