use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::hash::{BuildHasherDefault, DefaultHasher, Hash, Hasher};
use std::rc::Rc;
use std::time::{Duration, Instant};
use gpui::{
App, Bounds, Context, ElementId, Entity, FocusHandle, InteractiveElement, MouseButton,
MouseMoveEvent, Pixels, Point, ScrollHandle, SharedString, Window,
};
use crate::palette::{Palette, normalized_saturation};
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);
pub type ComboId = &'static str;
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct Tag(u64);
impl Tag {
pub fn new(of: impl Hash) -> Self {
let mut hasher = DefaultHasher::new();
of.hash(&mut hasher);
Tag(hasher.finish())
}
pub fn with(self, and: impl Hash) -> Self {
Tag::new((self.0, and))
}
pub(crate) fn element_id(self) -> ElementId {
("vampir", self.0).into()
}
}
impl From<&str> for Tag {
fn from(text: &str) -> Self {
Tag::new(text)
}
}
impl From<String> for Tag {
fn from(text: String) -> Self {
Tag::new(text.as_str())
}
}
impl From<SharedString> for Tag {
fn from(text: SharedString) -> Self {
Tag::new(text.as_ref())
}
}
impl From<&SharedString> for Tag {
fn from(text: &SharedString) -> Self {
Tag::new(text.as_ref())
}
}
impl From<ElementId> for Tag {
fn from(id: ElementId) -> Self {
Tag::new(id)
}
}
impl From<&ElementId> for Tag {
fn from(id: &ElementId) -> Self {
Tag::new(id)
}
}
impl<A: Hash, B: Hash> From<(A, B)> for Tag {
fn from(parts: (A, B)) -> Self {
Tag::new(parts)
}
}
impl<A: Hash, B: Hash, C: Hash> From<(A, B, C)> for Tag {
fn from(parts: (A, B, C)) -> Self {
Tag::new(parts)
}
}
#[derive(Default)]
struct TagHasher(u64);
impl Hasher for TagHasher {
fn finish(&self) -> u64 {
self.0
}
fn write_u64(&mut self, tag: u64) {
self.0 = tag;
}
fn write(&mut self, bytes: &[u8]) {
for byte in bytes {
self.0 = (self.0 ^ u64::from(*byte)).wrapping_mul(0x0100_0000_01b3);
}
}
}
type TagMap<T> = HashMap<Tag, T, BuildHasherDefault<TagHasher>>;
#[derive(Clone, Copy)]
enum Kind {
Flip,
Tween,
Streak,
List,
Bounds,
Reveal,
}
impl Kind {
fn slot(self, tag: Tag) -> Tag {
const SALT: [u64; 6] = [
0x9E37_79B9_7F4A_7C15,
0xD1B5_4A32_D192_ED03,
0x8CB9_2BA7_2F3D_8DD7,
0x5851_F42D_4C95_7F2D,
0x2545_F491_4F6C_DD1D,
0xA24B_1CD7_95E8_6F03,
];
Tag(tag.0 ^ SALT[self as usize])
}
}
#[derive(Clone, Copy, Debug)]
enum Record {
Flip {
value: u64,
since: u64,
duration: u32,
},
Tween {
from: f32,
to: f32,
since: u64,
duration: u32,
},
Streak { started: u32 },
List {
highlight: usize,
query: u64,
item: u64,
chosen: bool,
},
Bounds(Bounds<Pixels>),
Reveal {
selection: Tag,
pending: bool,
retries: u8,
},
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ListChange {
Same,
Reset,
Moved,
}
#[derive(Clone, Copy, Debug)]
struct Entry {
touched: u32,
record: Record,
}
fn progress_of(now: u64, since: u64, duration: u32) -> f32 {
if duration == 0 {
return 1.0;
}
(now.saturating_sub(since) as f32 / duration as f32).clamp(0.0, 1.0)
}
fn tween_value(now: u64, from: f32, to: f32, since: u64, duration: u32) -> f32 {
let t = progress_of(now, since, duration);
if t >= 1.0 {
return to;
}
from + (to - from) * crate::easing::ease_out_cubic(t)
}
fn micros(duration: Duration) -> u32 {
u32::try_from(duration.as_micros()).unwrap_or(u32::MAX)
}
fn next_dialog_button(indices: &[usize], current: Option<usize>, backward: bool) -> Option<usize> {
let count = indices.len();
if count == 0 {
return None;
}
let here = current.and_then(|current| indices.iter().position(|&index| index == current));
let next = match (here, backward) {
(Some(here), true) => (here + count - 1) % count,
(Some(here), false) => (here + 1) % count,
(None, true) => count - 1,
(None, false) => 0,
};
Some(indices[next])
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum TrackAxis {
Horizontal,
Vertical,
Both,
}
#[derive(Clone, Copy, Debug)]
pub struct TrackDrag {
pub id: ComboId,
pub axis: TrackAxis,
pub stops: Option<u32>,
}
#[derive(Clone, Copy, Debug)]
pub struct TabDrag {
pub bar: ComboId,
pub axis: TrackAxis,
pub from: usize,
pub to: usize,
pub moved: bool,
pub grab: f32,
pub pressed: f32,
pub pointer: f32,
}
fn tab_start(bounds: Bounds<Pixels>, axis: TrackAxis) -> f32 {
match axis {
TrackAxis::Vertical => f32::from(bounds.top()),
_ => f32::from(bounds.left()),
}
}
fn tab_end(bounds: Bounds<Pixels>, axis: TrackAxis) -> f32 {
match axis {
TrackAxis::Vertical => f32::from(bounds.bottom()),
_ => f32::from(bounds.right()),
}
}
pub const TAB_DRAG_THRESHOLD: f32 = 4.0;
enum Drag {
Scroll(ScrollDrag),
Track(TrackDrag),
Tab(TabDrag),
}
#[derive(Clone, Copy, Debug)]
pub struct OpenCombo {
pub id: ComboId,
pub opened_at: Instant,
pub opened_on: usize,
pub highlight: Option<usize>,
pub closing: Option<Instant>,
}
#[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>,
pub(crate) levels: Vec<MenuBranch>,
pub(crate) level_changed_at: Option<Instant>,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct MenuBranch {
pub index: usize,
pub highlight: usize,
pub identity: u64,
pub scroll: Point<Pixels>,
}
#[derive(Clone, Copy, 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>,
}
const ROOT_FOCUS: &str = "vampir-root";
pub struct ControlState {
pub theme: Theme,
epoch: Instant,
frame: Cell<u32>,
time_scale: Option<f32>,
records: RefCell<TagMap<Entry>>,
color_pads: RefCell<crate::swatch::PadCache>,
measured: TagMap<Bounds<Pixels>>,
focus_handles: RefCell<TagMap<FocusHandle>>,
scroll_handles: RefCell<TagMap<ScrollHandle>>,
combo: Option<OpenCombo>,
combo_dismissed: Option<(ComboId, Instant)>,
pub menu: Option<OpenMenu>,
pub menu_focus: Option<FocusHandle>,
pub menu_return_focus: Option<FocusHandle>,
pub dialog: Option<OpenDialog>,
pub dialog_return_focus: Option<FocusHandle>,
dialog_trap: RefCell<Option<(ComboId, Vec<usize>)>>,
pub palette_overlay: Option<OpenPalette>,
pub recording: Option<ComboId>,
pub(crate) recording_keys: Option<[gpui::Subscription; 2]>,
pub(crate) recording_activation: Option<&'static str>,
pub ring_hidden: bool,
drag: Option<Drag>,
tab_drag_invalidated: Cell<bool>,
floating_hints: bool,
pub(crate) hint_key: Option<String>,
pub(crate) hint_timer: Option<gpui::Task<()>>,
pub(crate) toast_timer: Option<gpui::Task<()>>,
}
impl Default for ControlState {
fn default() -> Self {
Self::new()
}
}
impl ControlState {
pub fn new() -> Self {
Self {
theme: Theme::default(),
epoch: Instant::now(),
frame: Cell::new(0),
time_scale: None,
records: RefCell::default(),
color_pads: RefCell::default(),
measured: TagMap::default(),
focus_handles: RefCell::default(),
scroll_handles: RefCell::default(),
combo: None,
combo_dismissed: None,
menu: None,
menu_focus: None,
menu_return_focus: None,
dialog: None,
dialog_return_focus: None,
dialog_trap: RefCell::new(None),
palette_overlay: None,
recording: None,
recording_keys: None,
recording_activation: None,
ring_hidden: false,
drag: None,
tab_drag_invalidated: Cell::new(false),
floating_hints: false,
hint_key: None,
hint_timer: None,
toast_timer: None,
}
}
pub fn set_floating_hints(&mut self, floating: bool) {
self.floating_hints = floating;
}
pub fn floating_hints(&self) -> bool {
self.floating_hints
}
fn now(&self) -> u64 {
u64::try_from(self.epoch.elapsed().as_micros()).unwrap_or(u64::MAX)
}
pub fn is_combo_open(&self, combo: ComboId) -> bool {
self.combo
.as_ref()
.is_some_and(|open| open.id == combo && open.closing.is_none())
}
pub fn close_combo(&mut self) {
if let Some(open) = self.combo.as_mut()
&& open.closing.is_none()
{
open.closing = Some(Instant::now());
open.highlight = None;
}
}
pub fn open_combo(&mut self, combo: ComboId, chosen: usize) {
self.combo = Some(OpenCombo {
id: combo,
opened_at: Instant::now(),
opened_on: chosen,
highlight: Some(chosen),
closing: None,
});
}
pub fn highlight_combo(&mut self, index: usize) {
if let Some(open) = self.combo.as_mut()
&& open.closing.is_none()
{
open.highlight = Some(index);
}
}
pub fn combo_highlight_or(&self, selected: usize) -> usize {
self.combo
.as_ref()
.filter(|open| open.closing.is_none())
.and_then(|open| open.highlight)
.unwrap_or(selected)
}
pub fn combo_opened_on(&self, combo: ComboId) -> Option<usize> {
self.combo_fade(combo)?;
self.combo.as_ref().map(|open| open.opened_on)
}
pub fn combo_fade(&self, combo: ComboId) -> Option<(f32, bool)> {
let open = self.combo.as_ref().filter(|open| open.id == combo)?;
let reveal = self.scaled(COMBO_REVEAL);
let fade = crate::easing::modal_opacity_at(
Some(open.opened_at),
open.closing,
Instant::now(),
reveal,
reveal,
);
(open.closing.is_none() || fade.1).then_some(fade)
}
pub fn combo_pressed_outside(&mut self, combo: ComboId) {
self.close_combo();
self.combo_dismissed = Some((combo, Instant::now()));
}
pub fn take_combo_dismissal(&mut self) -> Option<ComboId> {
let (combo, at) = self.combo_dismissed.take()?;
(at.elapsed() < COMBO_REVEAL).then_some(combo)
}
pub fn set_time_scale(&mut self, scale: f32) {
self.time_scale = (scale.is_finite() && 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 scaled(&self, duration: Duration) -> Duration {
match self.time_scale {
Some(scale) => Duration::try_from_secs_f64(duration.as_secs_f64() * f64::from(scale))
.unwrap_or(Duration::MAX),
None => duration,
}
}
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)
});
let saturation = normalized_saturation(theme.saturation) as f32;
let saturation_held = theme
.saturation_track()
.is_some_and(|track| self.is_dragging(track));
let saturation = f64::from(if saturation_held {
self.snap("vampir-scheme-saturation", saturation)
} else {
self.tween("vampir-scheme-saturation", saturation, MOVE)
});
if darkness <= 0.0 {
theme.palette_at(hue, saturation, false)
} else if darkness >= 1.0 {
theme.palette_at(hue, saturation, true)
} else {
Palette::mix(
theme.palette_at(hue, saturation, false),
theme.palette_at(hue, saturation, true),
darkness,
)
}
}
pub fn open_dialog(&mut self, id: ComboId) {
self.dismiss_popups();
*self.dialog_trap.get_mut() = None;
self.dialog = Some(OpenDialog {
id,
opened_at: Instant::now(),
closing: None,
});
}
pub fn close_dialog(&mut self) {
*self.dialog_trap.get_mut() = None;
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 fade = crate::easing::modal_opacity_at(
Some(dialog.opened_at),
dialog.closing,
Instant::now(),
self.scaled(crate::easing::MODAL_ENTER),
self.scaled(crate::easing::MODAL_EXIT),
);
(dialog.closing.is_none() || fade.1).then_some(fade)
}
pub fn open_palette(
&mut self,
id: ComboId,
query: &Entity<TextInput>,
window: &mut Window,
cx: &mut App,
) {
self.dismiss_popups();
self.restore_menu_focus(window, cx);
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.set_list_highlight(id.into(), 0, 0, false);
let scroll = self.scroll((id, "list"));
scroll.set_offset(Point::default());
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, list: impl Into<Tag>, query: &str) -> usize {
let hash = Tag::new(query).0;
let frame = self.frame.get();
let mut records = self.records.borrow_mut();
let entry = records
.entry(Kind::List.slot(list.into()))
.or_insert(Entry {
touched: frame,
record: Record::List {
highlight: 0,
query: hash,
item: 0,
chosen: false,
},
});
entry.touched = frame;
let Record::List {
highlight,
query,
item,
chosen,
} = &mut entry.record
else {
return 0;
};
if *query != hash {
*query = hash;
*highlight = 0;
*item = 0;
*chosen = false;
}
*highlight
}
pub(crate) fn follow_list(
&self,
list: impl Into<Tag>,
query: &str,
ids: &[SharedString],
) -> (usize, ListChange) {
let hash = Tag::new(query).0;
let tag = |id: &SharedString| Tag::from(id).0;
let frame = self.frame.get();
let mut records = self.records.borrow_mut();
let slot = Kind::List.slot(list.into());
let fresh = !records.contains_key(&slot);
let entry = records.entry(slot).or_insert(Entry {
touched: frame,
record: Record::List {
highlight: 0,
query: hash,
item: 0,
chosen: false,
},
});
entry.touched = frame;
let Record::List {
highlight,
query,
item,
chosen,
} = &mut entry.record
else {
return (0, ListChange::Same);
};
let change = if fresh || *query != hash {
*query = hash;
*highlight = 0;
*chosen = false;
ListChange::Reset
} else if *chosen && *item != 0 && ids.get(*highlight).map(tag) != Some(*item) {
match ids.iter().position(|id| tag(id) == *item) {
Some(index) => {
*highlight = index;
ListChange::Moved
}
None => {
*highlight = 0;
*chosen = false;
ListChange::Reset
}
}
} else {
ListChange::Same
};
*highlight = (*highlight).min(ids.len().saturating_sub(1));
*item = ids.get(*highlight).map_or(0, tag);
(*highlight, change)
}
pub fn list_position(&self, list: impl Into<Tag>) -> usize {
match self.records.borrow().get(&Kind::List.slot(list.into())) {
Some(Entry {
record: Record::List { highlight, .. },
..
}) => *highlight,
_ => 0,
}
}
pub fn highlight_list(&self, list: impl Into<Tag>, index: usize) {
self.set_list_highlight(list.into(), index, 0, true);
}
pub(crate) fn highlight_list_item(
&self,
list: impl Into<Tag>,
index: usize,
id: &SharedString,
) {
self.set_list_highlight(list.into(), index, Tag::from(id).0, true);
}
fn set_list_highlight(&self, list: Tag, index: usize, to: u64, moved: bool) {
let frame = self.frame.get();
let mut records = self.records.borrow_mut();
let entry = records.entry(Kind::List.slot(list)).or_insert(Entry {
touched: frame,
record: Record::List {
highlight: index,
query: Tag::new("").0,
item: to,
chosen: moved,
},
});
entry.touched = frame;
if let Record::List {
highlight,
item,
chosen,
..
} = &mut entry.record
{
*highlight = index;
*item = to;
*chosen = moved;
}
}
pub fn transition(&self, tag: impl Into<Tag>, value: u64, duration: Duration) -> f32 {
let now = self.now();
let frame = self.frame.get();
let mut records = self.records.borrow_mut();
let entry = records.entry(Kind::Flip.slot(tag.into())).or_insert(Entry {
touched: frame,
record: Record::Flip {
value,
since: now,
duration: 0,
},
});
entry.touched = frame;
let Record::Flip {
value: shown,
since,
duration: running,
} = &mut entry.record
else {
return 1.0;
};
if *shown != value {
*shown = value;
*since = now;
*running = micros(self.scaled(duration));
}
progress_of(now, *since, *running)
}
pub fn blend(&self, tag: impl Into<Tag>, on: bool, duration: Duration) -> f32 {
self.tween(tag, if on { 1.0 } else { 0.0 }, duration)
}
pub fn tween(&self, tag: impl Into<Tag>, target: f32, duration: Duration) -> f32 {
self.tween_inner(tag.into(), None, target, duration)
}
pub fn tween_from(
&self,
tag: impl Into<Tag>,
initial: f32,
target: f32,
duration: Duration,
) -> f32 {
self.tween_inner(tag.into(), Some(initial), target, duration)
}
pub fn tween_angle(&self, tag: impl Into<Tag>, degrees: f32, duration: Duration) -> f32 {
let tag = tag.into();
let target = match self.records.borrow().get(&Kind::Tween.slot(tag)) {
Some(Entry {
record: Record::Tween { to, .. },
..
}) => {
let here = *to;
let delta = (degrees - here).rem_euclid(360.0);
here + if delta > 180.0 { delta - 360.0 } else { delta }
}
_ => degrees,
};
self.tween_inner(tag, None, target, duration)
}
pub fn snap(&self, tag: impl Into<Tag>, value: f32) -> f32 {
self.records.borrow_mut().insert(
Kind::Tween.slot(tag.into()),
Entry {
touched: self.frame.get(),
record: Record::Tween {
from: value,
to: value,
since: self.now(),
duration: 0,
},
},
);
value
}
fn tween_inner(&self, tag: Tag, initial: Option<f32>, target: f32, duration: Duration) -> f32 {
let now = self.now();
let frame = self.frame.get();
let duration = micros(self.scaled(duration));
let mut records = self.records.borrow_mut();
let entry = records
.entry(Kind::Tween.slot(tag))
.or_insert_with(|| Entry {
touched: frame,
record: match initial {
Some(from) => Record::Tween {
from,
to: target,
since: now,
duration,
},
None => Record::Tween {
from: target,
to: target,
since: now,
duration: 0,
},
},
});
entry.touched = frame;
let Record::Tween {
from,
to,
since,
duration: running,
} = &mut entry.record
else {
return target;
};
if *to != target {
*from = tween_value(now, *from, *to, *since, *running);
*to = target;
*since = now;
*running = duration;
}
tween_value(now, *from, *to, *since, *running)
}
pub fn present(&self, group: impl Into<Tag>) -> bool {
let frame = self.frame.get();
let mut records = self.records.borrow_mut();
let entry = records
.entry(Kind::Streak.slot(group.into()))
.or_insert(Entry {
touched: frame,
record: Record::Streak { started: frame },
});
let Record::Streak { started } = &mut entry.record else {
return false;
};
if frame.wrapping_sub(entry.touched) > 1 {
*started = frame;
}
entry.touched = frame;
*started != frame
}
pub fn scroll(&self, list: impl Into<Tag>) -> ScrollHandle {
self.scroll_handles
.borrow_mut()
.entry(list.into())
.or_default()
.clone()
}
pub(crate) fn tab_reveal_pending(&self, bar: ComboId, selection: impl Hash) -> bool {
let selection = Tag::new(selection);
let frame = self.frame.get();
let mut records = self.records.borrow_mut();
let entry = records
.entry(Kind::Reveal.slot(Tag::new((bar, "selected-tab"))))
.or_insert(Entry {
touched: frame,
record: Record::Reveal {
selection,
pending: true,
retries: 0,
},
});
entry.touched = frame;
let Record::Reveal {
selection: shown,
pending,
retries,
} = &mut entry.record
else {
return false;
};
if *shown != selection {
*shown = selection;
*pending = true;
*retries = 0;
}
if *pending {
*retries = retries.saturating_add(1);
}
*pending
}
pub(crate) fn finish_tab_reveal(&self, bar: ComboId, selection: impl Hash) {
let selection = Tag::new(selection);
let mut records = self.records.borrow_mut();
if let Some(Entry {
record:
Record::Reveal {
selection: shown,
pending,
..
},
..
}) = records.get_mut(&Kind::Reveal.slot(Tag::new((bar, "selected-tab"))))
&& *shown == selection
{
*pending = false;
}
}
pub fn animating(&self) -> bool {
let frame = self.frame.get();
self.frame.set(frame.wrapping_add(1));
self.color_pads.borrow_mut().retain_recent(frame);
let now = self.now();
let mut running = false;
let mut records = self.records.borrow_mut();
records.retain(|_, entry| {
if frame.wrapping_sub(entry.touched) > 1 {
return false;
}
running |= match entry.record {
Record::Flip {
since, duration, ..
}
| Record::Tween {
since, duration, ..
} => now.saturating_sub(since) < u64::from(duration),
Record::Reveal {
pending, retries, ..
} => pending && retries <= 3,
_ => false,
};
true
});
if records.capacity() > records.len().saturating_mul(4).max(64) {
let target = records.len().saturating_mul(2).max(32);
records.shrink_to(target);
}
drop(records);
if running {
return true;
}
if let Some(open) = &self.combo
&& self.combo_fade(open.id).is_some_and(|(_, running)| running)
{
return true;
}
let reveal = self.scaled(COMBO_REVEAL);
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;
}
self.dialog.as_ref().is_some_and(|dialog| {
self.dialog_fade(dialog.id)
.is_some_and(|(_, running)| running)
})
}
pub(crate) fn color_pad_colors(&self, id: ComboId, hue: f64, rows: usize) -> Rc<[gpui::Rgba]> {
self.color_pads
.borrow_mut()
.colors(id, hue, rows, self.frame.get())
}
pub fn record_bounds(&mut self, tag: impl Into<Tag>, bounds: Bounds<Pixels>) {
self.records.borrow_mut().insert(
Kind::Bounds.slot(tag.into()),
Entry {
touched: self.frame.get(),
record: Record::Bounds(bounds),
},
);
}
pub fn bounds(&self, tag: impl Into<Tag>) -> Option<Bounds<Pixels>> {
match self.records.borrow().get(&Kind::Bounds.slot(tag.into())) {
Some(Entry {
record: Record::Bounds(bounds),
..
}) => Some(*bounds),
_ => None,
}
}
pub fn record_track(&mut self, id: ComboId, bounds: Bounds<Pixels>) {
self.record_bounds((id, "track"), bounds);
}
pub fn track(&self, id: ComboId) -> Option<Bounds<Pixels>> {
self.bounds((id, "track"))
}
pub fn record_group(&mut self, id: ComboId, bounds: Bounds<Pixels>) {
self.record_bounds((id, "group"), bounds);
}
pub fn group(&self, id: ComboId) -> Option<Bounds<Pixels>> {
self.bounds((id, "group"))
}
pub fn record_slot(&mut self, id: ComboId, slot: usize, bounds: Bounds<Pixels>) {
self.record_bounds((id, "slot", slot), bounds);
}
pub fn slot(&self, id: ComboId, slot: usize) -> Option<Bounds<Pixels>> {
self.bounds((id, "slot", slot))
}
pub fn measure(&mut self, tag: impl Into<Tag>, bounds: Bounds<Pixels>) {
self.measured.insert(tag.into(), bounds);
}
pub fn measured(&self, tag: impl Into<Tag>) -> Option<Bounds<Pixels>> {
self.measured.get(&tag.into()).copied()
}
pub fn scroll_dragging(&self) -> bool {
matches!(self.drag, Some(Drag::Scroll(_)))
}
pub fn track_dragging(&self) -> bool {
matches!(self.drag, Some(Drag::Track(_)))
}
pub fn is_dragging(&self, id: ComboId) -> bool {
matches!(&self.drag, Some(Drag::Track(drag)) if drag.id == id)
}
pub fn tab_drag(&self) -> Option<&TabDrag> {
match &self.drag {
Some(Drag::Tab(drag)) => Some(drag),
_ => None,
}
}
fn scroll_drag(&self) -> Option<&ScrollDrag> {
match &self.drag {
Some(Drag::Scroll(drag)) => Some(drag),
_ => None,
}
}
pub fn begin_scroll_drag(&mut self, drag: ScrollDrag) {
self.drag = Some(Drag::Scroll(drag));
}
pub fn begin_track_drag(&mut self, id: ComboId, axis: TrackAxis, stops: Option<u32>) {
self.drag = Some(Drag::Track(TrackDrag { id, axis, stops }));
}
pub fn begin_tab_drag(&mut self, drag: TabDrag) {
self.tab_drag_invalidated.set(false);
self.drag = Some(Drag::Tab(drag));
}
pub(crate) fn note_tab_axis(&self, bar: ComboId, axis: TrackAxis) -> bool {
if matches!(&self.drag, Some(Drag::Tab(drag)) if drag.bar == bar && drag.axis != axis) {
self.tab_drag_invalidated.set(true);
}
!self.tab_drag_invalidated.get()
}
pub fn track_ratio_at(&self, position: Point<Pixels>) -> Option<(ComboId, Point<f32>)> {
let Some(Drag::Track(drag)) = &self.drag else {
return None;
};
let bounds = self.track(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> {
(0..)
.map_while(|slot| self.slot(bar, slot))
.position(|bounds| bounds.contains(&position))
}
pub fn drag_tab_to(&mut self, position: Point<Pixels>) -> bool {
if self.tab_drag_invalidated.get() {
return false;
}
let Some(Drag::Tab(drag)) = &self.drag else {
return false;
};
let axis = drag.axis;
let pointer = match axis {
TrackAxis::Vertical => f32::from(position.y),
_ => f32::from(position.x),
};
if !drag.moved && (pointer - drag.pressed).abs() < TAB_DRAG_THRESHOLD {
return false;
}
let (bar, mut to) = (drag.bar, drag.to);
let backwards = self
.slot(bar, to)
.is_some_and(|current| pointer < tab_start(current, axis));
while let Some(current) = self.slot(bar, to) {
let next = if backwards {
if pointer >= tab_start(current, axis) || to == 0 {
break;
}
to - 1
} else {
if pointer <= tab_end(current, axis) {
break;
}
to + 1
};
let Some(neighbour) = self.slot(bar, next) else {
break;
};
let centre = (tab_start(neighbour, axis) + tab_end(neighbour, axis)) / 2.0;
let past = if backwards {
pointer < centre
} else {
pointer > centre
};
if !past {
break;
}
to = next;
}
if let Some(Drag::Tab(drag)) = &mut self.drag {
drag.pointer = pointer;
drag.moved = true;
drag.to = to;
}
true
}
pub fn dragging_anything(&self) -> bool {
self.drag.is_some()
}
pub fn end_drag(&mut self) -> Option<(ComboId, usize, usize)> {
self.combo_dismissed = None;
let invalidated = self.tab_drag_invalidated.replace(false);
match self.drag.take()? {
Drag::Tab(drag) if !invalidated && drag.moved && drag.from != drag.to => {
Some((drag.bar, drag.from, drag.to))
}
_ => None,
}
}
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,
levels: Vec::new(),
level_changed_at: None,
});
self.menu_scroll(id).set_offset(Point::default());
}
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,
levels: Vec::new(),
level_changed_at: None,
});
self.menu_scroll(id).set_offset(Point::default());
}
pub fn focus(&self, tag: impl Into<Tag>, cx: &App) -> FocusHandle {
self.focus_handles
.borrow_mut()
.entry(tag.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(Tag::from(ROOT_FOCUS))
.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 dialog_button_focus(&self, id: ComboId, index: usize, cx: &App) -> FocusHandle {
self.focus((id, "button", index), cx)
}
pub fn set_dialog_trap(&self, trap: Option<(ComboId, usize)>) {
*self.dialog_trap.borrow_mut() = trap.map(|(id, count)| (id, (0..count).collect()));
}
pub(crate) fn set_dialog_buttons(&self, id: ComboId, indices: Vec<usize>) {
*self.dialog_trap.borrow_mut() = Some((id, indices));
}
pub(crate) fn clear_dialog_trap(&self, id: ComboId) {
let mut trap = self.dialog_trap.borrow_mut();
if trap.as_ref().is_some_and(|(active, _)| *active == id) {
*trap = None;
}
}
pub fn trap_next(&self, window: &Window, backward: bool) -> Option<FocusHandle> {
let trap = self.dialog_trap.borrow();
let (id, indices) = trap.as_ref()?;
if !self.is_dialog_open(id) {
return None;
}
let handles = self.focus_handles.borrow();
if indices.is_empty() {
return handles.get(&Tag::new((*id, "panel"))).cloned();
}
let button = |index: usize| handles.get(&Tag::new((id, "button", index)));
let here = indices
.iter()
.copied()
.find(|&index| button(index).is_some_and(|handle| handle.is_focused(window)));
button(next_dialog_button(indices, here, backward)?).cloned()
}
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 restore_menu_focus(&mut self, window: &mut Window, cx: &mut App) {
let previous = self.menu_return_focus.take();
if self
.menu_focus
.as_ref()
.is_some_and(|focus| focus.is_focused(window))
{
self.return_focus_to(previous, window, cx);
}
}
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(crate) fn enter_menu(
&mut self,
index: usize,
highlight: usize,
identity: u64,
by_keyboard: bool,
) {
let Some(id) = self.menu.as_ref().map(|menu| menu.id) else {
return;
};
let scroll = self.menu_scroll(id).offset();
if let Some(menu) = self.menu.as_mut() {
menu.levels.push(MenuBranch {
index,
highlight,
identity,
scroll,
});
menu.highlight = by_keyboard.then_some(0);
}
self.menu_level_changed(Point::default());
}
pub(crate) fn back_menu(&mut self) -> bool {
let Some(menu) = self.menu.as_mut() else {
return false;
};
let Some(branch) = menu.levels.pop() else {
return false;
};
menu.highlight = Some(branch.highlight);
self.menu_level_changed(branch.scroll);
true
}
pub(crate) fn menu_scroll(&self, id: ComboId) -> ScrollHandle {
self.scroll((id, "menu-scroll"))
}
pub(crate) fn menu_level_changed(&mut self, offset: Point<Pixels>) {
let Some(menu) = self.menu.as_mut() else {
return;
};
menu.level_changed_at = Some(Instant::now());
let id = menu.id;
self.menu_scroll(id).set_offset(offset);
}
pub(crate) fn menu_takes_click(&self, opened_at: Instant) -> bool {
self.menu.as_ref().is_some_and(|menu| {
menu.opened_at == opened_at
&& menu
.level_changed_at
.is_none_or(|changed| changed.elapsed() >= self.scaled(MOVE))
})
}
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
.combo
.as_ref()
.is_some_and(|open| open.closing.is_none())
|| self.menu.is_some();
self.dismiss_popups();
self.restore_menu_focus(window, cx);
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 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();
}),
)
}
pub fn continue_drags<V: ControlHost>(
host: &mut V,
position: Point<Pixels>,
cx: &mut Context<V>,
) -> bool {
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);
return true;
}
if let Some((id, at)) = host.control_state().track_ratio_at(position) {
update_track(host, id, at, cx);
return true;
}
host.control_state_mut().drag_tab_to(position)
}
pub(crate) fn update_track<V: ControlHost>(
host: &mut V,
id: ComboId,
at: Point<f32>,
cx: &mut Context<V>,
) {
if !host.control_state_mut().theme.apply_track(id, at.x) {
host.track_dragged(id, at, cx);
}
}
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, Entry, ListChange, Palette, SCHEME_FADE, TabDrag, Tag, TrackAxis};
use gpui::{Bounds, ElementId, Point, SharedString, px, size};
fn at(x: f32, y: f32) -> Point<gpui::Pixels> {
gpui::point(px(x), px(y))
}
fn rect(x: f32, y: f32, w: f32, h: f32) -> Bounds<gpui::Pixels> {
Bounds::new(at(x, y), size(px(w), px(h)))
}
#[test]
fn a_record_is_small() {
assert_eq!(std::mem::size_of::<Tag>(), 8);
assert!(
std::mem::size_of::<Entry>() <= 40,
"{}",
std::mem::size_of::<Entry>()
);
}
#[test]
fn tags_are_hashes_of_their_parts() {
assert_eq!(Tag::new(("tabs", "pill-x")), Tag::from(("tabs", "pill-x")));
assert_ne!(Tag::new(("tabs", "pill-x")), Tag::new(("pill-x", "tabs")));
assert_ne!(Tag::new(("ab", "c")), Tag::new(("a", "bc")));
assert_ne!(
Tag::new(("rows", "shown", 1usize)),
Tag::new(("rows", "shown", 2usize))
);
let owned: SharedString = String::from("budget.csv").into();
assert_eq!(
Tag::new(("tree", "selected", &owned)),
Tag::new(("tree", "selected", "budget.csv"))
);
assert_eq!(Tag::from(&owned), Tag::from("budget.csv"));
assert_eq!(
Tag::from(ElementId::Name("x".into())),
Tag::from(&ElementId::Name("x".into()))
);
assert_ne!(Tag::new("a").with("b"), Tag::new(Tag::new("a")));
}
#[test]
fn kinds_do_not_clobber_each_other() {
let mut state = ControlState::new();
state.present("list");
state.highlight_list("list", 3);
state.record_bounds("list", rect(1.0, 2.0, 3.0, 4.0));
state.tween("list", 5.0, super::MOVE);
state.transition("list", 7, super::SWITCH_SLIDE);
assert_eq!(state.list_position("list"), 3);
assert_eq!(state.bounds("list"), Some(rect(1.0, 2.0, 3.0, 4.0)));
assert_eq!(state.tween("list", 5.0, super::MOVE), 5.0);
assert_eq!(state.transition("list", 7, super::SWITCH_SLIDE), 1.0);
}
#[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 submenu_navigation_keeps_the_opening_and_restores_its_parent_row() {
let mut state = ControlState::new();
state.open_menu("row", at(10.0, 20.0), "budget.csv");
let opening = state.menu_opened_at();
state.enter_menu(3, 1, 11, false);
state.highlight_menu(Some(2));
state.enter_menu(4, 2, 22, false);
assert_eq!(state.menu_target(), Some("budget.csv"));
assert_eq!(state.menu_opened_at(), opening);
assert_eq!(state.menu_highlight(), None);
assert!(state.back_menu());
assert_eq!(state.menu_highlight(), Some(2));
assert!(state.back_menu());
assert_eq!(state.menu_highlight(), Some(1));
assert!(!state.back_menu());
assert_eq!(state.menu_target(), Some("budget.csv"));
}
#[test]
fn a_level_entered_by_keyboard_starts_on_its_first_row() {
let mut state = ControlState::new();
state.open_menu("row", at(10.0, 20.0), "budget.csv");
state.enter_menu(3, 1, 11, true);
assert_eq!(state.menu_highlight(), Some(0));
assert!(state.back_menu());
state.enter_menu(3, 1, 11, false);
assert_eq!(state.menu_highlight(), None);
}
#[test]
fn back_restores_the_parent_scroll_and_a_new_level_starts_at_the_top() {
let mut state = ControlState::new();
state.open_menu("row", at(10.0, 20.0), "budget.csv");
let scroll = state.menu_scroll("row");
scroll.set_offset(at(0.0, -120.0));
state.enter_menu(9, 4, 11, false);
assert_eq!(scroll.offset(), Point::default());
assert!(state.back_menu());
assert_eq!(scroll.offset(), at(0.0, -120.0));
assert_eq!(state.menu_highlight(), Some(4));
assert!(!state.back_menu());
assert!(state.is_menu_open("row"));
state.open_menu("row", at(10.0, 20.0), "notes.md");
assert_eq!(scroll.offset(), Point::default());
}
#[test]
fn rows_take_no_clicks_until_their_level_has_arrived() {
let mut state = ControlState::new();
state.open_menu("row", at(10.0, 20.0), "budget.csv");
let opening = state.menu_opened_at().expect("open");
assert!(state.menu_takes_click(opening));
state.enter_menu(3, 1, 11, false);
assert!(!state.menu_takes_click(opening));
state.set_time_scale(0.001);
std::thread::sleep(std::time::Duration::from_millis(2));
assert!(state.menu_takes_click(opening));
state.open_menu("row", at(10.0, 20.0), "notes.md");
assert!(!state.menu_takes_click(opening));
}
#[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 reversing_a_blend_starts_from_its_visible_value() {
let mut state = ControlState::new();
let duration = std::time::Duration::from_secs(1000);
assert_eq!(state.blend("switch", false, duration), 0.0);
assert_eq!(state.blend("switch", true, duration), 0.0);
state.epoch -= std::time::Duration::from_secs(300);
let before = state.blend("switch", true, duration);
assert!((0.6..0.7).contains(&before), "{before}");
let reversing = state.blend("switch", false, duration);
assert!(
(reversing - before).abs() < 0.001,
"{before} -> {reversing}"
);
state.epoch -= std::time::Duration::from_secs(300);
let returning = state.blend("switch", false, duration);
assert!(returning < reversing, "{returning} < {reversing}");
let reversed_again = state.blend("switch", true, duration);
assert!((reversed_again - returning).abs() < 0.001);
}
#[test]
fn dialog_navigation_skips_disabled_buttons_and_wraps() {
let enabled = [0, 3, 5];
assert_eq!(super::next_dialog_button(&enabled, Some(0), false), Some(3));
assert_eq!(super::next_dialog_button(&enabled, Some(5), false), Some(0));
assert_eq!(super::next_dialog_button(&enabled, Some(0), true), Some(5));
assert_eq!(super::next_dialog_button(&enabled, Some(3), true), Some(0));
assert_eq!(super::next_dialog_button(&enabled, Some(2), false), Some(0));
assert_eq!(super::next_dialog_button(&enabled, None, true), Some(5));
assert_eq!(super::next_dialog_button(&[], None, false), None);
}
#[test]
fn an_inactive_dialog_cannot_clear_the_active_dialogs_trap() {
let mut state = ControlState::new();
state.open_dialog("active");
state.set_dialog_buttons("active", vec![1, 3]);
state.clear_dialog_trap("inactive");
assert_eq!(*state.dialog_trap.borrow(), Some(("active", vec![1, 3])));
state.close_dialog();
assert_eq!(*state.dialog_trap.borrow(), None);
state.set_dialog_trap(Some(("active", 4)));
state.open_dialog("replacement");
assert_eq!(*state.dialog_trap.borrow(), None);
}
#[test]
fn invalid_or_extreme_time_scales_cannot_panic() {
let mut state = ControlState::new();
for scale in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, 0.0, -1.0] {
state.set_time_scale(scale);
assert_eq!(state.time_scale(), None);
assert_eq!(state.scaled(super::MOVE), super::MOVE);
}
state.set_time_scale(f32::MAX);
assert_eq!(state.scaled(super::MOVE), std::time::Duration::MAX);
assert_eq!(
state.scaled(std::time::Duration::ZERO),
std::time::Duration::ZERO
);
}
#[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!(super::progress_of(0, 0, 0), 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();
state.transition("check", 1, super::SWITCH_SLIDE);
state.transition("check", 0, super::SWITCH_SLIDE);
assert!(state.animating(), "a change started a slide");
assert_eq!(state.records.borrow().len(), 1);
state.animating();
state.animating();
assert_eq!(
state.records.borrow().len(),
0,
"two frames unseen, and it is gone"
);
let t = state.transition("check", 1, super::SWITCH_SLIDE);
assert_eq!(t, 1.0);
}
#[test]
fn retired_records_release_excess_capacity() {
let state = ControlState::new();
for slot in 0..1024 {
state.snap(("rows", slot), 1.0);
}
assert!(state.records.borrow().capacity() >= 1024);
for _ in 0..3 {
state.snap(("rows", 0), 1.0);
state.animating();
}
assert_eq!(state.records.borrow().len(), 1);
assert!(state.records.borrow().capacity() <= 64);
}
#[test]
fn geometry_is_retired_but_measurements_are_kept() {
let mut state = ControlState::new();
state.record_slot("tabs", 0, rect(0.0, 0.0, 80.0, 26.0));
state.record_bounds(("tabs", "tab", "notes.md"), rect(0.0, 0.0, 80.0, 26.0));
state.measure(("section", "body"), rect(0.0, 0.0, 300.0, 120.0));
assert_eq!(
state.slot("tabs", 0).map(|b| f32::from(b.size.width)),
Some(80.0)
);
assert_eq!(state.tab_at("tabs", at(10.0, 10.0)), Some(0));
state.animating();
state.animating();
state.animating();
assert_eq!(state.slot("tabs", 0), None);
assert_eq!(state.bounds(("tabs", "tab", "notes.md")), None);
assert_eq!(state.tab_at("tabs", at(10.0, 10.0)), None);
assert_eq!(
state
.measured(("section", "body"))
.map(|b| f32::from(b.size.height)),
Some(120.0),
"a disclosure grows to the height it had, however long it was shut"
);
}
#[test]
fn time_scale_stretches_every_duration() {
let mut state = ControlState::new();
state.set_time_scale(1_000_000.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}");
state.transition("flip", 0, std::time::Duration::from_millis(1));
state.transition("flip", 1, std::time::Duration::from_millis(1));
std::thread::sleep(std::time::Duration::from_millis(10));
let t = state.transition("flip", 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_combo_fades_out_on_the_row_it_opened_on() {
let mut state = ControlState::new();
assert_eq!(state.combo_fade("sort"), None);
state.open_combo("sort", 2);
assert!(state.is_combo_open("sort"));
assert_eq!(
state.combo_highlight_or(0),
2,
"the keyboard starts on the current option"
);
let (reveal, running) = state.combo_fade("sort").expect("on screen");
assert!(running && reveal < 1.0, "{reveal}");
assert!(state.animating());
state.highlight_combo(4);
assert_eq!(state.combo_highlight_or(0), 4);
state.close_combo();
assert!(!state.is_combo_open("sort"));
assert_eq!(
state.combo_opened_on("sort"),
Some(2),
"kept through the fade"
);
assert_eq!(
state.combo_highlight_or(0),
0,
"the highlight went with the list"
);
assert!(state.combo_fade("sort").is_some(), "still fading");
std::thread::sleep(super::COMBO_REVEAL + std::time::Duration::from_millis(20));
assert_eq!(state.combo_fade("sort"), None);
assert_eq!(state.combo_opened_on("sort"), None);
assert!(!state.animating());
}
#[test]
fn a_dismissal_is_taken_once() {
let mut state = ControlState::new();
state.open_combo("sort", 0);
state.combo_pressed_outside("sort");
assert!(!state.is_combo_open("sort"));
assert_eq!(state.take_combo_dismissal(), Some("sort"));
assert_eq!(state.take_combo_dismissal(), None, "taken");
state.combo_pressed_outside("sort");
state.end_drag();
assert_eq!(state.take_combo_dismissal(), None, "a release clears it");
}
#[test]
fn one_gesture_at_a_time() {
let mut state = ControlState::new();
state.begin_track_drag("volume", TrackAxis::Horizontal, None);
assert!(state.is_dragging("volume") && state.track_dragging());
state.begin_tab_drag(TabDrag {
bar: "tabs",
axis: TrackAxis::Horizontal,
from: 0,
to: 0,
moved: false,
grab: 0.0,
pressed: 0.0,
pointer: 0.0,
});
assert!(!state.track_dragging(), "the tab took over");
assert!(state.dragging_anything());
assert_eq!(
state.end_drag(),
None,
"a press that never moved is a click"
);
assert!(!state.dragging_anything());
state.record_slot("tabs", 0, rect(0.0, 0.0, 80.0, 26.0));
state.record_slot("tabs", 1, rect(82.0, 0.0, 80.0, 26.0));
state.begin_tab_drag(TabDrag {
bar: "tabs",
axis: TrackAxis::Horizontal,
from: 0,
to: 0,
moved: false,
grab: 10.0,
pressed: 10.0,
pointer: 10.0,
});
assert!(
!state.drag_tab_to(at(11.0, 10.0)),
"a one-pixel wobble is still a click"
);
assert_eq!(state.tab_drag().map(|drag| drag.moved), Some(false));
assert!(
state.drag_tab_to(at(40.0, 10.0)),
"every move during a drag redraws"
);
assert_eq!(
state.tab_drag().map(|drag| drag.to),
Some(0),
"not past the neighbour's middle"
);
state.drag_tab_to(at(130.0, 10.0));
assert_eq!(state.tab_drag().map(|drag| drag.to), Some(1));
assert_eq!(state.end_drag(), Some(("tabs", 0, 1)));
}
#[test]
fn a_fling_lands_where_the_pointer_stops() {
let mut state = ControlState::new();
for slot in 0..4 {
let left = slot as f32 * 82.0;
state.record_slot("tabs", slot, rect(left, 0.0, 80.0, 26.0));
}
state.begin_tab_drag(TabDrag {
bar: "tabs",
axis: TrackAxis::Horizontal,
from: 0,
to: 0,
moved: false,
grab: 10.0,
pressed: 10.0,
pointer: 10.0,
});
state.drag_tab_to(at(300.0, 10.0));
assert_eq!(state.tab_drag().map(|drag| drag.to), Some(3));
state.drag_tab_to(at(120.0, 10.0));
assert_eq!(state.tab_drag().map(|drag| drag.to), Some(1));
state.drag_tab_to(at(50.0, 10.0));
assert_eq!(state.tab_drag().map(|drag| drag.to), Some(1));
assert_eq!(state.end_drag(), Some(("tabs", 0, 1)));
}
#[test]
fn a_vertical_tab_drag_uses_y_and_crosses_row_midpoints() {
let mut state = ControlState::new();
for slot in 0..3 {
state.record_slot("sidebar", slot, rect(20.0, slot as f32 * 30.0, 160.0, 28.0));
}
state.begin_tab_drag(TabDrag {
bar: "sidebar",
axis: TrackAxis::Vertical,
from: 0,
to: 0,
moved: false,
grab: 10.0,
pressed: 10.0,
pointer: 10.0,
});
assert!(
!state.drag_tab_to(at(140.0, 11.0)),
"x motion does not drag a vertical tab"
);
state.drag_tab_to(at(140.0, 80.0));
assert_eq!(state.tab_drag().map(|drag| drag.to), Some(2));
state.drag_tab_to(at(140.0, 34.0));
assert_eq!(state.tab_drag().map(|drag| drag.to), Some(1));
assert_eq!(state.end_drag(), Some(("sidebar", 0, 1)));
}
#[test]
fn changing_a_tab_bars_axis_cancels_its_pending_reorder() {
let mut state = ControlState::new();
state.begin_tab_drag(TabDrag {
bar: "tabs",
axis: TrackAxis::Horizontal,
from: 0,
to: 1,
moved: true,
grab: 10.0,
pressed: 10.0,
pointer: 90.0,
});
assert!(state.note_tab_axis("other", TrackAxis::Vertical));
assert!(state.note_tab_axis("tabs", TrackAxis::Horizontal));
assert!(state.tab_drag().is_some());
assert!(!state.note_tab_axis("tabs", TrackAxis::Vertical));
assert!(!state.note_tab_axis("tabs", TrackAxis::Horizontal));
assert!(!state.drag_tab_to(at(200.0, 20.0)));
assert_eq!(state.end_drag(), None);
assert!(!state.dragging_anything());
}
#[test]
fn selected_tab_reveal_waits_for_bounds_then_leaves_manual_scroll_alone() {
let state = ControlState::new();
assert!(state.tab_reveal_pending("tabs", ("first", false)));
assert!(state.animating(), "pending bounds request another frame");
assert!(state.tab_reveal_pending("tabs", ("first", false)));
state.finish_tab_reveal("tabs", ("first", false));
assert!(!state.tab_reveal_pending("tabs", ("first", false)));
assert!(
!state.animating(),
"completed reveal stops asking for frames"
);
assert!(!state.tab_reveal_pending("tabs", ("first", false)));
assert!(state.tab_reveal_pending("tabs", ("second", false)));
state.finish_tab_reveal("tabs", ("first", false));
assert!(state.tab_reveal_pending("tabs", ("second", false)));
state.finish_tab_reveal("tabs", ("second", false));
assert!(state.tab_reveal_pending("tabs", ("second", true)));
}
#[test]
fn an_unpainted_tab_does_not_request_frames_forever() {
let state = ControlState::new();
for _ in 0..3 {
assert!(state.tab_reveal_pending("tabs", ("hidden", false)));
assert!(state.animating());
}
assert!(state.tab_reveal_pending("tabs", ("hidden", false)));
assert!(!state.animating());
assert!(state.tab_reveal_pending("tabs", ("hidden", false)));
}
#[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);
}
fn ids(names: &[&'static str]) -> Vec<SharedString> {
names.iter().map(|name| SharedString::from(*name)).collect()
}
#[test]
fn the_highlight_stays_on_its_result_as_sources_arrive() {
let state = ControlState::new();
let first = ids(&["tab", "bookmark", "file", "action"]);
assert_eq!(
state.follow_list("results", "des", &first).1,
ListChange::Reset
);
state.highlight_list_item("results", 3, &first[3]);
let appended = ids(&["tab", "bookmark", "file", "action", "remote"]);
assert_eq!(
state.follow_list("results", "des", &appended),
(3, ListChange::Same)
);
let ranked_above = ids(&["tab", "history", "bookmark", "file", "action", "remote"]);
assert_eq!(
state.follow_list("results", "des", &ranked_above),
(4, ListChange::Moved)
);
assert_eq!(
state.follow_list("results", "des", &ranked_above),
(4, ListChange::Same)
);
let gone = ids(&["tab", "history"]);
assert_eq!(
state.follow_list("results", "des", &gone),
(0, ListChange::Reset)
);
}
#[test]
fn an_untouched_highlight_stays_on_the_first_row_as_results_arrive() {
let state = ControlState::new();
let first = ids(&["review", "system"]);
state.follow_list("results", "design", &first);
let better = ids(&["notes", "review", "system"]);
assert_eq!(
state.follow_list("results", "design", &better),
(0, ListChange::Same)
);
}
#[test]
fn a_new_query_puts_a_followed_list_back_on_its_first_row() {
let state = ControlState::new();
let results = ids(&["tab", "bookmark", "file"]);
state.follow_list("results", "de", &results);
state.highlight_list_item("results", 2, &results[2]);
assert_eq!(
state.follow_list("results", "des", &results),
(0, ListChange::Reset)
);
let better = ids(&["notes", "tab", "bookmark", "file"]);
assert_eq!(
state.follow_list("results", "des", &better),
(0, ListChange::Same)
);
}
#[test]
fn a_row_set_by_the_host_is_followed_once_drawn() {
let state = ControlState::new();
let results = ids(&["tab", "bookmark", "file"]);
state.follow_list("results", "", &results);
state.highlight_list("results", 1);
assert_eq!(
state.follow_list("results", "", &results),
(1, ListChange::Same)
);
let reordered = ids(&["bookmark", "tab", "file"]);
assert_eq!(
state.follow_list("results", "", &reordered),
(0, ListChange::Moved)
);
}
#[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;
assert_eq!(state.palette(), light);
assert!(state.animating(), "the scheme is crossing over");
std::thread::sleep(std::time::Duration::from_millis(20));
let crossing = state.palette();
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());
}
}