1+ use std:: io:: { self , Write } ;
2+
3+ use crossterm:: event:: { read, Event , KeyCode , KeyEventKind } ;
4+
5+ use super :: { i_manager:: IManager , terminal_cursor:: TerminalCursor } ;
6+
7+ const ANSI_COLOR_RESET : & ' static str = "\x1b [0m" ;
8+ const ANSI_BACKGROUND_WHITE : & ' static str = "\x1b [47m" ;
9+
10+ #[ derive( Clone ) ]
11+ pub struct TerminalManager < T : IManager > {
12+ cursor : TerminalCursor < T > ,
13+ }
14+
15+ impl < T : IManager > TerminalManager < T > {
16+
17+ pub fn new ( cursor : TerminalCursor < T > ) -> TerminalManager < T > {
18+ return TerminalManager { cursor} ;
19+ }
20+
21+ pub fn launch ( & mut self ) -> io:: Result < ( ) > {
22+
23+ self . hide_cursor ( ) ;
24+
25+ loop {
26+
27+ self . clear_screen ( ) ;
28+
29+ self . print ( ) ;
30+
31+ let key_event = match read ( ) ? {
32+ Event :: Key ( event) => event,
33+ _ => continue , // Skip non-key events
34+ } ;
35+
36+ if key_event. kind == KeyEventKind :: Press {
37+ match key_event. code {
38+ KeyCode :: Up => { self . cursor . decrease ( ) ; } ,
39+ KeyCode :: Down => { self . cursor . increase ( ) ; } ,
40+ KeyCode :: Enter => {
41+ println ! ( "Enter" ) ;
42+
43+ let update = self . manage ( ) ;
44+ if update. is_none ( ) {
45+ println ! ( "Something goes wrong!" ) ;
46+ break ;
47+ }
48+
49+ self . cursor = update. unwrap ( ) ;
50+
51+ } ,
52+ KeyCode :: Esc => {
53+ println ! ( "Exit" ) ;
54+ break ;
55+ }
56+ _ => println ! ( "Wrong key!" ) ,
57+ }
58+ }
59+ }
60+
61+ Ok ( ( ) )
62+
63+ }
64+
65+ fn clear_screen ( & self ) {
66+ print ! ( "\x1b [2J\x1b [1;1H" ) ;
67+ }
68+
69+ fn hide_cursor ( & self ) {
70+ print ! ( "\x1b [?25l" ) ;
71+ }
72+
73+ fn show_cursor ( & self ) {
74+ print ! ( "\x1b [?25h" ) ;
75+ }
76+
77+ fn print ( & mut self ) {
78+
79+ print ! ( "{}\n \n " , self . cursor. header( ) ) ;
80+
81+ for cursor in self . cursor . options ( ) . iter_mut ( ) . enumerate ( ) {
82+ let index = cursor. 0 ;
83+ let position = cursor. 1 ;
84+
85+ let mut title = position. title ( ) ;
86+ if position. is_focused ( ) {
87+ title = format ! ( "{}{}{}" , ANSI_BACKGROUND_WHITE , title, ANSI_COLOR_RESET ) ;
88+ }
89+ print ! ( "{}.- {}.\n " , index + 1 , title) ;
90+ }
91+
92+ let _ = io:: stdout ( ) . flush ( ) ;
93+
94+ }
95+
96+ fn manage ( & mut self ) -> Option < TerminalCursor < T > > {
97+ let o_option = self . cursor . option ( ) ;
98+ if o_option. is_some ( ) {
99+ let option = o_option. unwrap ( ) ;
100+ return Some ( option. execute ( ) ) ;
101+ }
102+ None
103+ }
104+
105+ }
0 commit comments