p2p_chat/ui/terminal/lifecycle.rs
1//! This module handles the lifecycle of the terminal user interface.
2use anyhow::Result;
3use crossterm::{
4 cursor, execute,
5 terminal::{self},
6};
7use std::io::stdout;
8
9use super::TerminalUI;
10
11impl TerminalUI {
12 /// Initializes the terminal for TUI mode.
13 ///
14 /// This function enables raw mode, enters the alternate screen, hides the cursor,
15 /// and captures the initial terminal size.
16 ///
17 /// # Errors
18 ///
19 /// Returns an error if terminal setup fails.
20 pub(super) fn initialize_terminal(&mut self) -> Result<()> {
21 terminal::enable_raw_mode()?;
22 execute!(stdout(), terminal::EnterAlternateScreen, cursor::Hide)?;
23
24 let (width, height) = terminal::size()?;
25 self.state.terminal_size = (width, height);
26
27 Ok(())
28 }
29
30 /// Cleans up the terminal, restoring it to its original state.
31 ///
32 /// This function disables raw mode, leaves the alternate screen, and shows the cursor.
33 ///
34 /// # Errors
35 ///
36 /// Returns an error if terminal cleanup fails.
37 pub fn cleanup(&mut self) -> Result<()> {
38 terminal::disable_raw_mode()?;
39 execute!(stdout(), cursor::Show, terminal::LeaveAlternateScreen)?;
40 Ok(())
41 }
42}
43
44impl Drop for TerminalUI {
45 /// Cleans up the terminal when the `TerminalUI` instance is dropped.
46 fn drop(&mut self) {
47 let _ = self.cleanup();
48 }
49}