use gpui::{Context, Pixels, Task, px};
use instant::Duration;
static INTERVAL: Duration = Duration::from_millis(500);
static PAUSE_DELAY: Duration = Duration::from_millis(300);
#[cfg(not(target_os = "macos"))]
pub(super) const CURSOR_WIDTH: Pixels = px(2.);
#[cfg(target_os = "macos")]
pub(super) const CURSOR_WIDTH: Pixels = px(1.5);
pub(crate) struct BlinkCursor {
visible: bool,
paused: bool,
epoch: usize,
_task: Task<()>,
}
impl BlinkCursor {
pub(crate) fn new() -> Self {
Self {
visible: false,
paused: false,
epoch: 0,
_task: Task::ready(()),
}
}
pub(crate) fn start(&mut self, cx: &mut Context<Self>) {
self.blink(self.epoch, cx);
}
pub(crate) fn stop(&mut self, cx: &mut Context<Self>) {
self.epoch = 0;
cx.notify();
}
fn next_epoch(&mut self) -> usize {
self.epoch += 1;
self.epoch
}
fn blink(&mut self, epoch: usize, cx: &mut Context<Self>) {
if self.paused || epoch != self.epoch {
self.visible = true;
return;
}
self.visible = !self.visible;
cx.notify();
let epoch = self.next_epoch();
self._task = cx.spawn(async move |this, cx| {
cx.background_executor().timer(INTERVAL).await;
if let Some(this) = this.upgrade() {
this.update(cx, |this, cx| this.blink(epoch, cx));
}
});
}
pub(crate) fn visible(&self) -> bool {
self.paused || self.visible
}
pub(crate) fn pause(&mut self, cx: &mut Context<Self>) {
self.paused = true;
self.visible = true;
cx.notify();
let epoch = self.next_epoch();
self._task = cx.spawn(async move |this, cx| {
cx.background_executor().timer(PAUSE_DELAY).await;
if let Some(this) = this.upgrade() {
this.update(cx, |this, cx| {
this.paused = false;
this.blink(epoch, cx);
});
}
});
}
}
#[cfg(test)]
mod tests {
use super::*;
use gpui::{AppContext as _, TestAppContext};
#[gpui::test]
fn repeated_pauses_keep_cursor_visible_until_idle(cx: &mut TestAppContext) {
let cursor = cx.new(|_| BlinkCursor::new());
assert!(!cursor.read_with(cx, |cursor, _| cursor.visible()));
for _ in 0..5 {
cursor.update(cx, |cursor, cx| cursor.pause(cx));
cx.run_until_parked();
cx.executor().advance_clock(Duration::from_millis(200));
cx.run_until_parked();
assert!(cursor.read_with(cx, |cursor, _| cursor.visible()));
}
cx.executor().advance_clock(Duration::from_millis(100));
cx.run_until_parked();
assert!(!cursor.read_with(cx, |cursor, _| cursor.visible()));
cx.executor().advance_clock(INTERVAL);
cx.run_until_parked();
assert!(cursor.read_with(cx, |cursor, _| cursor.visible()));
}
}