use std::collections::HashMap;
use std::time::{Duration, Instant};
use std::cell::{Cell, RefCell};
use gpui::{
App, Bounds, Context, ElementId, Entity, FocusHandle, InteractiveElement, MouseButton,
MouseMoveEvent, Pixels, Point, ScrollHandle, SharedString, Window,
};
use crate::palette::Palette;
pub use crate::scroll::{ScrollAxis, ScrollDrag, apply_scroll_drag};
use crate::text_input::TextInput;
use crate::theme::{Theme, system_dark};
pub const COMBO_REVEAL: Duration = Duration::from_millis(140);
pub const SWITCH_SLIDE: Duration = Duration::from_millis(140);
pub const MOVE: Duration = Duration::from_millis(180);
pub const SCHEME_FADE: Duration = Duration::from_millis(240);
#[derive(Clone, Copy, Debug)]
struct Tween {
from: f32,
to: f32,
since: Instant,
duration: Duration,
touched: u64,
}
impl Tween {
fn value(&self) -> f32 {
if !self.running() {
return self.to;
}
let t = crate::easing::ease_out_cubic(crate::easing::progress(self.since, self.duration));
self.from + (self.to - self.from) * t
}
fn running(&self) -> bool {
self.since.elapsed() < self.duration
}
}
pub type ComboId = &'static str;
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum TrackAxis {
Horizontal,
Vertical,
Both,
}
#[derive(Clone, Debug)]
pub struct TrackDrag {
pub id: ComboId,
pub axis: TrackAxis,
pub stops: Option<u32>,
}
#[derive(Clone, Debug)]
pub struct TabDrag {
pub bar: ComboId,
pub from: usize,
pub to: usize,
pub moved: bool,
pub grab: f32,
pub pointer: f32,
}
#[derive(Clone, Debug)]
pub struct OpenMenu {
pub id: ComboId,
pub anchor: Point<Pixels>,
pub under: Option<Bounds<Pixels>>,
pub target: SharedString,
pub opened_at: Instant,
pub highlight: Option<usize>,
}
#[derive(Clone, Debug)]
pub struct OpenDialog {
pub id: ComboId,
pub opened_at: Instant,
pub closing: Option<Instant>,
}
#[derive(Clone, Debug)]
pub struct OpenPalette {
pub id: ComboId,
pub opened_at: Instant,
pub return_focus: Option<FocusHandle>,
}
#[derive(Clone, Copy, Debug)]
struct ListKeyboard {
highlight: usize,
query: u64,
}
const ROOT_FOCUS: &str = "vampir-root";
#[derive(Default)]
pub struct ControlState {
pub theme: Theme,
pub open_combo: Option<ComboId>,
pub combo_opened_at: Option<Instant>,
pub combo_closing: Option<(ComboId, Instant)>,
pub combo_opened_on: Option<usize>,
focus_handles: RefCell<HashMap<ElementId, FocusHandle>>,
pub menu_focus: Option<FocusHandle>,
pub menu_return_focus: Option<FocusHandle>,
pub dialog_return_focus: Option<FocusHandle>,
pub ring_hidden: bool,
dialog_trap: RefCell<Option<Vec<FocusHandle>>>,
pub combo_highlight: Option<usize>,
pub combo_dismissed: Option<ComboId>,
pub combo_dismissed_at: Option<Instant>,
pub anim: RefCell<HashMap<ElementId, (Instant, Duration)>>,
seen: RefCell<HashMap<ElementId, (u64, u64)>>,
tweens: RefCell<HashMap<ElementId, Tween>>,
streaks: RefCell<HashMap<ElementId, (u64, u64)>>,
frame: Cell<u64>,
time_scale: Option<f32>,
scroll_handles: RefCell<HashMap<ElementId, ScrollHandle>>,
pub scroll_drag: Option<ScrollDrag>,
pub track_drag: Option<TrackDrag>,
pub track_bounds: HashMap<ComboId, Bounds<Pixels>>,
pub tab_drag: Option<TabDrag>,
pub tab_bounds: HashMap<ComboId, Vec<Bounds<Pixels>>>,
pub tab_widths: HashMap<ComboId, HashMap<SharedString, f32>>,
pub slot_bounds: HashMap<ComboId, Vec<Bounds<Pixels>>>,
pub group_bounds: HashMap<ComboId, Bounds<Pixels>>,
pub measured: HashMap<ElementId, Bounds<Pixels>>,
pub menu: Option<OpenMenu>,
pub dialog: Option<OpenDialog>,
pub palette_overlay: Option<OpenPalette>,
lists: RefCell<HashMap<ElementId, ListKeyboard>>,
pub recording: Option<ComboId>,
}
impl ControlState {
pub fn new() -> Self {
Self::default()
}
pub fn is_combo_open(&self, combo: ComboId) -> bool {
self.open_combo == Some(combo)
}
pub fn close_combo(&mut self) {
self.combo_highlight = None;
if let Some(combo) = self.open_combo.take() {
self.combo_closing = Some((combo, Instant::now()));
}
}
pub fn open_combo(&mut self, combo: ComboId, chosen: usize) {
self.close_combo();
self.open_combo = Some(combo);
self.combo_opened_at = Some(Instant::now());
self.combo_opened_on = Some(chosen);
self.combo_highlight = Some(chosen);
self.combo_closing = None;
}
pub fn highlight_combo(&mut self, index: usize) {
self.combo_highlight = Some(index);
}
pub fn combo_highlight_or(&self, selected: usize) -> usize {
self.combo_highlight.unwrap_or(selected)
}
pub fn set_time_scale(&mut self, scale: f32) {
self.time_scale = (scale > 0.0 && scale != 1.0).then_some(scale);
}
pub fn time_scale(&self) -> Option<f32> {
self.time_scale
}
pub fn slow_motion_from_env(&mut self) -> Option<f32> {
let scale = std::env::var("VAMPIR_SLOW_MOTION")
.ok()
.and_then(|value| value.parse::<f32>().ok())?;
self.set_time_scale(scale);
self.time_scale
}
pub fn observe_appearance<V: ControlHost>(&mut self, window: &Window, cx: &mut Context<V>) {
self.theme.set_system_dark(system_dark(window));
let this = cx.weak_entity();
let subscription = window.observe_window_appearance(move |window, cx| {
let dark = system_dark(window);
this.update(cx, |this, cx| {
if this.control_state_mut().theme.set_system_dark(dark) {
cx.notify();
}
})
.ok();
});
self.theme.keep_appearance(subscription);
}
pub fn palette(&self) -> Palette {
let theme = &self.theme;
let darkness = self.tween(
"vampir-scheme-dark",
if theme.is_dark() { 1.0 } else { 0.0 },
SCHEME_FADE,
);
let held = theme
.hue_track()
.is_some_and(|track| self.is_dragging(track));
let hue = f64::from(if held {
self.snap("vampir-scheme-hue", theme.hue as f32)
} else {
self.tween_angle("vampir-scheme-hue", theme.hue as f32, MOVE)
});
if darkness <= 0.0 {
Palette::from_hue(hue, false)
} else if darkness >= 1.0 {
Palette::from_hue(hue, true)
} else {
Palette::mix(
Palette::from_hue(hue, false),
Palette::from_hue(hue, true),
darkness,
)
}
}
pub fn open_dialog(&mut self, id: ComboId) {
self.dismiss_popups();
self.dialog = Some(OpenDialog {
id,
opened_at: Instant::now(),
closing: None,
});
}
pub fn close_dialog(&mut self) {
if let Some(dialog) = self.dialog.as_mut()
&& dialog.closing.is_none()
{
dialog.closing = Some(Instant::now());
}
}
pub fn is_dialog_open(&self, id: ComboId) -> bool {
self.dialog
.as_ref()
.is_some_and(|dialog| dialog.id == id && dialog.closing.is_none())
}
pub fn dialog_fade(&self, id: ComboId) -> Option<(f32, bool)> {
let dialog = self.dialog.as_ref().filter(|dialog| dialog.id == id)?;
let (opacity, running) = match dialog.closing {
Some(since) => {
let t = crate::easing::progress(since, self.scaled(crate::easing::MODAL_EXIT));
(1.0 - crate::easing::ease_in_cubic(t), t < 1.0)
}
None => {
let t = crate::easing::progress(
dialog.opened_at,
self.scaled(crate::easing::MODAL_ENTER),
);
(crate::easing::ease_out_cubic(t), t < 1.0)
}
};
if dialog.closing.is_some() && !running {
return None;
}
Some((opacity, running))
}
pub fn open_palette(
&mut self,
id: ComboId,
query: &Entity<TextInput>,
window: &mut Window,
cx: &mut App,
) {
self.dismiss_popups();
let return_focus = self
.palette_overlay
.take()
.and_then(|open| open.return_focus)
.or_else(|| window.focused(cx));
self.palette_overlay = Some(OpenPalette {
id,
opened_at: Instant::now(),
return_focus,
});
self.highlight_list(id, 0);
query.update(cx, |input, cx| input.set_text("", cx));
let focus = query.read(cx).focus_handle.clone();
window.focus(&focus, cx);
}
pub fn close_palette(&mut self, window: &mut Window, cx: &mut App) {
if let Some(open) = self.palette_overlay.take() {
self.return_focus_to(open.return_focus, window, cx);
}
}
pub fn toggle_palette(
&mut self,
id: ComboId,
query: &Entity<TextInput>,
window: &mut Window,
cx: &mut App,
) {
if self.is_palette_open(id) {
self.close_palette(window, cx);
} else {
self.open_palette(id, query, window, cx);
}
}
pub fn is_palette_open(&self, id: ComboId) -> bool {
self.palette_overlay
.as_ref()
.is_some_and(|open| open.id == id)
}
pub fn list_highlight(&self, id: impl Into<ElementId>, query: &str) -> usize {
let hash = hash_of(query);
let mut lists = self.lists.borrow_mut();
let entry = lists.entry(id.into()).or_insert(ListKeyboard {
highlight: 0,
query: hash,
});
if entry.query != hash {
entry.query = hash;
entry.highlight = 0;
}
entry.highlight
}
pub fn list_position(&self, id: impl Into<ElementId>) -> usize {
self.lists
.borrow()
.get(&id.into())
.map_or(0, |list| list.highlight)
}
pub fn highlight_list(&self, id: impl Into<ElementId>, index: usize) {
let mut lists = self.lists.borrow_mut();
let entry = lists.entry(id.into()).or_insert(ListKeyboard {
highlight: 0,
query: hash_of(""),
});
entry.highlight = index;
}
pub fn scaled(&self, duration: Duration) -> Duration {
match self.time_scale {
Some(scale) => duration.mul_f32(scale),
None => duration,
}
}
pub fn mark_changed(&self, id: impl Into<ElementId>) {
self.anim
.borrow_mut()
.insert(id.into(), (Instant::now(), self.scaled(SWITCH_SLIDE)));
}
pub fn anim_progress(&self, id: &ElementId, duration: Duration) -> f32 {
self.anim
.borrow()
.get(id)
.map(|(since, _)| crate::easing::progress(*since, self.scaled(duration)))
.unwrap_or(1.0)
}
pub fn transition(&self, id: &ElementId, value: u64, duration: Duration) -> f32 {
let frame = self.frame.get();
let previous = self.seen.borrow_mut().insert(id.clone(), (value, frame));
if previous.is_some_and(|(previous, _)| previous != value) {
self.anim
.borrow_mut()
.insert(id.clone(), (Instant::now(), self.scaled(duration)));
}
self.anim_progress(id, duration)
}
pub fn blend(&self, id: &ElementId, on: bool, duration: Duration) -> f32 {
let t = crate::easing::ease_out_cubic(self.transition(id, u64::from(on), duration));
if on { t } else { 1.0 - t }
}
pub fn tween(&self, id: impl Into<ElementId>, target: f32, duration: Duration) -> f32 {
self.tween_inner(id.into(), None, target, duration)
}
pub fn tween_from(
&self,
id: impl Into<ElementId>,
initial: f32,
target: f32,
duration: Duration,
) -> f32 {
self.tween_inner(id.into(), Some(initial), target, duration)
}
pub fn tween_angle(&self, id: impl Into<ElementId>, degrees: f32, duration: Duration) -> f32 {
let id = id.into();
let target = match self.tweens.borrow().get(&id) {
Some(tween) => {
let here = tween.to;
let delta = (degrees - here).rem_euclid(360.0);
here + if delta > 180.0 { delta - 360.0 } else { delta }
}
None => degrees,
};
self.tween_inner(id, None, target, duration)
}
pub fn snap(&self, id: impl Into<ElementId>, value: f32) -> f32 {
let id = id.into();
self.tweens.borrow_mut().insert(
id,
Tween {
from: value,
to: value,
since: Instant::now(),
duration: Duration::ZERO,
touched: self.frame.get(),
},
);
value
}
fn tween_inner(
&self,
id: ElementId,
initial: Option<f32>,
target: f32,
duration: Duration,
) -> f32 {
let duration = self.scaled(duration);
let frame = self.frame.get();
let mut tweens = self.tweens.borrow_mut();
let tween = tweens.entry(id).or_insert_with(|| match initial {
Some(from) => Tween {
from,
to: target,
since: Instant::now(),
duration,
touched: frame,
},
None => Tween {
from: target,
to: target,
since: Instant::now(),
duration: Duration::ZERO,
touched: frame,
},
});
tween.touched = frame;
if tween.to != target {
tween.from = tween.value();
tween.to = target;
tween.since = Instant::now();
tween.duration = duration;
}
tween.value()
}
pub fn present(&self, group: impl Into<ElementId>) -> bool {
let frame = self.frame.get();
let mut streaks = self.streaks.borrow_mut();
let entry = streaks.entry(group.into()).or_insert((frame, frame));
if entry.1 + 1 < frame {
entry.0 = frame;
}
entry.1 = frame;
entry.0 < frame
}
pub fn scroll(&self, id: impl Into<ElementId>) -> ScrollHandle {
self.scroll_handles
.borrow_mut()
.entry(id.into())
.or_default()
.clone()
}
pub fn animating(&self) -> bool {
let frame = self.frame.get();
self.frame.set(frame + 1);
let stale = |touched: u64| touched + 1 < frame;
self.tweens
.borrow_mut()
.retain(|_, tween| !stale(tween.touched));
self.seen
.borrow_mut()
.retain(|_, (_, touched)| !stale(*touched));
self.streaks
.borrow_mut()
.retain(|_, (_, touched)| !stale(*touched));
if self
.anim
.borrow()
.values()
.any(|(since, duration)| since.elapsed() < *duration)
{
return true;
}
if self.tweens.borrow().values().any(Tween::running) {
return true;
}
let reveal = self.scaled(COMBO_REVEAL);
if self.open_combo.is_some()
&& self
.combo_opened_at
.is_some_and(|since| since.elapsed() < reveal)
{
return true;
}
if self
.menu
.as_ref()
.is_some_and(|menu| menu.opened_at.elapsed() < reveal)
{
return true;
}
if self
.palette_overlay
.as_ref()
.is_some_and(|open| open.opened_at.elapsed() < reveal)
{
return true;
}
if let Some(dialog) = &self.dialog
&& self
.dialog_fade(dialog.id)
.is_some_and(|(_, running)| running)
{
return true;
}
self.combo_closing
.is_some_and(|(_, since)| since.elapsed() < reveal)
}
pub fn prune_anims(&mut self) {
self.anim
.borrow_mut()
.retain(|_, (since, duration)| since.elapsed() < *duration);
}
pub fn scroll_dragging(&self) -> bool {
self.scroll_drag.is_some()
}
pub fn track_dragging(&self) -> bool {
self.track_drag.is_some()
}
pub fn is_dragging(&self, id: ComboId) -> bool {
self.track_drag.as_ref().is_some_and(|drag| drag.id == id)
}
pub fn begin_track_drag(&mut self, id: ComboId, axis: TrackAxis, stops: Option<u32>) {
self.track_drag = Some(TrackDrag { id, axis, stops });
}
pub fn track_ratio_at(&self, position: Point<Pixels>) -> Option<(ComboId, Point<f32>)> {
let drag = self.track_drag.as_ref()?;
let bounds = self.track_bounds.get(drag.id)?;
let width = f32::from(bounds.size.width);
let height = f32::from(bounds.size.height);
if width <= 0.0 || height <= 0.0 {
return None;
}
let snap = |ratio: f32| match drag.stops {
Some(stops) if stops >= 2 => {
let last = (stops - 1) as f32;
(ratio * last).round() / last
}
_ => ratio,
};
let x = ((f32::from(position.x) - f32::from(bounds.origin.x)) / width).clamp(0.0, 1.0);
let y = ((f32::from(position.y) - f32::from(bounds.origin.y)) / height).clamp(0.0, 1.0);
let point = match drag.axis {
TrackAxis::Horizontal => Point::new(snap(x), y),
TrackAxis::Vertical => Point::new(x, snap(y)),
TrackAxis::Both => Point::new(snap(x), snap(y)),
};
Some((drag.id, point))
}
pub fn tab_at(&self, bar: ComboId, position: Point<Pixels>) -> Option<usize> {
self.tab_bounds
.get(bar)?
.iter()
.position(|bounds| bounds.contains(&position))
}
pub fn drag_tab_to(&mut self, position: Point<Pixels>) -> bool {
let pointer = f32::from(position.x);
let Some(drag) = self.tab_drag.as_mut() else {
return false;
};
drag.pointer = pointer;
drag.moved = true;
let (bar, to) = (drag.bar, drag.to);
let Some(bounds) = self.tab_bounds.get(bar) else {
return true;
};
let Some(current) = bounds.get(to) else {
return true;
};
let mut target = None;
if pointer < f32::from(current.left())
&& to > 0
&& let Some(previous) = bounds.get(to - 1)
&& pointer < f32::from(previous.center().x)
{
target = Some(to - 1);
}
if pointer > f32::from(current.right())
&& let Some(next) = bounds.get(to + 1)
&& pointer > f32::from(next.center().x)
{
target = Some(to + 1);
}
if let Some(to) = target {
self.tab_drag.as_mut().expect("checked above").to = to;
}
true
}
pub fn open_menu(
&mut self,
id: ComboId,
anchor: Point<Pixels>,
target: impl Into<SharedString>,
) {
self.close_combo();
self.menu = Some(OpenMenu {
id,
anchor,
under: None,
target: target.into(),
opened_at: Instant::now(),
highlight: None,
});
}
pub fn open_menu_under(
&mut self,
id: ComboId,
under: Bounds<Pixels>,
target: impl Into<SharedString>,
) {
self.close_combo();
self.menu = Some(OpenMenu {
id,
anchor: under.origin,
under: Some(under),
target: target.into(),
opened_at: Instant::now(),
highlight: None,
});
}
pub fn focus(&self, id: impl Into<ElementId>, cx: &App) -> FocusHandle {
self.focus_handles
.borrow_mut()
.entry(id.into())
.or_insert_with(|| cx.focus_handle().tab_stop(true))
.clone()
}
pub fn root_focus(&self, cx: &App) -> FocusHandle {
self.focus_handles
.borrow_mut()
.entry(ElementId::Name(ROOT_FOCUS.into()))
.or_insert_with(|| cx.focus_handle())
.clone()
}
pub fn focus_root(&self, window: &mut Window, cx: &mut App) {
window.focus(&self.root_focus(cx), cx);
}
pub fn return_focus_to(
&self,
previous: Option<FocusHandle>,
window: &mut Window,
cx: &mut App,
) {
match previous {
Some(handle) => window.focus(&handle, cx),
None => self.focus_root(window, cx),
}
}
pub fn set_dialog_trap(&self, buttons: Option<Vec<FocusHandle>>) {
*self.dialog_trap.borrow_mut() = buttons;
}
pub fn trap_next(&self, window: &Window, backward: bool) -> Option<FocusHandle> {
let trap = self.dialog_trap.borrow();
let buttons = trap.as_ref()?;
let here = buttons
.iter()
.position(|handle| handle.is_focused(window))?;
let count = buttons.len();
let next = if backward {
(here + count - 1) % count
} else {
(here + 1) % count
};
Some(buttons[next].clone())
}
pub fn restore_dialog_focus(&mut self, window: &mut Window, cx: &mut App) {
let previous = self.dialog_return_focus.take();
self.return_focus_to(previous, window, cx);
}
pub fn menu_focus(&mut self, cx: &App) -> FocusHandle {
self.menu_focus
.get_or_insert_with(|| cx.focus_handle())
.clone()
}
pub fn highlight_menu(&mut self, index: Option<usize>) {
if let Some(menu) = self.menu.as_mut() {
menu.highlight = index;
}
}
pub fn menu_highlight(&self) -> Option<usize> {
self.menu.as_ref().and_then(|menu| menu.highlight)
}
pub fn dismiss_popups(&mut self) {
self.close_combo();
self.close_menu();
}
pub fn dismiss_overlays(&mut self, window: &mut Window, cx: &mut App) -> bool {
let had_popup = self.open_combo.is_some() || self.menu.is_some();
self.dismiss_popups();
if self.palette_overlay.is_some() {
self.close_palette(window, cx);
return true;
}
had_popup
}
pub fn close_menu(&mut self) {
self.menu = None;
}
pub fn is_menu_open(&self, id: ComboId) -> bool {
self.menu.as_ref().is_some_and(|menu| menu.id == id)
}
pub fn menu_target(&self) -> Option<&str> {
self.menu.as_ref().map(|menu| menu.target.as_ref())
}
pub fn menu_opened_at(&self) -> Option<Instant> {
self.menu.as_ref().map(|menu| menu.opened_at)
}
pub fn dragging_anything(&self) -> bool {
self.scroll_drag.is_some() || self.track_drag.is_some() || self.tab_drag.is_some()
}
pub fn end_drag(&mut self) -> Option<(ComboId, usize, usize)> {
self.scroll_drag = None;
self.track_drag = None;
self.combo_dismissed = None;
self.combo_dismissed_at = None;
self.tab_drag
.take()
.filter(|drag| drag.moved && drag.from != drag.to)
.map(|drag| (drag.bar, drag.from, drag.to))
}
}
pub trait ControlHost: Sized + 'static {
fn control_state(&self) -> &ControlState;
fn control_state_mut(&mut self) -> &mut ControlState;
fn track_dragged(&mut self, _id: ComboId, _at: Point<f32>, _cx: &mut Context<Self>) {}
fn tabs_reordered(&mut self, _bar: ComboId, _from: usize, _to: usize, _cx: &mut Context<Self>) {
}
fn forwarded_mouse_move(
&mut self,
event: &MouseMoveEvent,
_window: &mut Window,
cx: &mut Context<Self>,
) {
if mouse_moved(self, event, cx) {
cx.notify();
}
}
fn forwarded_mouse_up(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
end_drags(self, cx);
cx.notify();
}
}
pub fn mouse_moved<V: ControlHost>(
host: &mut V,
event: &MouseMoveEvent,
cx: &mut Context<V>,
) -> bool {
if !event.dragging() {
if host.control_state().dragging_anything() {
end_drags(host, cx);
return true;
}
return false;
}
continue_drags(host, event.position, cx)
}
pub fn handle_mouse<E: InteractiveElement, V: ControlHost>(root: E, cx: &mut Context<V>) -> E {
root.on_mouse_move(cx.listener(|this, event: &MouseMoveEvent, _window, cx| {
if mouse_moved(this, event, cx) {
cx.notify();
}
}))
.on_mouse_up(
MouseButton::Left,
cx.listener(|this, _event, _window, cx| {
end_drags(this, cx);
cx.notify();
}),
)
}
fn hash_of(text: &str) -> u64 {
use std::hash::{Hash, Hasher};
let mut hasher = std::collections::hash_map::DefaultHasher::new();
text.hash(&mut hasher);
hasher.finish()
}
pub fn continue_drags<V: ControlHost>(
host: &mut V,
position: Point<Pixels>,
cx: &mut Context<V>,
) -> bool {
let mut moved = false;
if let Some(drag) = &host.control_state().scroll_drag {
let along = match drag.axis {
ScrollAxis::Vertical => f32::from(position.y),
ScrollAxis::Horizontal => f32::from(position.x),
};
apply_scroll_drag(drag, along);
moved = true;
}
if let Some((id, at)) = host.control_state().track_ratio_at(position) {
let theme = &mut host.control_state_mut().theme;
if theme.hue_track() == Some(id) {
theme.hue = Theme::hue_from_track(at.x);
} else {
host.track_dragged(id, at, cx);
}
moved = true;
}
if host.control_state_mut().drag_tab_to(position) {
moved = true;
}
moved
}
pub fn end_drags<V: ControlHost>(host: &mut V, cx: &mut Context<V>) {
if let Some((bar, from, to)) = host.control_state_mut().end_drag() {
host.tabs_reordered(bar, from, to, cx);
}
}
#[cfg(test)]
mod tests {
use super::{ControlState, Palette, SCHEME_FADE};
use gpui::{Point, px};
fn at(x: f32, y: f32) -> Point<gpui::Pixels> {
gpui::point(px(x), px(y))
}
#[test]
fn a_menu_carries_its_target_until_it_closes() {
let mut state = ControlState::new();
assert_eq!(state.menu_target(), None);
state.open_menu("row", at(10.0, 20.0), "budget.csv");
assert_eq!(state.menu_target(), Some("budget.csv"));
assert!(state.is_menu_open("row"));
state.close_menu();
assert_eq!(state.menu_target(), None);
assert_eq!(state.menu_opened_at(), None);
}
#[test]
fn reopening_a_menu_retargets_it() {
let mut state = ControlState::new();
state.open_menu("row", at(0.0, 0.0), "report.pdf");
state.open_menu("row", at(40.0, 60.0), "budget.csv");
assert_eq!(state.menu_target(), Some("budget.csv"));
}
#[test]
fn a_new_tween_starts_at_its_target() {
let state = ControlState::new();
assert_eq!(state.tween("pill", 40.0, super::MOVE), 40.0);
let moving = state.tween("pill", 100.0, super::MOVE);
assert!((40.0..100.0).contains(&moving), "{moving}");
}
#[test]
fn tween_from_starts_where_told() {
let state = ControlState::new();
let v = state.tween_from("row", 0.0, 1.0, super::MOVE);
assert!(v < 0.5, "{v}");
assert!(state.animating());
}
#[test]
fn angles_take_the_short_way() {
let state = ControlState::new();
state.tween_angle("hue", 350.0, super::MOVE);
let v = state.tween_angle("hue", 10.0, super::MOVE);
assert!(v >= 350.0, "{v}");
}
#[test]
fn a_zero_length_tween_is_finished() {
assert_eq!(
crate::easing::progress(std::time::Instant::now(), std::time::Duration::ZERO),
1.0
);
let state = ControlState::new();
for _ in 0..1000 {
let v = state.tween("fresh", 3.0, super::MOVE);
assert!(v.is_finite() && v == 3.0, "{v}");
let s = state.snap("snapped", 4.0);
assert_eq!(state.tween("snapped", 4.0, super::MOVE), s);
}
}
#[test]
fn snap_lands_at_once() {
let state = ControlState::new();
state.tween("thumb", 0.2, super::MOVE);
assert_eq!(state.snap("thumb", 0.9), 0.9);
assert_eq!(state.tween("thumb", 0.9, super::MOVE), 0.9);
assert!(!state.animating());
}
#[test]
fn presence_is_per_frame_and_consistent() {
let state = ControlState::new();
assert!(!state.present("list"));
assert!(!state.present("list"), "second row, same frame");
state.animating(); assert!(state.present("list"));
state.animating();
state.animating();
state.animating();
assert!(!state.present("list"));
}
#[test]
fn stale_records_are_retired() {
let state = ControlState::new();
let id = gpui::ElementId::Name("check".into());
state.transition(&id, 1, super::SWITCH_SLIDE);
state.animating();
state.animating();
state.animating();
let t = state.transition(&id, 0, super::SWITCH_SLIDE);
assert_eq!(t, 1.0);
}
#[test]
fn time_scale_stretches_every_duration() {
let mut state = ControlState::new();
state.set_time_scale(1000.0);
state.tween("x", 0.0, std::time::Duration::from_millis(1));
state.tween("x", 1.0, std::time::Duration::from_millis(1));
std::thread::sleep(std::time::Duration::from_millis(10));
let v = state.tween("x", 1.0, std::time::Duration::from_millis(1));
assert!(v < 0.2, "{v}");
let id = gpui::ElementId::Name("flip".into());
state.transition(&id, 0, std::time::Duration::from_millis(1));
state.transition(&id, 1, std::time::Duration::from_millis(1));
std::thread::sleep(std::time::Duration::from_millis(10));
let t = state.transition(&id, 1, std::time::Duration::from_millis(1));
assert!(t < 0.2, "{t}");
}
#[test]
fn a_dialog_fades_out_before_it_is_gone() {
let mut state = ControlState::new();
assert_eq!(state.dialog_fade("confirm"), None);
state.open_dialog("confirm");
assert!(state.is_dialog_open("confirm"));
assert!(!state.is_dialog_open("other"));
let (opacity, running) = state.dialog_fade("confirm").expect("on screen");
assert!(running && opacity < 1.0, "{opacity}");
state.close_dialog();
assert!(!state.is_dialog_open("confirm"), "closing is not open");
assert!(state.dialog_fade("confirm").is_some(), "still fading");
assert!(state.animating());
let first = state.dialog.as_ref().and_then(|d| d.closing);
state.close_dialog();
assert_eq!(state.dialog.as_ref().and_then(|d| d.closing), first);
std::thread::sleep(crate::easing::MODAL_EXIT + std::time::Duration::from_millis(20));
assert_eq!(state.dialog_fade("confirm"), None);
assert!(!state.animating());
}
#[test]
fn a_new_query_puts_the_keyboard_back_on_the_best_match() {
let state = ControlState::new();
assert_eq!(state.list_highlight("results", "re"), 0);
state.highlight_list("results", 2);
assert_eq!(state.list_highlight("results", "re"), 2);
assert_eq!(state.list_position("results"), 2);
assert_eq!(state.list_highlight("results", "rep"), 0);
state.highlight_list("commands", 4);
assert_eq!(state.list_highlight("results", "rep"), 0);
assert_eq!(state.list_position("commands"), 4);
}
#[test]
fn the_palette_crosses_over_rather_than_cutting() {
let mut state = ControlState::new();
let light = state.palette();
assert!(!light.is_dark);
state.theme.scheme = crate::theme::Scheme::Dark;
let crossing = state.palette();
assert!(state.animating(), "the scheme is crossing over");
assert_ne!(crossing.backdrop, light.backdrop);
assert_ne!(
crossing.backdrop,
Palette::from_hue(state.theme.hue, true).backdrop
);
std::thread::sleep(SCHEME_FADE + std::time::Duration::from_millis(20));
assert_eq!(state.palette(), Palette::from_hue(state.theme.hue, true));
}
#[test]
fn an_opening_is_identifiable_while_it_lasts() {
let mut state = ControlState::new();
state.open_menu("row", at(0.0, 0.0), "report.pdf");
let opening = state.menu_opened_at().expect("a menu is open");
assert_eq!(state.menu_opened_at(), Some(opening));
state.close_menu();
state.open_menu("row", at(0.0, 0.0), "report.pdf");
assert!(state.menu_opened_at().is_some());
}
}