use rustty::{CellAccessor, Size, HasSize};
use core::{
Alignable,
HorizontalAlign,
VerticalAlign,
Widget,
Frame,
Painter,
};
pub struct Label {
frame: Frame,
text: Vec<String>,
x: usize,
y: usize,
t_halign: HorizontalAlign,
t_valign: VerticalAlign,
t_margin: (usize, usize)
}
impl Label {
pub fn new(cols: usize, rows: usize) -> Label {
Label {
frame: Frame::new(cols, rows),
text: Vec::new(),
x: 0,
y: 0,
t_halign: HorizontalAlign::Left,
t_valign: VerticalAlign::Middle,
t_margin: (0, 0),
}
}
pub fn from_str<S: Into<String>>(s: S) -> Label {
let s = s.into();
Label {
frame: Frame::new(s.len(), 1),
text: vec![s.into()],
x: 0,
y: 0,
t_halign: HorizontalAlign::Left,
t_valign: VerticalAlign::Middle,
t_margin: (0, 0),
}
}
pub fn from_str_ref(s: &str) -> Label
{
Label {
frame: Frame::new(s.len(), 1),
text: vec![s.to_string()],
x: 0,
y: 0,
t_halign: HorizontalAlign::Left,
t_valign: VerticalAlign::Middle,
t_margin: (0, 0),
}
}
pub fn align_text(&mut self, halign: HorizontalAlign, valign: VerticalAlign,
margin: (usize, usize)) {
self.t_halign = halign;
self.t_valign = valign;
self.t_margin = margin;
}
pub fn set_text<S: Into<String>>(&mut self, new_str: S) {
let (framex, _) = self.frame.size();
self.text = Vec::new();
let mut parse = new_str.into();
let mut line = String::new();
loop {
if let Some(loc) = parse.find(char::is_whitespace) {
let line_len = line.len();
let tmp = parse[..loc].to_owned();
if line_len + tmp.len() + self.t_margin.0 < framex {
line.push_str(&tmp);
} else {
line = line.trim_right().to_owned();
self.text.push(line);
line = tmp.to_owned();
}
parse = parse[loc..].to_owned();
} else {
if parse.len() != 0 {
let line_len = line.len();
if line_len + parse.len() + self.t_margin.0 < framex {
line.push_str(&parse);
self.text.push(line);
} else {
self.text.push(line);
self.text.push(parse);
}
}
break;
}
if let Some(loc) = parse.find(|c: char| c != ' ') {
let line_len = line.len();
let tmp = parse[..loc].to_owned();
if line_len + tmp.len() + self.t_margin.0 < framex {
line.push_str(&tmp);
} else {
line = line.trim_right().to_owned();
self.text.push(line);
line = "".to_string();
}
parse = parse[loc..].to_owned();
} else {
break;
}
}
}
}
impl Widget for Label {
fn draw(&mut self, parent: &mut CellAccessor) {
for (i, item) in self.text.iter().enumerate() {
self.x = self.frame.halign_line(&item, self.t_halign.clone(), self.t_margin.0);
self.y = self.frame.valign_line(&item, self.t_valign.clone(), self.t_margin.1);
self.frame.printline(self.x, self.y + i, &item);
}
self.frame.draw_into(parent);
}
fn pack(&mut self, parent: &HasSize, halign: HorizontalAlign, valign: VerticalAlign,
margin: (usize, usize)) {
self.frame.align(parent, halign, valign, margin);
}
fn draw_box(&mut self) {
self.frame.draw_box();
}
fn resize(&mut self, new_size: Size) {
self.frame.resize(new_size);
}
fn frame(&self) -> &Frame {
&self.frame
}
fn frame_mut(&mut self) -> &mut Frame {
&mut self.frame
}
}