Rusty_tui/label.rs
1// Label.rs
2
3use std::io::{self, Write}; // Importing necessary modules for input/output operations
4
5/// A structure representing a text label that can be drawn on a console at a specific position.
6pub struct Label {
7 text: String, // The text to be displayed by the label
8 x: u16, // The x-coordinate (horizontal position) where the label will be drawn
9 y: u16, // The y-coordinate (vertical position) where the label will be drawn
10}
11
12impl Label {
13 /// Creates a new Label instance.
14 ///
15 /// # Arguments
16 ///
17 /// * `text` - A string slice that holds the text of the label.
18 /// * `x` - The horizontal position (x-coordinate) where the label will be drawn.
19 /// * `y` - The vertical position (y-coordinate) where the label will be drawn.
20 ///
21 /// # Returns
22 ///
23 /// A new instance of `Label`.
24 pub fn new(text: &str, x: u16, y: u16) -> Self {
25 Label {
26 text: text.to_string(), // Convert the string slice into a String
27 x, // Set the x-coordinate
28 y, // Set the y-coordinate
29 }
30 }
31
32 /// Draws the label at the specified (x, y) coordinates in the console.
33 ///
34 /// # Arguments
35 ///
36 /// * `stdout` - A mutable reference to any type that implements the `Write` trait, allowing
37 /// the method to write the label's text to the specified output.
38 ///
39 /// # Errors
40 ///
41 /// Returns an `io::Result<()>`, which will contain an error if the write operation fails.
42 ///
43 /// # Example
44 ///
45 /// ```
46 /// use std::io::{self, Write};
47 /// let mut stdout = io::stdout();
48 /// let label = Label::new("Hello, world!", 10, 5);
49 /// label.draw(&mut stdout).unwrap(); // Draws the label
50 /// ```
51 pub fn draw(&self, stdout: &mut impl Write) -> io::Result<()> {
52 // Move the cursor to the (x, y) position in the console
53 write!(stdout, "\x1B[{};{}H", self.y, self.x)?;
54
55 // Print the text of the label
56 write!(stdout, "{}", self.text)?;
57
58 // Flush the output buffer to ensure the text is displayed immediately
59 stdout.flush()?;
60
61 Ok(())
62 }
63}