1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
|
use std::io::{BufRead, BufReader, Write, stdout};
use std::net::TcpStream;
use rusqlite::Connection;
use std::time::Instant;
use crate::connection;
use crate::database;
use crossterm::{event::{read, Event, KeyCode, KeyModifiers}, terminal::{disable_raw_mode, enable_raw_mode, Clear, ClearType}, cursor::{MoveToColumn, Show}, execute};
macro_rules! println {
() => {
print!("\r\n")
};
($($arg:tt)*) => {
print!("\r{}\n", format_args!($($arg)*))
};
}
pub struct ClientState {
pub stream: Option<TcpStream>,
pub conn: Connection,
pub addr: Option<String>,
pub default_port: u16,
pub history: Vec<String>,
pub history_index: usize,
}
impl ClientState {
pub fn new() -> Self {
let conn = database::init_db();
let default_ip = "127.0.0.1".to_string();
let default_port = 11525;
let last_host = database::get_last_host(&conn);
let default_host = format!("{}:{}", default_ip, default_port);
let addr = last_host.or(Some(default_host));
Self {
stream: None,
conn,
addr,
default_port,
history: vec![],
history_index: 0,
}
}
pub fn connect_to(&mut self, addr: &str) {
self.addr = Some(addr.to_string());
match connection::connect(addr) {
Ok(s) => {
self.stream = Some(s);
database::save_host(&self.conn, addr);
}
Err(e) => println!("Failed to connect: {}", e),
}
}
pub fn run(&mut self) {
enable_raw_mode().unwrap();
'outer: loop {
let mut current_input = String::new();
self.history_index = self.history.len();
redraw("");
loop {
match read().unwrap() {
Event::Key(key) => match key.code {
KeyCode::Up => {
if self.history_index > 0 {
self.history_index -= 1;
current_input = self.history[self.history_index].clone();
redraw(¤t_input);
}
}
KeyCode::Down => {
if self.history_index < self.history.len() {
self.history_index += 1;
current_input = if self.history_index == self.history.len() { "".to_string() } else { self.history[self.history_index].clone() };
redraw(¤t_input);
}
}
KeyCode::Enter => {
let line = current_input.trim().to_string();
if !line.is_empty() {
self.history.push(line.clone());
}
// Process command
let parts: Vec<&str> = line.splitn(2, ' ').collect();
match parts[0] {
"connect" => {
let addr_str = if parts.len() < 2 {
if let Some(h) = &self.addr {
h.clone()
} else {
println!("\nNo host specified and no previous connection. Usage: connect <ip>:<port>");
continue 'outer;
}
} else {
let mut a = parts[1].to_string();
if !a.contains(':') {
a = format!("{}:{}", a, self.default_port);
}
a
};
self.connect_to(&addr_str);
}
"send" => {
if self.stream.is_none() {
println!("\nNot connected. Use 'connect <ip>:<port>' first.");
continue 'outer;
}
if parts.len() < 2 {
println!("\nUsage: send <message>");
continue 'outer;
}
let msg = parts[1];
let s = self.stream.as_mut().unwrap();
let writer_stream = s.try_clone().unwrap();
let mut writer = writer_stream;
let response_reader_stream = s.try_clone().unwrap();
let mut response_reader = BufReader::new(response_reader_stream);
if let Err(_) = writeln!(writer, "{}", msg) {
self.stream = None;
println!("\nConnection lost");
continue 'outer;
}
let mut response = String::new();
if let Err(_) = response_reader.read_line(&mut response) {
self.stream = None;
println!("\nConnection lost");
} else {
println!("\nEcho: {}", response.trim());
}
}
"disconnect" => {
self.stream = None;
println!("\nDisconnected");
}
"ping" => {
if self.stream.is_none() {
println!("\nNot connected. Use 'connect <ip>:<port>' first.");
continue 'outer;
}
let s = self.stream.as_mut().unwrap();
let writer_stream = s.try_clone().unwrap();
let mut writer = writer_stream;
let start = Instant::now();
let response_reader_stream = s.try_clone().unwrap();
let mut response_reader = BufReader::new(response_reader_stream);
if let Err(_) = writeln!(writer, "PING") {
self.stream = None;
println!("\nConnection lost");
continue 'outer;
}
let mut response = String::new();
if let Err(_) = response_reader.read_line(&mut response) {
self.stream = None;
println!("\nConnection lost");
} else {
if response.trim() == "PING" {
let elapsed = start.elapsed();
println!("\nPong ({:?})", elapsed);
} else {
self.stream = None;
println!("\nConnection lost");
}
}
}
"help" => {
help();
}
"quit" => break 'outer,
_ => help(),
}
break;
}
KeyCode::Backspace => {
if !current_input.is_empty() {
current_input.pop();
redraw(¤t_input);
}
}
KeyCode::Char(c) => {
if key.modifiers.contains(KeyModifiers::CONTROL) && c == 'c' {
disable_raw_mode().unwrap();
execute!(stdout(), Show).unwrap();
return;
} else {
current_input.push(c);
redraw(¤t_input);
}
}
_ => {}
}
_ => {}
}
}
}
disable_raw_mode().unwrap();
execute!(stdout(), Show).unwrap();
}
}
fn redraw(current_input: &str) {
execute!(stdout(), Clear(ClearType::CurrentLine), MoveToColumn(0)).unwrap();
print!("> {}", current_input);
stdout().flush().unwrap();
execute!(stdout(), MoveToColumn((2 + current_input.len()) as u16)).unwrap();
}
fn help() {
println!("Available commands: connect <ip>:<port>, send <message>, disconnect, ping, help, quit");
}
|