use std::future::Future;
use std::time::Duration;
#[cfg(not(test))]
use ratatui::crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
use crate::api::ApiError;
use super::actions::ActionPrepError;
pub(super) enum RequestOutcome<T> {
Completed(T),
Cancelled,
}
pub(super) async fn run_cancellable<T>(
fut: impl Future<Output = T>,
cancel: impl Future<Output = ()>,
) -> RequestOutcome<T> {
tokio::select! {
result = fut => RequestOutcome::Completed(result),
() = cancel => RequestOutcome::Cancelled,
}
}
pub(super) async fn cancellable_api<T>(
fut: impl Future<Output = Result<T, ApiError>>,
) -> Result<T, ActionPrepError> {
match run_cancellable(fut, wait_for_cancel_key()).await {
RequestOutcome::Completed(result) => Ok(result?),
RequestOutcome::Cancelled => Err(ActionPrepError::Cancelled),
}
}
#[cfg(not(test))]
fn is_cancel_key(key: KeyEvent) -> bool {
key.code == KeyCode::Esc
|| (key.code == KeyCode::Char('c') && key.modifiers.contains(KeyModifiers::CONTROL))
}
#[cfg(not(test))]
pub(super) async fn wait_for_cancel_key() {
loop {
let ready =
tokio::task::spawn_blocking(|| event::poll(Duration::from_millis(50)).unwrap_or(false))
.await
.unwrap_or(false);
if ready
&& let Ok(Event::Key(key)) = event::read()
&& key.kind == KeyEventKind::Press
&& is_cancel_key(key)
{
return;
}
}
}
#[cfg(test)]
thread_local! {
static TEST_CANCEL_DELAY: std::cell::Cell<Option<Duration>> = const { std::cell::Cell::new(None) };
}
#[cfg(test)]
pub(super) struct TestCancelGuard;
#[cfg(test)]
impl Drop for TestCancelGuard {
fn drop(&mut self) {
TEST_CANCEL_DELAY.with(|cell| cell.set(None));
}
}
#[cfg(test)]
#[must_use]
pub(super) fn arm_test_cancel(delay: Duration) -> TestCancelGuard {
TEST_CANCEL_DELAY.with(|cell| cell.set(Some(delay)));
TestCancelGuard
}
#[cfg(test)]
pub(super) async fn wait_for_cancel_key() {
let delay = TEST_CANCEL_DELAY.with(std::cell::Cell::get);
match delay {
Some(delay) => tokio::time::sleep(delay).await,
None => std::future::pending().await,
}
}