#![allow(unexpected_cfgs)]
#[cfg(all(test, not(test_standalone)))]
use crate::widgets::abstractable_widget_types;
#[cfg(not(test_standalone))]
use crate::widgets::{CanvasRect, Color, WidgetId, WidgetKind, WidgetSpec};
#[cfg(test_standalone)]
pub use standalone_stubs::*;
#[cfg(test_standalone)]
mod standalone_stubs {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Color {
pub r: u8,
pub g: u8,
pub b: u8,
}
impl Color {
pub const fn rgb(r: u8, g: u8, b: u8) -> Self {
Self { r, g, b }
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct CanvasRect {
pub x: i32,
pub y: i32,
pub width: i32,
pub height: i32,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct WidgetId(pub u64);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum WidgetKind {
Window,
Container,
Label,
Button,
RadioButton,
#[cfg(feature = "widgets-range")]
Slider,
#[cfg(feature = "widgets-range")]
SpinBox,
#[cfg(feature = "widgets-containers")]
Separator,
#[cfg(feature = "widgets-containers")]
GroupBox,
#[cfg(feature = "widgets-containers")]
Tabs,
#[cfg(feature = "widgets-media")]
Image,
#[cfg(feature = "widgets-pickers")]
DatePicker,
#[cfg(feature = "widgets-text")]
LinkLabel,
#[cfg(feature = "widgets-data")]
ListView,
#[cfg(feature = "widgets-data")]
TreeView,
#[cfg(feature = "widgets-containers")]
SplitPane,
#[cfg(feature = "widgets-pickers")]
FileChooserDialog,
#[cfg(feature = "widgets-containers")]
AlertDialog,
#[cfg(feature = "widgets-text")]
TextInput,
#[cfg(feature = "widgets-text")]
TextArea,
#[cfg(feature = "widgets-canvas")]
VulkanCanvas,
Checkbox,
ComboBox,
#[cfg(feature = "widgets-range")]
ProgressBar,
#[cfg(feature = "widgets-data")]
DataList,
#[cfg(feature = "widgets-data")]
DataGrid,
#[cfg(feature = "widgets-canvas")]
Canvas,
#[cfg(feature = "widgets-pickers")]
ColorDialog,
#[cfg(feature = "widgets-pickers")]
FontDialog,
Toolbar,
#[cfg(feature = "widgets-pickers")]
Calendar,
}
pub fn abstractable_widget_types() -> &'static [WidgetKind] {
&[
WidgetKind::Window,
WidgetKind::Container,
WidgetKind::Label,
WidgetKind::Button,
#[cfg(feature = "widgets-choice")]
WidgetKind::RadioButton,
#[cfg(feature = "widgets-range")]
WidgetKind::Slider,
#[cfg(feature = "widgets-range")]
WidgetKind::SpinBox,
#[cfg(feature = "widgets-containers")]
WidgetKind::Separator,
#[cfg(feature = "widgets-containers")]
WidgetKind::GroupBox,
#[cfg(feature = "widgets-containers")]
WidgetKind::Tabs,
#[cfg(feature = "widgets-media")]
WidgetKind::Image,
#[cfg(feature = "widgets-pickers")]
WidgetKind::DatePicker,
#[cfg(feature = "widgets-text")]
WidgetKind::LinkLabel,
#[cfg(feature = "widgets-data")]
WidgetKind::ListView,
#[cfg(feature = "widgets-data")]
WidgetKind::TreeView,
#[cfg(feature = "widgets-containers")]
WidgetKind::SplitPane,
#[cfg(feature = "widgets-pickers")]
WidgetKind::FileChooserDialog,
#[cfg(feature = "widgets-containers")]
WidgetKind::AlertDialog,
#[cfg(feature = "widgets-text")]
WidgetKind::TextInput,
#[cfg(feature = "widgets-text")]
WidgetKind::TextArea,
#[cfg(feature = "widgets-canvas")]
WidgetKind::VulkanCanvas,
#[cfg(feature = "widgets-choice")]
WidgetKind::Checkbox,
#[cfg(feature = "widgets-choice")]
WidgetKind::ComboBox,
#[cfg(feature = "widgets-range")]
WidgetKind::ProgressBar,
#[cfg(feature = "widgets-data")]
WidgetKind::DataList,
#[cfg(feature = "widgets-data")]
WidgetKind::DataGrid,
#[cfg(feature = "widgets-canvas")]
WidgetKind::Canvas,
#[cfg(feature = "widgets-pickers")]
WidgetKind::ColorDialog,
#[cfg(feature = "widgets-pickers")]
WidgetKind::FontDialog,
WidgetKind::Toolbar,
]
}
pub struct WidgetSpec {
pub id: WidgetId,
pub kind: WidgetKind,
pub focusable: Option<bool>,
pub enabled: bool,
pub visible: bool,
}
impl WidgetSpec {
pub fn new(id: WidgetId, kind: WidgetKind) -> Self {
Self {
id,
kind,
focusable: None,
enabled: true,
visible: true,
}
}
}
}
pub fn default_focusable(kind: WidgetKind) -> bool {
match kind {
WidgetKind::Window | WidgetKind::Container | WidgetKind::Label | WidgetKind::Toolbar => {
false
}
#[cfg(feature = "widgets-containers")]
WidgetKind::Separator | WidgetKind::GroupBox | WidgetKind::SplitPane => false,
#[cfg(feature = "widgets-range")]
WidgetKind::ProgressBar => false,
#[cfg(feature = "widgets-canvas")]
WidgetKind::VulkanCanvas | WidgetKind::MetalCanvas => false,
#[cfg(feature = "widgets-media")]
WidgetKind::Image => false,
WidgetKind::Button => true,
#[cfg(feature = "widgets-text")]
WidgetKind::TextInput
| WidgetKind::TextArea
| WidgetKind::LinkLabel
| WidgetKind::RichText => true,
#[cfg(feature = "widgets-pickers")]
WidgetKind::DatePicker
| WidgetKind::FileChooserDialog
| WidgetKind::ColorDialog
| WidgetKind::FontDialog
| WidgetKind::Calendar => true,
#[cfg(feature = "widgets-containers")]
WidgetKind::Tabs | WidgetKind::AlertDialog => true,
#[cfg(feature = "widgets-data")]
WidgetKind::ListView
| WidgetKind::TreeView
| WidgetKind::DataList
| WidgetKind::DataGrid => true,
#[cfg(feature = "widgets-choice")]
WidgetKind::Checkbox
| WidgetKind::RadioButton
| WidgetKind::ComboBox
| WidgetKind::MultiSelect => true,
#[cfg(feature = "widgets-range")]
WidgetKind::Slider | WidgetKind::SpinBox => true,
#[cfg(feature = "widgets-canvas")]
WidgetKind::Canvas => true,
}
}
pub fn is_focusable(spec: &WidgetSpec) -> bool {
spec.focusable
.unwrap_or_else(|| default_focusable(spec.kind))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum FocusDirection {
Up,
Down,
Left,
Right,
TabNext,
TabPrev,
}
impl FocusDirection {
pub const fn is_directional(&self) -> bool {
matches!(
self,
FocusDirection::Up
| FocusDirection::Down
| FocusDirection::Left
| FocusDirection::Right
)
}
pub const fn is_tab(&self) -> bool {
matches!(self, FocusDirection::TabNext | FocusDirection::TabPrev)
}
pub const fn opposite(&self) -> Self {
match self {
FocusDirection::Up => FocusDirection::Down,
FocusDirection::Down => FocusDirection::Up,
FocusDirection::Left => FocusDirection::Right,
FocusDirection::Right => FocusDirection::Left,
FocusDirection::TabNext => FocusDirection::TabPrev,
FocusDirection::TabPrev => FocusDirection::TabNext,
}
}
pub const fn unit_vector(&self) -> Option<(i32, i32)> {
match self {
FocusDirection::Up => Some((0, -1)),
FocusDirection::Down => Some((0, 1)),
FocusDirection::Left => Some((-1, 0)),
FocusDirection::Right => Some((1, 0)),
FocusDirection::TabNext | FocusDirection::TabPrev => None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)]
pub struct FocusRect {
pub x: i32,
pub y: i32,
pub width: i32,
pub height: i32,
}
impl FocusRect {
pub const fn new(x: i32, y: i32, width: i32, height: i32) -> Self {
Self {
x,
y,
width,
height,
}
}
pub const fn from_canvas_rect(rect: CanvasRect) -> Self {
Self {
x: rect.x,
y: rect.y,
width: rect.width,
height: rect.height,
}
}
pub const fn to_canvas_rect(&self) -> CanvasRect {
CanvasRect {
x: self.x,
y: self.y,
width: self.width,
height: self.height,
}
}
pub const fn left(&self) -> i32 {
self.x
}
pub const fn top(&self) -> i32 {
self.y
}
pub const fn right(&self) -> i32 {
self.x + self.width
}
pub const fn bottom(&self) -> i32 {
self.y + self.height
}
pub fn center_x(&self) -> f64 {
self.x as f64 + (self.width as f64 / 2.0)
}
pub fn center_y(&self) -> f64 {
self.y as f64 + (self.height as f64 / 2.0)
}
pub fn center(&self) -> (f64, f64) {
(self.center_x(), self.center_y())
}
pub const fn is_empty(&self) -> bool {
self.width <= 0 || self.height <= 0
}
pub const fn contains_point(&self, px: i32, py: i32) -> bool {
px >= self.x && px < self.x + self.width && py >= self.y && py < self.y + self.height
}
pub const fn intersects(&self, other: &Self) -> bool {
self.x < other.x + other.width
&& self.x + self.width > other.x
&& self.y < other.y + other.height
&& self.y + self.height > other.y
}
pub fn aspect_ratio(&self) -> f64 {
if self.height > 0 {
self.width as f64 / self.height as f64
} else {
1.0
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FocusCandidate<T = WidgetId> {
pub id: T,
pub rect: FocusRect,
pub focusable: bool,
pub tab_index: Option<i32>,
}
impl<T> FocusCandidate<T> {
pub fn new(id: T, rect: FocusRect) -> Self {
Self {
id,
rect,
focusable: true,
tab_index: None,
}
}
pub fn with_focusable(mut self, focusable: bool) -> Self {
self.focusable = focusable;
self
}
pub fn with_tab_index(mut self, tab_index: i32) -> Self {
self.tab_index = Some(tab_index);
self
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct FocusProjectionScore {
pub in_beam: bool,
pub primary_distance: f64,
pub orthogonal_distance: f64,
pub overlap: f64,
pub weighted_score: f64,
}
impl FocusProjectionScore {
pub fn is_better_than(&self, other: &Self) -> bool {
if self.in_beam != other.in_beam {
return self.in_beam;
}
self.weighted_score < other.weighted_score
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ProjectionOptions {
pub primary_weight: f64,
pub orthogonal_weight_in_beam: f64,
pub orthogonal_weight_off_beam: f64,
pub overlap_weight: f64,
pub off_beam_penalty: f64,
pub aspect_ratio_weight: f64,
}
impl Default for ProjectionOptions {
fn default() -> Self {
Self {
primary_weight: 13.0,
orthogonal_weight_in_beam: 1.0,
orthogonal_weight_off_beam: 5.0,
overlap_weight: 0.1,
off_beam_penalty: 1000.0,
aspect_ratio_weight: 0.0,
}
}
}
impl ProjectionOptions {
pub const fn standard() -> Self {
Self {
primary_weight: 13.0,
orthogonal_weight_in_beam: 1.0,
orthogonal_weight_off_beam: 5.0,
overlap_weight: 0.1,
off_beam_penalty: 1000.0,
aspect_ratio_weight: 0.0,
}
}
pub const fn with_aspect_ratio_weighting(weight: f64) -> Self {
Self {
primary_weight: 13.0,
orthogonal_weight_in_beam: 1.0,
orthogonal_weight_off_beam: 5.0,
overlap_weight: 0.1,
off_beam_penalty: 1000.0,
aspect_ratio_weight: weight,
}
}
pub fn with_aspect_ratio_weight(mut self, weight: f64) -> Self {
self.aspect_ratio_weight = weight;
self
}
}
pub fn compute_projection_score_options(
source: &FocusRect,
target: &FocusRect,
direction: FocusDirection,
options: &ProjectionOptions,
) -> Option<FocusProjectionScore> {
if source.is_empty() || target.is_empty() {
return None;
}
match direction {
FocusDirection::Right => {
if target.center_x() <= source.center_x() || target.left() < source.left() {
return None;
}
let primary_distance = if target.left() >= source.right() {
(target.left() - source.right()) as f64
} else {
target.center_x() - source.center_x()
};
let overlap_start = source.top().max(target.top());
let overlap_end = source.bottom().min(target.bottom());
let in_beam = overlap_end > overlap_start;
let overlap = if in_beam {
(overlap_end - overlap_start) as f64
} else {
0.0
};
let orthogonal_distance = if in_beam {
(source.center_y() - target.center_y()).abs() * 0.5
} else {
let gap = if target.top() >= source.bottom() {
(target.top() - source.bottom()) as f64
} else {
(source.top() - target.bottom()) as f64
};
gap + (source.center_y() - target.center_y()).abs() * 0.5
};
let ar = target.aspect_ratio();
let ar_mod = if options.aspect_ratio_weight > 0.0 && ar > 0.0 {
ar.powf(options.aspect_ratio_weight)
} else {
1.0
};
let effective_orthogonal = orthogonal_distance / ar_mod;
let weighted_score = if in_beam {
options.primary_weight * primary_distance
+ options.orthogonal_weight_in_beam * effective_orthogonal
- (overlap * options.overlap_weight)
} else {
options.primary_weight * primary_distance
+ options.orthogonal_weight_off_beam * effective_orthogonal
+ options.off_beam_penalty
};
Some(FocusProjectionScore {
in_beam,
primary_distance,
orthogonal_distance,
overlap,
weighted_score,
})
}
FocusDirection::Left => {
if target.center_x() >= source.center_x() || target.right() > source.right() {
return None;
}
let primary_distance = if target.right() <= source.left() {
(source.left() - target.right()) as f64
} else {
source.center_x() - target.center_x()
};
let overlap_start = source.top().max(target.top());
let overlap_end = source.bottom().min(target.bottom());
let in_beam = overlap_end > overlap_start;
let overlap = if in_beam {
(overlap_end - overlap_start) as f64
} else {
0.0
};
let orthogonal_distance = if in_beam {
(source.center_y() - target.center_y()).abs() * 0.5
} else {
let gap = if target.top() >= source.bottom() {
(target.top() - source.bottom()) as f64
} else {
(source.top() - target.bottom()) as f64
};
gap + (source.center_y() - target.center_y()).abs() * 0.5
};
let ar = target.aspect_ratio();
let ar_mod = if options.aspect_ratio_weight > 0.0 && ar > 0.0 {
ar.powf(options.aspect_ratio_weight)
} else {
1.0
};
let effective_orthogonal = orthogonal_distance / ar_mod;
let weighted_score = if in_beam {
options.primary_weight * primary_distance
+ options.orthogonal_weight_in_beam * effective_orthogonal
- (overlap * options.overlap_weight)
} else {
options.primary_weight * primary_distance
+ options.orthogonal_weight_off_beam * effective_orthogonal
+ options.off_beam_penalty
};
Some(FocusProjectionScore {
in_beam,
primary_distance,
orthogonal_distance,
overlap,
weighted_score,
})
}
FocusDirection::Down => {
if target.center_y() <= source.center_y() || target.top() < source.top() {
return None;
}
let primary_distance = if target.top() >= source.bottom() {
(target.top() - source.bottom()) as f64
} else {
target.center_y() - source.center_y()
};
let overlap_start = source.left().max(target.left());
let overlap_end = source.right().min(target.right());
let in_beam = overlap_end > overlap_start;
let overlap = if in_beam {
(overlap_end - overlap_start) as f64
} else {
0.0
};
let orthogonal_distance = if in_beam {
(source.center_x() - target.center_x()).abs() * 0.5
} else {
let gap = if target.left() >= source.right() {
(target.left() - source.right()) as f64
} else {
(source.left() - target.right()) as f64
};
gap + (source.center_x() - target.center_x()).abs() * 0.5
};
let ar = target.aspect_ratio();
let ar_vert = if ar > 0.0 { 1.0 / ar } else { 1.0 };
let ar_mod = if options.aspect_ratio_weight > 0.0 && ar_vert > 0.0 {
ar_vert.powf(options.aspect_ratio_weight)
} else {
1.0
};
let effective_orthogonal = orthogonal_distance / ar_mod;
let weighted_score = if in_beam {
options.primary_weight * primary_distance
+ options.orthogonal_weight_in_beam * effective_orthogonal
- (overlap * options.overlap_weight)
} else {
options.primary_weight * primary_distance
+ options.orthogonal_weight_off_beam * effective_orthogonal
+ options.off_beam_penalty
};
Some(FocusProjectionScore {
in_beam,
primary_distance,
orthogonal_distance,
overlap,
weighted_score,
})
}
FocusDirection::Up => {
if target.center_y() >= source.center_y() || target.bottom() > source.bottom() {
return None;
}
let primary_distance = if target.bottom() <= source.top() {
(source.top() - target.bottom()) as f64
} else {
source.center_y() - target.center_y()
};
let overlap_start = source.left().max(target.left());
let overlap_end = source.right().min(target.right());
let in_beam = overlap_end > overlap_start;
let overlap = if in_beam {
(overlap_end - overlap_start) as f64
} else {
0.0
};
let orthogonal_distance = if in_beam {
(source.center_x() - target.center_x()).abs() * 0.5
} else {
let gap = if target.left() >= source.right() {
(target.left() - source.right()) as f64
} else {
(source.left() - target.right()) as f64
};
gap + (source.center_x() - target.center_x()).abs() * 0.5
};
let ar = target.aspect_ratio();
let ar_vert = if ar > 0.0 { 1.0 / ar } else { 1.0 };
let ar_mod = if options.aspect_ratio_weight > 0.0 && ar_vert > 0.0 {
ar_vert.powf(options.aspect_ratio_weight)
} else {
1.0
};
let effective_orthogonal = orthogonal_distance / ar_mod;
let weighted_score = if in_beam {
options.primary_weight * primary_distance
+ options.orthogonal_weight_in_beam * effective_orthogonal
- (overlap * options.overlap_weight)
} else {
options.primary_weight * primary_distance
+ options.orthogonal_weight_off_beam * effective_orthogonal
+ options.off_beam_penalty
};
Some(FocusProjectionScore {
in_beam,
primary_distance,
orthogonal_distance,
overlap,
weighted_score,
})
}
FocusDirection::TabNext | FocusDirection::TabPrev => None,
}
}
pub fn compute_projection_score(
source: &FocusRect,
target: &FocusRect,
direction: FocusDirection,
) -> Option<FocusProjectionScore> {
compute_projection_score_options(source, target, direction, &ProjectionOptions::default())
}
pub fn find_next_focus_2d<'a, T: Clone>(
current_rect: &FocusRect,
candidates: &'a [FocusCandidate<T>],
direction: FocusDirection,
wrap_around: bool,
) -> Option<&'a FocusCandidate<T>> {
find_next_focus_2d_options(
current_rect,
candidates,
direction,
wrap_around,
&ProjectionOptions::default(),
)
}
pub fn find_next_focus_2d_options<'a, T: Clone>(
current_rect: &FocusRect,
candidates: &'a [FocusCandidate<T>],
direction: FocusDirection,
wrap_around: bool,
options: &ProjectionOptions,
) -> Option<&'a FocusCandidate<T>> {
if !direction.is_directional() || candidates.is_empty() {
return None;
}
let mut best_candidate: Option<(&'a FocusCandidate<T>, FocusProjectionScore)> = None;
for candidate in candidates {
if !candidate.focusable || candidate.rect.is_empty() || &candidate.rect == current_rect {
continue;
}
if let Some(score) =
compute_projection_score_options(current_rect, &candidate.rect, direction, options)
{
match &best_candidate {
None => best_candidate = Some((candidate, score)),
Some((_, best_score)) => {
if score.is_better_than(best_score) {
best_candidate = Some((candidate, score));
}
}
}
}
}
if let Some((best, _)) = best_candidate {
return Some(best);
}
if wrap_around {
let eligible: Vec<&'a FocusCandidate<T>> = candidates
.iter()
.filter(|c| c.focusable && !c.rect.is_empty() && &c.rect != current_rect)
.collect();
if eligible.is_empty() {
return None;
}
return match direction {
FocusDirection::Right => {
eligible.into_iter().min_by_key(|c| c.rect.left())
}
FocusDirection::Left => {
eligible.into_iter().max_by_key(|c| c.rect.right())
}
FocusDirection::Down => {
eligible.into_iter().min_by_key(|c| c.rect.top())
}
FocusDirection::Up => {
eligible.into_iter().max_by_key(|c| c.rect.bottom())
}
FocusDirection::TabNext | FocusDirection::TabPrev => None,
};
}
None
}
pub fn find_next_focus_tab<'a, T: Clone + PartialEq>(
current_id: Option<&T>,
candidates: &'a [FocusCandidate<T>],
direction: FocusDirection,
wrap_around: bool,
) -> Option<&'a FocusCandidate<T>> {
if !direction.is_tab() || candidates.is_empty() {
return None;
}
let mut eligible: Vec<&'a FocusCandidate<T>> =
candidates.iter().filter(|c| c.focusable).collect();
if eligible.is_empty() {
return None;
}
eligible.sort_by(|a, b| {
match (a.tab_index, b.tab_index) {
(Some(idx_a), Some(idx_b)) => idx_a.cmp(&idx_b),
(Some(_), None) => std::cmp::Ordering::Less,
(None, Some(_)) => std::cmp::Ordering::Greater,
(None, None) => {
let row_a = a.rect.top() / 8;
let row_b = b.rect.top() / 8;
if row_a != row_b {
row_a.cmp(&row_b)
} else {
a.rect.left().cmp(&b.rect.left())
}
}
}
});
let current_index = current_id.and_then(|id| eligible.iter().position(|c| &c.id == id));
match direction {
FocusDirection::TabNext => match current_index {
Some(idx) => {
if idx + 1 < eligible.len() {
Some(eligible[idx + 1])
} else if wrap_around {
Some(eligible[0])
} else {
None
}
}
None => eligible.first().copied(),
},
FocusDirection::TabPrev => match current_index {
Some(idx) => {
if idx > 0 {
Some(eligible[idx - 1])
} else if wrap_around {
eligible.last().copied()
} else {
None
}
}
None => eligible.last().copied(),
},
_ => None,
}
}
pub fn find_next_focus<'a, T: Clone + PartialEq>(
current_id: Option<&T>,
current_rect: Option<&FocusRect>,
candidates: &'a [FocusCandidate<T>],
direction: FocusDirection,
wrap_around: bool,
) -> Option<&'a FocusCandidate<T>> {
if direction.is_tab() {
find_next_focus_tab(current_id, candidates, direction, wrap_around)
} else if direction.is_directional() {
if let Some(rect) = current_rect {
find_next_focus_2d(rect, candidates, direction, wrap_around)
} else if let Some(id) = current_id {
if let Some(candidate) = candidates.iter().find(|c| &c.id == id) {
find_next_focus_2d(&candidate.rect, candidates, direction, wrap_around)
} else {
candidates.iter().find(|c| c.focusable)
}
} else {
candidates.iter().find(|c| c.focusable)
}
} else {
None
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum GridWrapMode {
#[default]
None,
Axis,
Flow,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct GridAccelerator {
pub threshold: usize,
pub step_multiplier: usize,
pub max_step: usize,
pub consecutive_count: usize,
pub last_direction: Option<FocusDirection>,
}
impl Default for GridAccelerator {
fn default() -> Self {
Self {
threshold: 2,
step_multiplier: 1,
max_step: 4,
consecutive_count: 0,
last_direction: None,
}
}
}
impl GridAccelerator {
pub const fn new(threshold: usize, step_multiplier: usize, max_step: usize) -> Self {
Self {
threshold,
step_multiplier,
max_step,
consecutive_count: 0,
last_direction: None,
}
}
pub fn reset(&mut self) {
self.consecutive_count = 0;
self.last_direction = None;
}
pub fn record_step(&mut self, direction: FocusDirection) -> usize {
if self.last_direction == Some(direction) {
self.consecutive_count = self.consecutive_count.saturating_add(1);
} else {
self.last_direction = Some(direction);
self.consecutive_count = 1;
}
self.current_step()
}
pub fn current_step(&self) -> usize {
if self.consecutive_count <= self.threshold {
1
} else {
let extra = self.consecutive_count - self.threshold;
let step = 1 + extra * self.step_multiplier;
step.min(self.max_step).max(1)
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct FocusGrid<T = WidgetId> {
pub columns: usize,
pub rows: usize,
pub cells: Vec<Option<FocusCandidate<T>>>,
pub wrap_mode: GridWrapMode,
pub accelerator: Option<GridAccelerator>,
}
impl<T: Clone + PartialEq> FocusGrid<T> {
pub fn new(columns: usize, rows: usize) -> Self {
let total = columns * rows;
Self {
columns,
rows,
cells: vec![None; total],
wrap_mode: GridWrapMode::None,
accelerator: None,
}
}
pub fn from_candidates(columns: usize, candidates: Vec<FocusCandidate<T>>) -> Self {
let columns = columns.max(1);
let rows = if candidates.is_empty() {
0
} else {
candidates.len().div_ceil(columns)
};
let mut cells = vec![None; columns * rows];
for (i, c) in candidates.into_iter().enumerate() {
cells[i] = Some(c);
}
Self {
columns,
rows,
cells,
wrap_mode: GridWrapMode::None,
accelerator: None,
}
}
pub fn with_wrap_mode(mut self, wrap_mode: GridWrapMode) -> Self {
self.wrap_mode = wrap_mode;
self
}
pub fn with_accelerator(mut self, accelerator: GridAccelerator) -> Self {
self.accelerator = Some(accelerator);
self
}
pub fn reset_accelerator(&mut self) {
if let Some(ref mut accel) = self.accelerator {
accel.reset();
}
}
pub fn set_cell(&mut self, col: usize, row: usize, candidate: Option<FocusCandidate<T>>) {
if col < self.columns && row < self.rows {
self.cells[row * self.columns + col] = candidate;
}
}
pub fn get_cell(&self, col: usize, row: usize) -> Option<&FocusCandidate<T>> {
if col < self.columns && row < self.rows {
self.cells[row * self.columns + col].as_ref()
} else {
None
}
}
pub fn is_cell_focusable(&self, col: usize, row: usize) -> bool {
self.get_cell(col, row).is_some_and(|c| c.focusable)
}
pub fn find_position(&self, id: &T) -> Option<(usize, usize)> {
for row in 0..self.rows {
for col in 0..self.columns {
if let Some(candidate) = &self.cells[row * self.columns + col] {
if &candidate.id == id {
return Some((col, row));
}
}
}
}
None
}
pub fn navigate_step(
&self,
current_id: &T,
direction: FocusDirection,
step: usize,
) -> Option<&FocusCandidate<T>> {
let (start_col, start_row) = self.find_position(current_id)?;
self.navigate_from_coords(start_col, start_row, direction, step)
}
pub fn navigate_accelerated(
&mut self,
current_id: &T,
direction: FocusDirection,
) -> Option<&FocusCandidate<T>> {
let step = if let Some(ref mut accel) = self.accelerator {
accel.record_step(direction)
} else {
1
};
self.navigate_step(current_id, direction, step)
}
pub fn navigate_from_coords(
&self,
start_col: usize,
start_row: usize,
direction: FocusDirection,
step: usize,
) -> Option<&FocusCandidate<T>> {
if self.columns == 0 || self.rows == 0 || step == 0 {
return None;
}
match direction {
FocusDirection::Right => match self.wrap_mode {
GridWrapMode::None => {
let target_col = (start_col + step).min(self.columns - 1);
if target_col == start_col {
return None;
}
if self.is_cell_focusable(target_col, start_row) {
return self.get_cell(target_col, start_row);
}
for c in (start_col + 1..=target_col).rev() {
if self.is_cell_focusable(c, start_row) {
return self.get_cell(c, start_row);
}
}
for c in (target_col + 1)..self.columns {
if self.is_cell_focusable(c, start_row) {
return self.get_cell(c, start_row);
}
}
None
}
GridWrapMode::Axis => {
let target_col = (start_col + step) % self.columns;
if target_col != start_col && self.is_cell_focusable(target_col, start_row) {
return self.get_cell(target_col, start_row);
}
for offset in 1..self.columns {
let c = (start_col + step + offset) % self.columns;
if c != start_col && self.is_cell_focusable(c, start_row) {
return self.get_cell(c, start_row);
}
}
None
}
GridWrapMode::Flow => {
let total = self.columns * self.rows;
let start_idx = start_row * self.columns + start_col;
let target_idx = (start_idx + step) % total;
let tr = target_idx / self.columns;
let tc = target_idx % self.columns;
if target_idx != start_idx && self.is_cell_focusable(tc, tr) {
return self.get_cell(tc, tr);
}
for offset in 1..total {
let idx = (start_idx + step + offset) % total;
if idx == start_idx {
continue;
}
let r = idx / self.columns;
let c = idx % self.columns;
if self.is_cell_focusable(c, r) {
return self.get_cell(c, r);
}
}
None
}
},
FocusDirection::Left => match self.wrap_mode {
GridWrapMode::None => {
if start_col == 0 {
return None;
}
let target_col = start_col.saturating_sub(step);
if self.is_cell_focusable(target_col, start_row) {
return self.get_cell(target_col, start_row);
}
for c in (target_col..start_col).rev() {
if self.is_cell_focusable(c, start_row) {
return self.get_cell(c, start_row);
}
}
None
}
GridWrapMode::Axis => {
let step_rem = step % self.columns;
let target_col = (start_col + self.columns - step_rem) % self.columns;
if target_col != start_col && self.is_cell_focusable(target_col, start_row) {
return self.get_cell(target_col, start_row);
}
for offset in 1..self.columns {
let c =
(target_col + self.columns - (offset % self.columns)) % self.columns;
if c != start_col && self.is_cell_focusable(c, start_row) {
return self.get_cell(c, start_row);
}
}
None
}
GridWrapMode::Flow => {
let total = self.columns * self.rows;
let start_idx = start_row * self.columns + start_col;
let step_rem = step % total;
let target_idx = (start_idx + total - step_rem) % total;
let tr = target_idx / self.columns;
let tc = target_idx % self.columns;
if target_idx != start_idx && self.is_cell_focusable(tc, tr) {
return self.get_cell(tc, tr);
}
for offset in 1..total {
let idx = (target_idx + total - (offset % total)) % total;
if idx == start_idx {
continue;
}
let r = idx / self.columns;
let c = idx % self.columns;
if self.is_cell_focusable(c, r) {
return self.get_cell(c, r);
}
}
None
}
},
FocusDirection::Down => match self.wrap_mode {
GridWrapMode::None => {
let target_row = (start_row + step).min(self.rows - 1);
if target_row == start_row {
return None;
}
if self.is_cell_focusable(start_col, target_row) {
return self.get_cell(start_col, target_row);
}
for r in (start_row + 1..=target_row).rev() {
if self.is_cell_focusable(start_col, r) {
return self.get_cell(start_col, r);
}
}
for r in (target_row + 1)..self.rows {
if self.is_cell_focusable(start_col, r) {
return self.get_cell(start_col, r);
}
}
None
}
GridWrapMode::Axis | GridWrapMode::Flow => {
let target_row = (start_row + step) % self.rows;
if target_row != start_row && self.is_cell_focusable(start_col, target_row) {
return self.get_cell(start_col, target_row);
}
for offset in 1..self.rows {
let r = (start_row + step + offset) % self.rows;
if r != start_row && self.is_cell_focusable(start_col, r) {
return self.get_cell(start_col, r);
}
}
None
}
},
FocusDirection::Up => match self.wrap_mode {
GridWrapMode::None => {
if start_row == 0 {
return None;
}
let target_row = start_row.saturating_sub(step);
if self.is_cell_focusable(start_col, target_row) {
return self.get_cell(start_col, target_row);
}
for r in (target_row..start_row).rev() {
if self.is_cell_focusable(start_col, r) {
return self.get_cell(start_col, r);
}
}
None
}
GridWrapMode::Axis | GridWrapMode::Flow => {
let step_rem = step % self.rows;
let target_row = (start_row + self.rows - step_rem) % self.rows;
if target_row != start_row && self.is_cell_focusable(start_col, target_row) {
return self.get_cell(start_col, target_row);
}
for offset in 1..self.rows {
let r = (target_row + self.rows - (offset % self.rows)) % self.rows;
if r != start_row && self.is_cell_focusable(start_col, r) {
return self.get_cell(start_col, r);
}
}
None
}
},
FocusDirection::TabNext => {
let total = self.columns * self.rows;
let start_idx = start_row * self.columns + start_col;
for offset in 1..total {
let idx = start_idx + offset;
if idx >= total && self.wrap_mode == GridWrapMode::None {
return None;
}
let wrapped_idx = idx % total;
let r = wrapped_idx / self.columns;
let c = wrapped_idx % self.columns;
if self.is_cell_focusable(c, r) {
return self.get_cell(c, r);
}
}
None
}
FocusDirection::TabPrev => {
let total = self.columns * self.rows;
let start_idx = start_row * self.columns + start_col;
for offset in 1..total {
if start_idx < offset && self.wrap_mode == GridWrapMode::None {
return None;
}
let wrapped_idx = (start_idx + total - (offset % total)) % total;
let r = wrapped_idx / self.columns;
let c = wrapped_idx % self.columns;
if self.is_cell_focusable(c, r) {
return self.get_cell(c, r);
}
}
None
}
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum FocusTrapBoundaryPolicy {
#[default]
Wrap,
Clamp,
Stop,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FocusTrapOutcome<'a, T> {
Moved(&'a FocusCandidate<T>),
Wrapped(&'a FocusCandidate<T>),
Clamped(&'a FocusCandidate<T>),
Stopped,
Exited(&'a FocusCandidate<T>),
}
impl<'a, T> FocusTrapOutcome<'a, T> {
pub fn candidate(&self) -> Option<&'a FocusCandidate<T>> {
match self {
Self::Moved(c) | Self::Wrapped(c) | Self::Clamped(c) | Self::Exited(c) => Some(c),
Self::Stopped => None,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct FocusTrap<T = WidgetId> {
pub container_id: Option<T>,
pub bounds: Option<FocusRect>,
pub members: Vec<T>,
pub boundary_policy: FocusTrapBoundaryPolicy,
pub exit_directions: Vec<FocusDirection>,
pub active: bool,
}
impl<T: Clone + PartialEq> FocusTrap<T> {
pub fn new(members: Vec<T>) -> Self {
Self {
container_id: None,
bounds: None,
members,
boundary_policy: FocusTrapBoundaryPolicy::Wrap,
exit_directions: Vec::new(),
active: true,
}
}
pub fn with_container_id(mut self, container_id: T) -> Self {
self.container_id = Some(container_id);
self
}
pub fn with_bounds(mut self, bounds: FocusRect) -> Self {
self.bounds = Some(bounds);
self
}
pub fn with_boundary_policy(mut self, policy: FocusTrapBoundaryPolicy) -> Self {
self.boundary_policy = policy;
self
}
pub fn with_exit_direction(mut self, direction: FocusDirection) -> Self {
if !self.exit_directions.contains(&direction) {
self.exit_directions.push(direction);
}
self
}
pub fn with_active(mut self, active: bool) -> Self {
self.active = active;
self
}
pub fn activate(&mut self) {
self.active = true;
}
pub fn deactivate(&mut self) {
self.active = false;
}
pub fn contains_candidate(&self, candidate: &FocusCandidate<T>) -> bool {
if self.members.contains(&candidate.id) {
return true;
}
if let Some(bounds) = self.bounds {
if bounds.contains_point(candidate.rect.x, candidate.rect.y)
|| bounds.intersects(&candidate.rect)
{
return true;
}
}
false
}
pub fn contains_id(&self, id: &T) -> bool {
self.members.contains(id)
}
pub fn is_direction_trapped(&self, direction: FocusDirection) -> bool {
self.active && !self.exit_directions.contains(&direction)
}
pub fn navigate<'a>(
&self,
current_id: &T,
current_rect: &FocusRect,
candidates: &'a [FocusCandidate<T>],
direction: FocusDirection,
) -> FocusTrapOutcome<'a, T> {
if !self.active || !self.contains_id(current_id) {
let next = find_next_focus(
Some(current_id),
Some(current_rect),
candidates,
direction,
false,
);
return match next {
Some(c) => FocusTrapOutcome::Moved(c),
None => FocusTrapOutcome::Stopped,
};
}
if self.exit_directions.contains(&direction) {
let next = find_next_focus(
Some(current_id),
Some(current_rect),
candidates,
direction,
false,
);
return match next {
Some(c) => {
if self.contains_id(&c.id) {
FocusTrapOutcome::Moved(c)
} else {
FocusTrapOutcome::Exited(c)
}
}
None => FocusTrapOutcome::Stopped,
};
}
let trapped_candidates: Vec<FocusCandidate<T>> = candidates
.iter()
.filter(|c| self.contains_candidate(c))
.cloned()
.collect();
if let Some(next) = find_next_focus(
Some(current_id),
Some(current_rect),
&trapped_candidates,
direction,
false,
) {
if let Some(original) = candidates.iter().find(|c| c.id == next.id) {
return FocusTrapOutcome::Moved(original);
}
}
match self.boundary_policy {
FocusTrapBoundaryPolicy::Wrap => {
if let Some(wrapped) = find_next_focus(
Some(current_id),
Some(current_rect),
&trapped_candidates,
direction,
true,
) {
if let Some(original) = candidates.iter().find(|c| c.id == wrapped.id) {
return FocusTrapOutcome::Wrapped(original);
}
}
FocusTrapOutcome::Stopped
}
FocusTrapBoundaryPolicy::Clamp => {
if let Some(curr) = candidates.iter().find(|c| &c.id == current_id) {
FocusTrapOutcome::Clamped(curr)
} else {
FocusTrapOutcome::Stopped
}
}
FocusTrapBoundaryPolicy::Stop => FocusTrapOutcome::Stopped,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum FocusRingStyle {
#[default]
Solid,
Dotted,
Dashed,
DoubleRing,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct FocusRingMetrics {
pub thickness: f32,
pub offset: f32,
pub corner_radius: f32,
pub color: Color,
pub secondary_color: Option<Color>,
pub style: FocusRingStyle,
}
impl Default for FocusRingMetrics {
fn default() -> Self {
Self::gtk()
}
}
impl FocusRingMetrics {
pub const fn win32() -> Self {
Self {
thickness: 2.0,
offset: 1.0,
corner_radius: 4.0,
color: Color::rgb(0, 103, 192), secondary_color: None,
style: FocusRingStyle::Solid,
}
}
pub const fn win32_classic() -> Self {
Self {
thickness: 1.0,
offset: 0.0,
corner_radius: 0.0,
color: Color::rgb(0, 0, 0),
secondary_color: None,
style: FocusRingStyle::Dotted,
}
}
pub const fn gtk() -> Self {
Self {
thickness: 2.0,
offset: 2.0,
corner_radius: 4.0,
color: Color::rgb(53, 132, 228), secondary_color: None,
style: FocusRingStyle::Solid,
}
}
pub const fn cocoa() -> Self {
Self {
thickness: 3.0,
offset: 1.0,
corner_radius: 5.0,
color: Color::rgb(10, 132, 255), secondary_color: None,
style: FocusRingStyle::Solid,
}
}
pub const fn high_contrast() -> Self {
Self {
thickness: 3.0,
offset: 2.0,
corner_radius: 4.0,
color: Color::rgb(255, 255, 255), secondary_color: Some(Color::rgb(0, 0, 0)), style: FocusRingStyle::DoubleRing,
}
}
pub fn with_thickness(mut self, thickness: f32) -> Self {
self.thickness = thickness;
self
}
pub fn with_offset(mut self, offset: f32) -> Self {
self.offset = offset;
self
}
pub fn with_corner_radius(mut self, corner_radius: f32) -> Self {
self.corner_radius = corner_radius;
self
}
pub fn with_color(mut self, color: Color) -> Self {
self.color = color;
self
}
pub fn with_secondary_color(mut self, secondary: Color) -> Self {
self.secondary_color = Some(secondary);
self
}
pub fn with_style(mut self, style: FocusRingStyle) -> Self {
self.style = style;
self
}
pub fn compute_outer_bounds(&self, widget_bounds: FocusRect) -> FocusRect {
let expansion = (self.offset + self.thickness).ceil() as i32;
FocusRect::new(
widget_bounds.x - expansion,
widget_bounds.y - expansion,
widget_bounds.width + (2 * expansion),
widget_bounds.height + (2 * expansion),
)
}
pub fn compute_inner_bounds(&self, widget_bounds: FocusRect) -> FocusRect {
let offset_px = self.offset.round() as i32;
FocusRect::new(
widget_bounds.x - offset_px,
widget_bounds.y - offset_px,
widget_bounds.width + (2 * offset_px),
widget_bounds.height + (2 * offset_px),
)
}
pub fn compute_ring_rect(&self, widget_bounds: FocusRect) -> FocusRect {
let half_thickness = self.thickness / 2.0;
let dist = (self.offset + half_thickness).round() as i32;
FocusRect::new(
widget_bounds.x - dist,
widget_bounds.y - dist,
widget_bounds.width + (2 * dist),
widget_bounds.height + (2 * dist),
)
}
pub fn relative_luminance(color: Color) -> f64 {
fn linearize(channel: u8) -> f64 {
let v = channel as f64 / 255.0;
if v <= 0.04045 {
v / 12.92
} else {
((v + 0.055) / 1.055).powf(2.4)
}
}
0.2126 * linearize(color.r) + 0.7152 * linearize(color.g) + 0.0722 * linearize(color.b)
}
pub fn contrast_ratio(c1: Color, c2: Color) -> f64 {
let l1 = Self::relative_luminance(c1);
let l2 = Self::relative_luminance(c2);
let (lighter, darker) = if l1 > l2 { (l1, l2) } else { (l2, l1) };
(lighter + 0.05) / (darker + 0.05)
}
pub fn meets_wcag_contrast(&self, background: Color) -> bool {
Self::contrast_ratio(self.color, background) >= 3.0
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn default_focusable_covers_every_widget_kind() {
let expected = [
(WidgetKind::Window, false),
(WidgetKind::Container, false),
(WidgetKind::Label, false),
(WidgetKind::Button, true),
#[cfg(feature = "widgets-choice")]
(WidgetKind::RadioButton, true),
#[cfg(feature = "widgets-range")]
(WidgetKind::Slider, true),
#[cfg(feature = "widgets-range")]
(WidgetKind::SpinBox, true),
#[cfg(feature = "widgets-containers")]
(WidgetKind::Separator, false),
#[cfg(feature = "widgets-containers")]
(WidgetKind::GroupBox, false),
#[cfg(feature = "widgets-containers")]
(WidgetKind::Tabs, true),
#[cfg(feature = "widgets-media")]
(WidgetKind::Image, false),
#[cfg(feature = "widgets-pickers")]
(WidgetKind::DatePicker, true),
#[cfg(feature = "widgets-text")]
(WidgetKind::LinkLabel, true),
#[cfg(feature = "widgets-data")]
(WidgetKind::ListView, true),
#[cfg(feature = "widgets-data")]
(WidgetKind::TreeView, true),
#[cfg(feature = "widgets-containers")]
(WidgetKind::SplitPane, false),
#[cfg(feature = "widgets-pickers")]
(WidgetKind::FileChooserDialog, true),
#[cfg(feature = "widgets-containers")]
(WidgetKind::AlertDialog, true),
#[cfg(feature = "widgets-text")]
(WidgetKind::TextInput, true),
#[cfg(feature = "widgets-text")]
(WidgetKind::TextArea, true),
#[cfg(feature = "widgets-canvas")]
(WidgetKind::VulkanCanvas, false),
#[cfg(feature = "widgets-choice")]
(WidgetKind::Checkbox, true),
#[cfg(feature = "widgets-choice")]
(WidgetKind::ComboBox, true),
#[cfg(feature = "widgets-range")]
(WidgetKind::ProgressBar, false),
#[cfg(feature = "widgets-data")]
(WidgetKind::DataList, true),
#[cfg(feature = "widgets-data")]
(WidgetKind::DataGrid, true),
#[cfg(feature = "widgets-canvas")]
(WidgetKind::Canvas, true),
#[cfg(feature = "widgets-pickers")]
(WidgetKind::ColorDialog, true),
#[cfg(feature = "widgets-pickers")]
(WidgetKind::FontDialog, true),
(WidgetKind::Toolbar, false),
#[cfg(feature = "widgets-pickers")]
(WidgetKind::Calendar, true),
#[cfg(feature = "widgets-choice")]
(WidgetKind::MultiSelect, true),
];
assert_eq!(expected.len(), abstractable_widget_types().len());
for (kind, focusable) in expected {
assert_eq!(default_focusable(kind), focusable, "default for {kind:?}");
}
}
#[test]
fn explicit_override_wins_over_the_per_kind_default() {
let mut label = WidgetSpec::new(WidgetId(1), WidgetKind::Label);
assert!(!is_focusable(&label));
label.focusable = Some(true);
assert!(is_focusable(&label));
let mut button = WidgetSpec::new(WidgetId(2), WidgetKind::Button);
assert!(is_focusable(&button));
button.focusable = Some(false);
assert!(!is_focusable(&button));
}
#[test]
fn focus_direction_properties_and_invariants() {
assert!(FocusDirection::Up.is_directional());
assert!(FocusDirection::Down.is_directional());
assert!(FocusDirection::Left.is_directional());
assert!(FocusDirection::Right.is_directional());
assert!(!FocusDirection::TabNext.is_directional());
assert!(!FocusDirection::TabPrev.is_directional());
assert!(FocusDirection::TabNext.is_tab());
assert!(FocusDirection::TabPrev.is_tab());
assert!(!FocusDirection::Up.is_tab());
assert_eq!(FocusDirection::Up.opposite(), FocusDirection::Down);
assert_eq!(FocusDirection::Down.opposite(), FocusDirection::Up);
assert_eq!(FocusDirection::Left.opposite(), FocusDirection::Right);
assert_eq!(FocusDirection::Right.opposite(), FocusDirection::Left);
assert_eq!(FocusDirection::TabNext.opposite(), FocusDirection::TabPrev);
assert_eq!(FocusDirection::TabPrev.opposite(), FocusDirection::TabNext);
assert_eq!(FocusDirection::Up.unit_vector(), Some((0, -1)));
assert_eq!(FocusDirection::Down.unit_vector(), Some((0, 1)));
assert_eq!(FocusDirection::Left.unit_vector(), Some((-1, 0)));
assert_eq!(FocusDirection::Right.unit_vector(), Some((1, 0)));
assert_eq!(FocusDirection::TabNext.unit_vector(), None);
}
#[test]
fn focus_rect_geometry_and_queries() {
let r = FocusRect::new(10, 20, 100, 50);
assert_eq!(r.left(), 10);
assert_eq!(r.top(), 20);
assert_eq!(r.right(), 110);
assert_eq!(r.bottom(), 70);
assert_eq!(r.center_x(), 60.0);
assert_eq!(r.center_y(), 45.0);
assert_eq!(r.center(), (60.0, 45.0));
assert!(!r.is_empty());
assert!(r.contains_point(10, 20));
assert!(r.contains_point(109, 69));
assert!(!r.contains_point(110, 70));
assert!(!r.contains_point(9, 20));
let intersecting = FocusRect::new(50, 40, 80, 60);
assert!(r.intersects(&intersecting));
assert!(intersecting.intersects(&r));
let disjoint = FocusRect::new(200, 200, 30, 30);
assert!(!r.intersects(&disjoint));
let empty = FocusRect::new(0, 0, 0, 0);
assert!(empty.is_empty());
}
#[test]
fn directional_2d_horizontal_row_navigation() {
let b1 = FocusCandidate::new(WidgetId(1), FocusRect::new(10, 20, 50, 30));
let b2 = FocusCandidate::new(WidgetId(2), FocusRect::new(80, 20, 50, 30));
let b3 = FocusCandidate::new(WidgetId(3), FocusRect::new(150, 20, 50, 30));
let candidates = [b1.clone(), b2.clone(), b3.clone()];
let next_from_b1 = find_next_focus_2d(&b1.rect, &candidates, FocusDirection::Right, false);
assert_eq!(next_from_b1.map(|c| c.id), Some(WidgetId(2)));
let next_from_b2 = find_next_focus_2d(&b2.rect, &candidates, FocusDirection::Right, false);
assert_eq!(next_from_b2.map(|c| c.id), Some(WidgetId(3)));
let next_from_b3_no_wrap =
find_next_focus_2d(&b3.rect, &candidates, FocusDirection::Right, false);
assert_eq!(next_from_b3_no_wrap, None);
let next_from_b3_wrap =
find_next_focus_2d(&b3.rect, &candidates, FocusDirection::Right, true);
assert_eq!(next_from_b3_wrap.map(|c| c.id), Some(WidgetId(1)));
let prev_from_b3 = find_next_focus_2d(&b3.rect, &candidates, FocusDirection::Left, false);
assert_eq!(prev_from_b3.map(|c| c.id), Some(WidgetId(2)));
let prev_from_b2 = find_next_focus_2d(&b2.rect, &candidates, FocusDirection::Left, false);
assert_eq!(prev_from_b2.map(|c| c.id), Some(WidgetId(1)));
let prev_from_b1_wrap =
find_next_focus_2d(&b1.rect, &candidates, FocusDirection::Left, true);
assert_eq!(prev_from_b1_wrap.map(|c| c.id), Some(WidgetId(3)));
}
#[test]
fn directional_2d_vertical_column_navigation() {
let r1 = FocusCandidate::new(WidgetId(1), FocusRect::new(10, 10, 90, 30));
let r2 = FocusCandidate::new(WidgetId(2), FocusRect::new(10, 60, 90, 30));
let r3 = FocusCandidate::new(WidgetId(3), FocusRect::new(10, 110, 90, 30));
let candidates = [r1.clone(), r2.clone(), r3.clone()];
let next_down_1 = find_next_focus_2d(&r1.rect, &candidates, FocusDirection::Down, false);
assert_eq!(next_down_1.map(|c| c.id), Some(WidgetId(2)));
let next_down_2 = find_next_focus_2d(&r2.rect, &candidates, FocusDirection::Down, false);
assert_eq!(next_down_2.map(|c| c.id), Some(WidgetId(3)));
let next_down_3_wrap =
find_next_focus_2d(&r3.rect, &candidates, FocusDirection::Down, true);
assert_eq!(next_down_3_wrap.map(|c| c.id), Some(WidgetId(1)));
let next_up_3 = find_next_focus_2d(&r3.rect, &candidates, FocusDirection::Up, false);
assert_eq!(next_up_3.map(|c| c.id), Some(WidgetId(2)));
let next_up_1_wrap = find_next_focus_2d(&r1.rect, &candidates, FocusDirection::Up, true);
assert_eq!(next_up_1_wrap.map(|c| c.id), Some(WidgetId(3)));
}
#[test]
fn directional_2d_grid_navigation() {
let a = FocusCandidate::new(WidgetId(1), FocusRect::new(10, 10, 40, 40));
let b = FocusCandidate::new(WidgetId(2), FocusRect::new(70, 10, 40, 40));
let c = FocusCandidate::new(WidgetId(3), FocusRect::new(10, 70, 40, 40));
let d = FocusCandidate::new(WidgetId(4), FocusRect::new(70, 70, 40, 40));
let grid = [a.clone(), b.clone(), c.clone(), d.clone()];
assert_eq!(
find_next_focus_2d(&a.rect, &grid, FocusDirection::Right, false).map(|x| x.id),
Some(WidgetId(2))
);
assert_eq!(
find_next_focus_2d(&a.rect, &grid, FocusDirection::Down, false).map(|x| x.id),
Some(WidgetId(3))
);
assert_eq!(
find_next_focus_2d(&b.rect, &grid, FocusDirection::Left, false).map(|x| x.id),
Some(WidgetId(1))
);
assert_eq!(
find_next_focus_2d(&b.rect, &grid, FocusDirection::Down, false).map(|x| x.id),
Some(WidgetId(4))
);
assert_eq!(
find_next_focus_2d(&c.rect, &grid, FocusDirection::Up, false).map(|x| x.id),
Some(WidgetId(1))
);
assert_eq!(
find_next_focus_2d(&c.rect, &grid, FocusDirection::Right, false).map(|x| x.id),
Some(WidgetId(4))
);
assert_eq!(
find_next_focus_2d(&d.rect, &grid, FocusDirection::Up, false).map(|x| x.id),
Some(WidgetId(2))
);
assert_eq!(
find_next_focus_2d(&d.rect, &grid, FocusDirection::Left, false).map(|x| x.id),
Some(WidgetId(3))
);
}
#[test]
fn directional_beam_projection_prefers_in_beam_over_diagonal() {
let s = FocusRect::new(10, 10, 50, 30);
let in_beam = FocusCandidate::new(WidgetId(1), FocusRect::new(120, 10, 50, 30));
let off_beam = FocusCandidate::new(WidgetId(2), FocusRect::new(70, 70, 50, 30));
let candidates = [off_beam.clone(), in_beam.clone()];
let target = find_next_focus_2d(&s, &candidates, FocusDirection::Right, false);
assert_eq!(
target.map(|c| c.id),
Some(WidgetId(1)),
"In-beam projection must win over diagonal target"
);
}
#[test]
fn directional_navigation_skips_unfocusable_candidates() {
let b1 = FocusCandidate::new(WidgetId(1), FocusRect::new(10, 10, 50, 30));
let b2_disabled =
FocusCandidate::new(WidgetId(2), FocusRect::new(80, 10, 50, 30)).with_focusable(false);
let b3 = FocusCandidate::new(WidgetId(3), FocusRect::new(150, 10, 50, 30));
let candidates = [b1.clone(), b2_disabled, b3.clone()];
let next = find_next_focus_2d(&b1.rect, &candidates, FocusDirection::Right, false);
assert_eq!(
next.map(|c| c.id),
Some(WidgetId(3)),
"Must jump over disabled/unfocusable candidate"
);
}
#[test]
fn tab_navigation_sequence_and_wrap_around() {
let c1 = FocusCandidate::new(WidgetId(1), FocusRect::new(10, 10, 40, 20));
let c2 = FocusCandidate::new(WidgetId(2), FocusRect::new(60, 10, 40, 20));
let c3 = FocusCandidate::new(WidgetId(3), FocusRect::new(10, 40, 40, 20));
let candidates = [c1.clone(), c2.clone(), c3.clone()];
let t1 = find_next_focus_tab(
Some(&WidgetId(1)),
&candidates,
FocusDirection::TabNext,
true,
);
assert_eq!(t1.map(|c| c.id), Some(WidgetId(2)));
let t2 = find_next_focus_tab(
Some(&WidgetId(2)),
&candidates,
FocusDirection::TabNext,
true,
);
assert_eq!(t2.map(|c| c.id), Some(WidgetId(3)));
let t3 = find_next_focus_tab(
Some(&WidgetId(3)),
&candidates,
FocusDirection::TabNext,
true,
);
assert_eq!(t3.map(|c| c.id), Some(WidgetId(1)));
let prev = find_next_focus_tab(
Some(&WidgetId(1)),
&candidates,
FocusDirection::TabPrev,
true,
);
assert_eq!(prev.map(|c| c.id), Some(WidgetId(3)));
}
#[test]
fn tab_navigation_explicit_tab_indices_take_priority() {
let c1 = FocusCandidate::new(WidgetId(1), FocusRect::new(10, 10, 40, 20)).with_tab_index(2);
let c2 = FocusCandidate::new(WidgetId(2), FocusRect::new(60, 10, 40, 20)).with_tab_index(1);
let candidates = [c1.clone(), c2.clone()];
let first = find_next_focus_tab(None, &candidates, FocusDirection::TabNext, true);
assert_eq!(first.map(|c| c.id), Some(WidgetId(2)));
let second = find_next_focus_tab(
Some(&WidgetId(2)),
&candidates,
FocusDirection::TabNext,
true,
);
assert_eq!(second.map(|c| c.id), Some(WidgetId(1)));
}
#[test]
fn focus_ring_metrics_presets_and_bounds() {
let win = FocusRingMetrics::win32();
assert_eq!(win.thickness, 2.0);
assert_eq!(win.offset, 1.0);
assert_eq!(win.style, FocusRingStyle::Solid);
let classic = FocusRingMetrics::win32_classic();
assert_eq!(classic.style, FocusRingStyle::Dotted);
assert_eq!(classic.thickness, 1.0);
let gtk = FocusRingMetrics::gtk();
assert_eq!(gtk.thickness, 2.0);
assert_eq!(gtk.offset, 2.0);
let cocoa = FocusRingMetrics::cocoa();
assert_eq!(cocoa.thickness, 3.0);
assert_eq!(cocoa.offset, 1.0);
let hc = FocusRingMetrics::high_contrast();
assert_eq!(hc.style, FocusRingStyle::DoubleRing);
assert!(hc.secondary_color.is_some());
let widget = FocusRect::new(20, 30, 100, 40);
let outer = gtk.compute_outer_bounds(widget);
assert_eq!(outer, FocusRect::new(16, 26, 108, 48));
let inner = gtk.compute_inner_bounds(widget);
assert_eq!(inner, FocusRect::new(18, 28, 104, 44));
let stroke = gtk.compute_ring_rect(widget);
assert_eq!(stroke, FocusRect::new(17, 27, 106, 46));
}
#[test]
fn focus_ring_wcag_luminance_and_contrast() {
let white = Color::rgb(255, 255, 255);
let black = Color::rgb(0, 0, 0);
let lum_white = FocusRingMetrics::relative_luminance(white);
let lum_black = FocusRingMetrics::relative_luminance(black);
assert!((lum_white - 1.0).abs() < 1e-4);
assert!(lum_black.abs() < 1e-4);
let ratio_bw = FocusRingMetrics::contrast_ratio(white, black);
assert!((ratio_bw - 21.0).abs() < 0.1);
let ratio_same = FocusRingMetrics::contrast_ratio(white, white);
assert!((ratio_same - 1.0).abs() < 1e-4);
let hc = FocusRingMetrics::high_contrast();
assert!(hc.meets_wcag_contrast(black));
let win = FocusRingMetrics::win32();
assert!(win.meets_wcag_contrast(white));
}
#[test]
fn aspect_ratio_calculation_and_distance_weighting() {
let square = FocusRect::new(0, 0, 50, 50);
let wide = FocusRect::new(0, 0, 200, 50);
let tall = FocusRect::new(0, 0, 50, 200);
assert!((square.aspect_ratio() - 1.0).abs() < 1e-6);
assert!((wide.aspect_ratio() - 4.0).abs() < 1e-6);
assert!((tall.aspect_ratio() - 0.25).abs() < 1e-6);
let zero_h = FocusRect::new(0, 0, 100, 0);
assert!((zero_h.aspect_ratio() - 1.0).abs() < 1e-6);
let source = FocusRect::new(0, 0, 50, 50);
let tall_cand = FocusCandidate::new(WidgetId(1), FocusRect::new(100, 60, 20, 50));
let wide_cand = FocusCandidate::new(WidgetId(2), FocusRect::new(100, 70, 200, 40));
let candidates = [tall_cand.clone(), wide_cand.clone()];
let unweighted = find_next_focus_2d_options(
&source,
&candidates,
FocusDirection::Right,
false,
&ProjectionOptions::standard(),
);
assert_eq!(unweighted.map(|c| c.id), Some(WidgetId(1)));
let weighted = find_next_focus_2d_options(
&source,
&candidates,
FocusDirection::Right,
false,
&ProjectionOptions::with_aspect_ratio_weighting(1.0),
);
assert_eq!(weighted.map(|c| c.id), Some(WidgetId(2)));
}
#[test]
fn grid_multi_column_navigation_and_wrap_modes() {
let mut candidates = Vec::new();
for id in 1..=9 {
let row = (id - 1) / 3;
let col = (id - 1) % 3;
candidates.push(FocusCandidate::new(
WidgetId(id),
FocusRect::new(col as i32 * 60, row as i32 * 40, 50, 30),
));
}
let grid_none = FocusGrid::from_candidates(3, candidates.clone());
assert_eq!(grid_none.columns, 3);
assert_eq!(grid_none.rows, 3);
assert_eq!(
grid_none
.navigate_step(&WidgetId(1), FocusDirection::Right, 1)
.map(|c| c.id),
Some(WidgetId(2))
);
assert_eq!(
grid_none
.navigate_step(&WidgetId(1), FocusDirection::Down, 1)
.map(|c| c.id),
Some(WidgetId(4))
);
assert_eq!(
grid_none.navigate_step(&WidgetId(3), FocusDirection::Right, 1),
None
);
assert_eq!(
grid_none.navigate_step(&WidgetId(1), FocusDirection::Left, 1),
None
);
assert_eq!(
grid_none.navigate_step(&WidgetId(7), FocusDirection::Down, 1),
None
);
assert_eq!(
grid_none.navigate_step(&WidgetId(2), FocusDirection::Up, 1),
None
);
let grid_axis = grid_none.clone().with_wrap_mode(GridWrapMode::Axis);
assert_eq!(
grid_axis
.navigate_step(&WidgetId(3), FocusDirection::Right, 1)
.map(|c| c.id),
Some(WidgetId(1)),
"Row wraps back to column 0 in Axis mode"
);
assert_eq!(
grid_axis
.navigate_step(&WidgetId(1), FocusDirection::Left, 1)
.map(|c| c.id),
Some(WidgetId(3)),
"Row wraps back to column 2 in Axis mode"
);
assert_eq!(
grid_axis
.navigate_step(&WidgetId(8), FocusDirection::Down, 1)
.map(|c| c.id),
Some(WidgetId(2)),
"Column wraps back to row 0 in Axis mode"
);
assert_eq!(
grid_axis
.navigate_step(&WidgetId(2), FocusDirection::Up, 1)
.map(|c| c.id),
Some(WidgetId(8)),
"Column wraps back to bottom row in Axis mode"
);
let grid_flow = grid_none.clone().with_wrap_mode(GridWrapMode::Flow);
assert_eq!(
grid_flow
.navigate_step(&WidgetId(3), FocusDirection::Right, 1)
.map(|c| c.id),
Some(WidgetId(4)),
"End of row wraps to beginning of next row in Flow mode"
);
assert_eq!(
grid_flow
.navigate_step(&WidgetId(4), FocusDirection::Left, 1)
.map(|c| c.id),
Some(WidgetId(3)),
"Start of row wraps to end of previous row in Flow mode"
);
assert_eq!(
grid_flow
.navigate_step(&WidgetId(9), FocusDirection::Right, 1)
.map(|c| c.id),
Some(WidgetId(1)),
"End of grid wraps to first item in Flow mode"
);
assert_eq!(
grid_flow
.navigate_step(&WidgetId(1), FocusDirection::Left, 1)
.map(|c| c.id),
Some(WidgetId(9)),
"Start of grid wraps to last item in Flow mode"
);
}
#[test]
fn grid_navigation_acceleration() {
let mut accel = GridAccelerator::new(2, 2, 6);
assert_eq!(accel.current_step(), 1);
assert_eq!(accel.record_step(FocusDirection::Right), 1);
assert_eq!(accel.record_step(FocusDirection::Right), 1);
assert_eq!(accel.record_step(FocusDirection::Right), 3);
assert_eq!(accel.record_step(FocusDirection::Right), 5);
assert_eq!(accel.record_step(FocusDirection::Right), 6);
assert_eq!(accel.record_step(FocusDirection::Down), 1);
let mut candidates = Vec::new();
for id in 1..=36 {
let row = (id - 1) / 6;
let col = (id - 1) % 6;
candidates.push(FocusCandidate::new(
WidgetId(id),
FocusRect::new(col as i32 * 50, row as i32 * 50, 40, 40),
));
}
let mut grid = FocusGrid::from_candidates(6, candidates)
.with_accelerator(GridAccelerator::new(1, 2, 4));
let n1 = grid.navigate_accelerated(&WidgetId(1), FocusDirection::Right);
assert_eq!(n1.map(|c| c.id), Some(WidgetId(2)));
let n2 = grid.navigate_accelerated(&WidgetId(2), FocusDirection::Right);
assert_eq!(n2.map(|c| c.id), Some(WidgetId(5)));
}
#[test]
fn grid_skips_unfocusable_and_empty_cells() {
let mut grid = FocusGrid::new(3, 3);
grid.set_cell(
0,
0,
Some(FocusCandidate::new(
WidgetId(1),
FocusRect::new(0, 0, 40, 30),
)),
);
grid.set_cell(
1,
0,
Some(
FocusCandidate::new(WidgetId(2), FocusRect::new(50, 0, 40, 30))
.with_focusable(false),
),
);
grid.set_cell(2, 0, None);
grid.set_cell(
0,
1,
Some(FocusCandidate::new(
WidgetId(4),
FocusRect::new(0, 40, 40, 30),
)),
);
grid.set_cell(
1,
1,
Some(FocusCandidate::new(
WidgetId(5),
FocusRect::new(50, 40, 40, 30),
)),
);
assert_eq!(
grid.navigate_step(&WidgetId(1), FocusDirection::Right, 1),
None
);
let grid_flow = grid.clone().with_wrap_mode(GridWrapMode::Flow);
assert_eq!(
grid_flow
.navigate_step(&WidgetId(1), FocusDirection::Right, 1)
.map(|c| c.id),
Some(WidgetId(4))
);
}
#[test]
fn directional_focus_trap_containment_and_policies() {
let c1 = FocusCandidate::new(WidgetId(1), FocusRect::new(10, 10, 40, 20));
let c2 = FocusCandidate::new(WidgetId(2), FocusRect::new(60, 10, 40, 20));
let c3 = FocusCandidate::new(WidgetId(3), FocusRect::new(110, 10, 40, 20));
let c4 = FocusCandidate::new(WidgetId(4), FocusRect::new(200, 10, 40, 20)); let candidates = [c1.clone(), c2.clone(), c3.clone(), c4.clone()];
let trap_wrap = FocusTrap::new(vec![WidgetId(1), WidgetId(2), WidgetId(3)])
.with_boundary_policy(FocusTrapBoundaryPolicy::Wrap);
let out1 = trap_wrap.navigate(&WidgetId(2), &c2.rect, &candidates, FocusDirection::Right);
assert_eq!(out1, FocusTrapOutcome::Moved(&c3));
let out2 = trap_wrap.navigate(&WidgetId(3), &c3.rect, &candidates, FocusDirection::Right);
assert_eq!(out2, FocusTrapOutcome::Wrapped(&c1));
let out_tab_prev =
trap_wrap.navigate(&WidgetId(1), &c1.rect, &candidates, FocusDirection::TabPrev);
assert_eq!(out_tab_prev, FocusTrapOutcome::Wrapped(&c3));
let trap_clamp = trap_wrap
.clone()
.with_boundary_policy(FocusTrapBoundaryPolicy::Clamp);
let out_clamp =
trap_clamp.navigate(&WidgetId(3), &c3.rect, &candidates, FocusDirection::Right);
assert_eq!(out_clamp, FocusTrapOutcome::Clamped(&c3));
let trap_stop = trap_wrap
.clone()
.with_boundary_policy(FocusTrapBoundaryPolicy::Stop);
let out_stop =
trap_stop.navigate(&WidgetId(3), &c3.rect, &candidates, FocusDirection::Right);
assert_eq!(out_stop, FocusTrapOutcome::Stopped);
let trap_exit = trap_wrap.clone().with_exit_direction(FocusDirection::Right);
let out_exit =
trap_exit.navigate(&WidgetId(3), &c3.rect, &candidates, FocusDirection::Right);
assert_eq!(out_exit, FocusTrapOutcome::Exited(&c4));
let mut trap_inactive = trap_wrap.clone();
trap_inactive.deactivate();
let out_inactive =
trap_inactive.navigate(&WidgetId(3), &c3.rect, &candidates, FocusDirection::Right);
assert_eq!(out_inactive, FocusTrapOutcome::Moved(&c4));
}
}