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