Day 3 Morning Exercise

A Simple GUI Library

(back to exercise)

  1. // Copyright 2022 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // ANCHOR: setup
  15. pub trait Widget {
  16. /// Natural width of `self`.
  17. fn width(&self) -> usize;
  18. /// Draw the widget into a buffer.
  19. fn draw_into(&self, buffer: &mut dyn std::fmt::Write);
  20. /// Draw the widget on standard output.
  21. fn draw(&self) {
  22. let mut buffer = String::new();
  23. self.draw_into(&mut buffer);
  24. println!("{buffer}");
  25. }
  26. }
  27. pub struct Label {
  28. label: String,
  29. }
  30. impl Label {
  31. fn new(label: &str) -> Label {
  32. Label {
  33. label: label.to_owned(),
  34. }
  35. }
  36. }
  37. pub struct Button {
  38. label: Label,
  39. callback: Box<dyn FnMut()>,
  40. }
  41. impl Button {
  42. fn new(label: &str, callback: Box<dyn FnMut()>) -> Button {
  43. Button {
  44. label: Label::new(label),
  45. callback,
  46. }
  47. }
  48. }
  49. pub struct Window {
  50. title: String,
  51. widgets: Vec<Box<dyn Widget>>,
  52. }
  53. impl Window {
  54. fn new(title: &str) -> Window {
  55. Window {
  56. title: title.to_owned(),
  57. widgets: Vec::new(),
  58. }
  59. }
  60. fn add_widget(&mut self, widget: Box<dyn Widget>) {
  61. self.widgets.push(widget);
  62. }
  63. }
  64. // ANCHOR_END: setup
  65. // ANCHOR: Window-width
  66. impl Widget for Window {
  67. fn width(&self) -> usize {
  68. // ANCHOR_END: Window-width
  69. std::cmp::max(
  70. self.title.chars().count(),
  71. self.widgets.iter().map(|w| w.width()).max().unwrap_or(0),
  72. )
  73. }
  74. // ANCHOR: Window-draw_into
  75. fn draw_into(&self, buffer: &mut dyn std::fmt::Write) {
  76. // ANCHOR_END: Window-draw_into
  77. let mut inner = String::new();
  78. for widget in &self.widgets {
  79. widget.draw_into(&mut inner);
  80. }
  81. let window_width = self.width();
  82. // TODO: after learning about error handling, you can change
  83. // draw_into to return Result<(), std::fmt::Error>. Then use
  84. // the ?-operator here instead of .unwrap().
  85. writeln!(buffer, "+-{:-<window_width$}-+", "").unwrap();
  86. writeln!(buffer, "| {:^window_width$} |", &self.title).unwrap();
  87. writeln!(buffer, "+={:=<window_width$}=+", "").unwrap();
  88. for line in inner.lines() {
  89. writeln!(buffer, "| {:window_width$} |", line).unwrap();
  90. }
  91. writeln!(buffer, "+-{:-<window_width$}-+", "").unwrap();
  92. }
  93. }
  94. // ANCHOR: Button-width
  95. impl Widget for Button {
  96. fn width(&self) -> usize {
  97. // ANCHOR_END: Button-width
  98. self.label.width() + 8 // add a bit of padding
  99. }
  100. // ANCHOR: Button-draw_into
  101. fn draw_into(&self, buffer: &mut dyn std::fmt::Write) {
  102. // ANCHOR_END: Button-draw_into
  103. let width = self.width();
  104. let mut label = String::new();
  105. self.label.draw_into(&mut label);
  106. writeln!(buffer, "+{:-<width$}+", "").unwrap();
  107. for line in label.lines() {
  108. writeln!(buffer, "|{:^width$}|", &line).unwrap();
  109. }
  110. writeln!(buffer, "+{:-<width$}+", "").unwrap();
  111. }
  112. }
  113. // ANCHOR: Label-width
  114. impl Widget for Label {
  115. fn width(&self) -> usize {
  116. // ANCHOR_END: Label-width
  117. self.label
  118. .lines()
  119. .map(|line| line.chars().count())
  120. .max()
  121. .unwrap_or(0)
  122. }
  123. // ANCHOR: Label-draw_into
  124. fn draw_into(&self, buffer: &mut dyn std::fmt::Write) {
  125. // ANCHOR_END: Label-draw_into
  126. writeln!(buffer, "{}", &self.label).unwrap();
  127. }
  128. }
  129. // ANCHOR: main
  130. fn main() {
  131. let mut window = Window::new("Rust GUI Demo 1.23");
  132. window.add_widget(Box::new(Label::new("This is a small text GUI demo.")));
  133. window.add_widget(Box::new(Button::new(
  134. "Click me!",
  135. Box::new(|| println!("You clicked the button!")),
  136. )));
  137. window.draw();
  138. }
  139. // ANCHOR_END: main