use std::rc::Rc;
use std::cell::RefCell;
use crate::Widget;
use crate::common::{BoundingBox, Dimensions, Position};
pub struct LabelWidget {
text: String,
bounding_box: BoundingBox
}
impl LabelWidget {
pub fn new(
x: i32, y: i32, max_width: u32, max_height: u32, text: &str
) -> Rc<RefCell<Self>> {
return Rc::new(RefCell::new(Self {
text: text.to_string(),
bounding_box: BoundingBox::new(
Position::new(x, y),
Dimensions::new(max_width, max_height)
)
}));
}
pub fn set_text(&mut self, new_text: &str) {
self.text = new_text.to_string();
}
pub fn get_text(&mut self) -> String {
return self.text.clone();
}
}
impl Widget for LabelWidget {
fn draw(
&mut self,
positioning_algorithm: &Box<dyn crate::PositioningAlgorithm>,
display_buffer: &mut crate::DisplayBuffer
) {
if self.bounding_box.get_width() == 0 ||
self.bounding_box.get_height() == 0
{
return;
}
let abs_pos = positioning_algorithm.calculate_position(
self.bounding_box.get_position()
);
let mut lines: Vec<String> = vec![];
let user_set_lines: Vec<_> = self.text.split('\n').collect();
for line in user_set_lines {
if line.chars().count() < self.bounding_box.get_width() as usize {
lines.push(line.to_string());
}
else {
let mut label_line = String::new();
for c in line.chars().collect::<Vec<_>>() {
label_line.push(c);
if label_line.chars().count() ==
self.bounding_box.get_width() as usize
{
lines.push(label_line.clone());
label_line.clear();
}
}
}
}
let mut x = 0;
let mut y = 0;
for line in lines {
for c in line.chars().collect::<Vec<_>>() {
display_buffer.set_char(
c,
x + abs_pos.get_x(),
y + abs_pos.get_y()
);
x += 1;
}
x = 0;
y += 1;
}
}
fn get_bounding_box(&self) -> BoundingBox {
return self.bounding_box;
}
}