You've already forked comprehensive-rust
mirror of
https://github.com/google/comprehensive-rust.git
synced 2025-07-05 22:19:01 +02:00
Main - Fix bug in exercise solution (#569)
* Fix bug in the exercise solution Window may be nested, so its width should also consider border size.
This commit is contained in:
@ -70,6 +70,13 @@ impl Window {
|
|||||||
fn add_widget(&mut self, widget: Box<dyn Widget>) {
|
fn add_widget(&mut self, widget: Box<dyn Widget>) {
|
||||||
self.widgets.push(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),
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ANCHOR_END: setup
|
// ANCHOR_END: setup
|
||||||
@ -78,10 +85,8 @@ impl Window {
|
|||||||
impl Widget for Window {
|
impl Widget for Window {
|
||||||
fn width(&self) -> usize {
|
fn width(&self) -> usize {
|
||||||
// ANCHOR_END: Window-width
|
// ANCHOR_END: Window-width
|
||||||
std::cmp::max(
|
// Add 4 paddings for borders
|
||||||
self.title.chars().count(),
|
self.inner_width() + 4
|
||||||
self.widgets.iter().map(|w| w.width()).max().unwrap_or(0),
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ANCHOR: Window-draw_into
|
// ANCHOR: Window-draw_into
|
||||||
@ -92,18 +97,18 @@ impl Widget for Window {
|
|||||||
widget.draw_into(&mut inner);
|
widget.draw_into(&mut inner);
|
||||||
}
|
}
|
||||||
|
|
||||||
let window_width = self.width();
|
let inner_width = self.inner_width();
|
||||||
|
|
||||||
// TODO: after learning about error handling, you can change
|
// TODO: after learning about error handling, you can change
|
||||||
// draw_into to return Result<(), std::fmt::Error>. Then use
|
// draw_into to return Result<(), std::fmt::Error>. Then use
|
||||||
// the ?-operator here instead of .unwrap().
|
// the ?-operator here instead of .unwrap().
|
||||||
writeln!(buffer, "+-{:-<window_width$}-+", "").unwrap();
|
writeln!(buffer, "+-{:-<inner_width$}-+", "").unwrap();
|
||||||
writeln!(buffer, "| {:^window_width$} |", &self.title).unwrap();
|
writeln!(buffer, "| {:^inner_width$} |", &self.title).unwrap();
|
||||||
writeln!(buffer, "+={:=<window_width$}=+", "").unwrap();
|
writeln!(buffer, "+={:=<inner_width$}=+", "").unwrap();
|
||||||
for line in inner.lines() {
|
for line in inner.lines() {
|
||||||
writeln!(buffer, "| {:window_width$} |", line).unwrap();
|
writeln!(buffer, "| {:inner_width$} |", line).unwrap();
|
||||||
}
|
}
|
||||||
writeln!(buffer, "+-{:-<window_width$}-+", "").unwrap();
|
writeln!(buffer, "+-{:-<inner_width$}-+", "").unwrap();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user