use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::hash::{BuildHasherDefault, DefaultHasher, Hash, Hasher};
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;
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))
}
}
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,
}
impl Kind {
fn slot(self, tag: Tag) -> Tag {
const SALT: [u64; 5] = [
0x9E37_79B9_7F4A_7C15,
0xD1B5_4A32_D192_ED03,
0x8CB9_2BA7_2F3D_8DD7,
0x5851_F42D_4C95_7F2D,
0x2545_F491_4F6C_DD1D,
];
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 },
Bounds(Bounds<Pixels>),
}
#[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)
}
#[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 from: usize,
pub to: usize,
pub moved: bool,
pub grab: f32,
pub pressed: f32,
pub pointer: f32,
}
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>,
}
#[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>>,
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: Cell<Option<(ComboId, usize)>>,
pub palette_overlay: Option<OpenPalette>,
pub recording: Option<ComboId>,
pub ring_hidden: bool,
drag: Option<Drag>,
}
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(),
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: Cell::new(None),
palette_overlay: None,
recording: None,
ring_hidden: false,
drag: None,
}
}
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);
match open.closing {
Some(since) => {
let t = crate::easing::progress(since, reveal);
(t < 1.0).then(|| (1.0 - crate::easing::ease_in_cubic(t), true))
}
None => {
let t = crate::easing::progress(open.opened_at, reveal);
Some((crate::easing::ease_out_cubic(t), t < 1.0))
}
}
}
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 > 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.mul_f32(scale),
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)
});
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)?;
match dialog.closing {
Some(since) => {
let t = crate::easing::progress(since, self.scaled(crate::easing::MODAL_EXIT));
(t < 1.0).then(|| (1.0 - crate::easing::ease_in_cubic(t), true))
}
None => {
let t = crate::easing::progress(
dialog.opened_at,
self.scaled(crate::easing::MODAL_ENTER),
);
Some((crate::easing::ease_out_cubic(t), t < 1.0))
}
}
}
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, 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,
},
});
entry.touched = frame;
let Record::List { highlight, query } = &mut entry.record else {
return 0;
};
if *query != hash {
*query = hash;
*highlight = 0;
}
*highlight
}
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) {
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: index,
query: Tag::new("").0,
},
});
entry.touched = frame;
if let Record::List { highlight, .. } = &mut entry.record {
*highlight = index;
}
}
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 {
let t = crate::easing::ease_out_cubic(self.transition(tag, u64::from(on), duration));
if on { t } else { 1.0 - t }
}
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 fn animating(&self) -> bool {
let frame = self.frame.get();
self.frame.set(frame.wrapping_add(1));
let now = self.now();
let mut running = false;
self.records.borrow_mut().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),
_ => false,
};
true
});
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 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.drag = Some(Drag::Tab(drag));
}
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 {
let pointer = f32::from(position.x);
let Some(Drag::Tab(drag)) = &self.drag else {
return false;
};
if !drag.moved && (pointer - drag.pressed).abs() < TAB_DRAG_THRESHOLD {
return false;
}
let (bar, mut to) = (drag.bar, drag.to);
let leftwards = self
.slot(bar, to)
.is_some_and(|current| pointer < f32::from(current.left()));
while let Some(current) = self.slot(bar, to) {
let next = if leftwards {
if pointer >= f32::from(current.left()) || to == 0 {
break;
}
to - 1
} else {
if pointer <= f32::from(current.right()) {
break;
}
to + 1
};
let Some(neighbour) = self.slot(bar, next) else {
break;
};
let centre = f32::from(neighbour.center().x);
let past = if leftwards {
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;
match self.drag.take()? {
Drag::Tab(drag) if 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,
});
}
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, 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.set(trap);
}
pub fn trap_next(&self, window: &Window, backward: bool) -> Option<FocusHandle> {
let (id, count) = self.dialog_trap.get()?;
if count == 0 {
return None;
}
let handles = self.focus_handles.borrow();
let button = |index: usize| handles.get(&Tag::new((id, "button", index)));
let here = (0..count)
.position(|index| button(index).is_some_and(|handle| handle.is_focused(window)))?;
let next = if backward {
(here + count - 1) % count
} else {
(here + 1) % count
};
button(next).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 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
.combo
.as_ref()
.is_some_and(|open| open.closing.is_none())
|| 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 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) {
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);
}
return true;
}
host.control_state_mut().drag_tab_to(position)
}
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, 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 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!(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 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",
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",
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",
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_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;
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());
}
}