Exercício: Módulos para uma Biblioteca GUI
Neste exercício, você reorganizará uma pequena implementação de uma biblioteca GUI. Esta biblioteca define um trait Widget
e algumas implementações desse trait, bem como uma função main
.
É típico colocar cada tipo ou conjunto de tipos intimamente relacionados em seu próprio módulo, então cada tipo de widget deve ter seu próprio módulo.
Configuração do Cargo
O playground do Rust suporta apenas um arquivo, então você precisará criar um projeto Cargo em seu sistema de arquivos local:
cargo init gui-modules
cd gui-modules
cargo run
Edite o src/main.rs
resultante para adicionar declarações mod
, e adicione arquivos adicionais no diretório src
.
Código-fonte
Aqui está a implementação de um único módulo da biblioteca GUI:
pub trait Widget {
/// Largura natural de `self`.
fn width(&self) -> usize;
/// Desenha o _widget_ em um buffer.
fn draw_into(&self, buffer: &mut dyn std::fmt::Write);
/// Desenha o _widget_ na saída padrão.
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,
}
impl Button {
fn new(label: &str) -> Button {
Button { label: Label::new(label) }
}
}
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 Window {
fn width(&self) -> usize {
// Adiciona 4 preenchimentos para as bordas
self.inner_width() + 4
}
fn draw_into(&self, buffer: &mut dyn std::fmt::Write) {
let mut inner = String::new();
for widget in &self.widgets {
widget.draw_into(&mut inner);
}
let inner_width = self.inner_width();
// TODO: Altere draw_into para retornar Result<(), std::fmt::Error>. Então use
// o operador ? aqui em vez de .unwrap().
writeln!(buffer, "+-{:-<inner_width$}-+", "").unwrap();
writeln!(buffer, "| {:^inner_width$} |", &self.title).unwrap();
writeln!(buffer, "+={:=<inner_width$}=+", "").unwrap();
for line in inner.lines() {
writeln!(buffer, "| {:inner_width$} |", line).unwrap();
}
writeln!(buffer, "+-{:-<inner_width$}-+", "").unwrap();
}
}
impl Widget for Button {
fn width(&self) -> usize {
self.label.width() + 8 // adicione um pouco de preenchimento
}
fn draw_into(&self, buffer: &mut dyn std::fmt::Write) {
let width = self.width();
let mut label = String::new();
self.label.draw_into(&mut label);
writeln!(buffer, "+{:-<width$}+", "").unwrap();
for line in label.lines() {
writeln!(buffer, "|{:^width$}|", &line).unwrap();
}
writeln!(buffer, "+{:-<width$}+", "").unwrap();
}
}
impl Widget for Label {
fn width(&self) -> usize {
self.label.lines().map(|line| line.chars().count()).max().unwrap_or(0)
}
fn draw_into(&self, buffer: &mut dyn std::fmt::Write) {
writeln!(buffer, "{}", &self.label).unwrap();
}
}
fn main() {
let mut window = Window::new("Rust GUI Demo 1.23");
window.add_widget(Box::new(Label::new("Este é um pequeno demo de GUI em texto.")));
window.add_widget(Box::new(Button::new("Clique em mim!")));
window.draw();
}
Speaker Notes
This slide and its sub-slides should take about 15 minutes.
Incentive os alunos a dividir o código de uma maneira que pareça natural para eles, e se acostumem com as declarações mod
, use
e pub
necessárias. Depois, discuta quais organizações são mais idiomáticas.