Uma Biblioteca GUI Simples

Vamos projetar uma biblioteca GUI clĂĄssica usando nosso novo conhecimento de traits e objetos de trait.

Teremos vĂĄrios widgets em nossa biblioteca:

  • Window: tem um tĂ­tulo e contĂ©m outros widgets.
  • Button: tem um rĂłtulo e uma função de callback que Ă© invocada quando o botĂŁo Ă© pressionado.
  • Label: tem um rĂłtulo.

Os widgets irĂŁo implementar o trait Widget, veja abaixo.

Copie o cĂłdigo abaixo para https://play.rust-lang.org/, codifique os mĂ©todos draw_into para que vocĂȘ implemente o trait Widget:

// TODO: remove this when you're done with your implementation. #![allow(unused_imports, unused_variables, dead_code)] pub trait Widget { /// Natural width of `self`. fn width(&self) -> usize; /// Draw the widget into a buffer. fn draw_into(&self, buffer: &mut dyn std::fmt::Write); /// Draw the widget on standard output. fn draw(&self) { let mut buffer = String::new(); self.draw_into(&mut buffer); println!("{buffer}"); } } pub struct Label { label: String, } impl Label { fn new(label: &str) -> Label { Label { label: label.to_owned(), } } } pub struct Button { label: Label, callback: Box<dyn FnMut()>, } impl Button { fn new(label: &str, callback: Box<dyn FnMut()>) -> Button { Button { label: Label::new(label), callback, } } } pub struct Window { title: String, widgets: Vec<Box<dyn Widget>>, } impl Window { fn new(title: &str) -> Window { Window { title: title.to_owned(), widgets: Vec::new(), } } fn add_widget(&mut self, widget: Box<dyn Widget>) { self.widgets.push(widget); } fn inner_width(&self) -> usize { std::cmp::max( self.title.chars().count(), self.widgets.iter().map(|w| w.width()).max().unwrap_or(0), ) } } impl Widget for Label { fn width(&self) -> usize { unimplemented!() } fn draw_into(&self, buffer: &mut dyn std::fmt::Write) { unimplemented!() } } impl Widget for Button { fn width(&self) -> usize { unimplemented!() } fn draw_into(&self, buffer: &mut dyn std::fmt::Write) { unimplemented!() } } impl Widget for Window { fn width(&self) -> usize { unimplemented!() } fn draw_into(&self, buffer: &mut dyn std::fmt::Write) { unimplemented!() } } fn main() { let mut window = Window::new("Rust GUI Demo 1.23"); window.add_widget(Box::new(Label::new("This is a small text GUI demo."))); window.add_widget(Box::new(Button::new( "Click me!", Box::new(|| println!("You clicked the button!")), ))); window.draw(); }

A saĂ­da do programa acima pode ser algo simples como:

======== Rust GUI Demo 1.23 ======== This is a small text GUI demo. | Click me! |

Se vocĂȘ quiser desenhar texto alinhado, vocĂȘ pode usar os operadores de formatação fill/alignment. Em particular, observe como vocĂȘ pode preencher com diferentes caracteres (aqui um '/') e como vocĂȘ pode controlar o alinhamento:

XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Usando esses truques de alinhamento, vocĂȘ pode, por exemplo, produzir uma saĂ­da como esta:

+--------------------------------+ | Rust GUI Demo 1.23 | +================================+ | This is a small text GUI demo. | | +-----------+ | | | Click me! | | | +-----------+ | +--------------------------------+