use cursive::Vec2;
pub struct LinkHandler {
links: Vec<Link>,
current_link: usize,
}
impl LinkHandler {
pub fn new() -> Self {
Self {
links: Vec::new(),
current_link: 0,
}
}
pub fn registered_links(&self) -> usize {
self.links.len()
}
pub fn push_link(&mut self, id: i32, x: usize, y: usize) {
self.links.push(Link { id, x, y })
}
pub fn get_current_link(&self) -> Option<i32> {
if self.links.is_empty() {
return None;
}
Some(self.links[self.current_link].id)
}
pub fn get_current_link_pos(&self) -> Option<Vec2> {
if self.links.is_empty() {
return None;
}
let link = &self.links[self.current_link];
Some(Vec2::new(link.x, link.y))
}
pub fn move_up(&mut self, amount: usize) {
if self.links.is_empty() {
warn!("no links are registered, abort moving up by '{}'", amount);
return;
}
let min_y = self.links[self.current_link].y.saturating_sub(amount);
for i in (0..self.current_link).rev() {
if self.links[i].y <= min_y {
self.current_link = i;
return;
}
}
self.current_link = 0;
}
pub fn move_down(&mut self, amount: usize) {
if self.links.is_empty() {
warn!("no links are registered, abort moving down by '{}'", amount);
return;
}
let min_y = self.links[self.current_link].y.saturating_add(amount);
for i in self.current_link..self.links.len() {
if self.links[i].y >= min_y {
self.current_link = i;
return;
}
}
self.current_link = self.links.len().saturating_sub(1);
}
pub fn move_left(&mut self, amount: usize) {
if self.links.is_empty() {
warn!("no links are registered, abort moving left by '{}'", amount);
return;
}
self.current_link = self.current_link.saturating_sub(amount);
}
pub fn move_right(&mut self, amount: usize) {
if self.links.is_empty() {
warn!(
"no links are registered, abort moving right by '{}'",
amount
);
return;
}
if self.current_link + amount >= self.links.len() {
self.current_link = self.links.len().saturating_sub(1);
return;
}
self.current_link += amount
}
pub fn set_current_link(&mut self, id: i32) {
if self.links.is_empty() {
warn!(
"no links are registered, abort setting the current link to '{}'",
id
);
return;
}
let new_selection = self
.links
.iter()
.position(|l| l.id == id)
.unwrap_or_default();
debug!(
"replacing the current link '{}', with '{}'",
self.current_link, new_selection
);
self.current_link = new_selection as usize;
}
}
struct Link {
id: i32,
x: usize,
y: usize,
}