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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
/*
This is part of WHY2
Copyright (C) 2022-2026 Václav Šmejkal
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
use ratatui::text::{ Line, Span };
use crate::
{
options,
network::client::ClientEvent,
};
use super::
{
theme,
state::App,
tofu::Prompt,
login::Stage,
};
//IMPLEMENTATIONS
impl App
{
//TRANSLATES ONE SERVER/CLIENT EVENT INTO STATE. NOTHING HERE PRINTS OR TOUCHES THE TERMINAL.
pub fn apply(&mut self, event: ClientEvent)
{
match event
{
//THE PROMPTS THEMSELVES LIVE IN THE CONNECT BOX - NOTHING GOES INTO THE HISTORY
//NOTHING IS PUSHED HERE, SO THE REDRAW HAS TO BE ASKED FOR - THE TICK ONLY DRAWS WHEN DIRTY
ClientEvent::Register =>
{
if let Some(login) = self.login.as_mut() { login.ask(Stage::Password { register: true }, None); }
self.dirty = true;
},
ClientEvent::Login =>
{
if let Some(login) = self.login.as_mut() { login.ask(Stage::Password { register: false }, None); }
self.dirty = true;
},
ClientEvent::FirstUser =>
{
self.push_styled("You are the first user to register, owner role has been granted to you.", theme::NOTICE);
},
ClientEvent::Authenticated(role) =>
{
self.login = None; //THE BOX HAS ASKED FOR EVERYTHING IT WAS GOING TO ASK FOR
self.role = role;
self.push_styled("Login successful. Press Ctrl+H for help.", theme::OK);
self.refresh_online = true;
},
ClientEvent::Connected(server_name) =>
{
self.push_styled(format!("Successfully connected to {server_name}."), theme::OK);
self.server_name = server_name;
},
//STORED UNRENDERED - App::theme TURNS IT INTO A LINE, AGAIN AFTER EVERY THEME CHANGE
ClientEvent::Message(message, username, id, colors) => self.push_message(username, id, message, colors),
ClientEvent::PrivateMessageSent(to, id, msg) =>
{
self.push(Line::from(vec!
[
Span::styled("[PM TO] ", theme::ACCENT),
Span::raw(format!("{to} ({id}): {msg}")),
]));
},
ClientEvent::PrivateMessageRecv(from, id, msg) =>
{
self.push(Line::from(vec!
[
Span::styled("[PM FROM] ", theme::ACCENT),
Span::raw(format!("{from} ({id}): {msg}")),
]));
},
ClientEvent::TofuPrompt(request) =>
{
self.tofu = Some(Prompt::new(request));
self.dirty = true;
},
//REFUSING (OR FAILING) THE CHECK JUST ENDS THE SESSION - THE PROMPT ALREADY SAID WHY
ClientEvent::TofuError => self.quit(1, None),
//THE SERVER WENT AWAY BETWEEN THE TWO CONNECTIONS - BACK TO THE ADDRESS, THE KEY IS PINNED NOW
ClientEvent::ReconnectFailed => self.disconnected("Reconnecting to the server failed."),
//UNLIKE TofuError THERE WAS NO PROMPT TO EXPLAIN ITSELF, SO THE REASON GOES BACK WITH THE BOX
ClientEvent::HandshakeFailed(reason) => self.disconnected(reason),
ClientEvent::TofuSkip(hash) =>
{
self.push_styled("SECURITY WARNING: UNKNOWN SERVER IDENTITY", theme::ERROR);
self.push_styled("The server's identity key cannot be verified due to disabled ToFU \
verification. If you don't recognize the identity key below, disconnect immediately!", theme::NOTICE);
self.push_styled(hash, theme::NOTICE);
},
ClientEvent::VoiceActivity(users) =>
{
self.voice_activity = users;
self.rebuild_voice();
},
//THE WHOLE ROSTER - IT REPLACES WHAT WE HELD, IT DOES NOT ADD TO IT
ClientEvent::VoiceRoster(clients) =>
{
self.voice_roster = clients.into_iter().collect();
self.rebuild_voice();
},
ClientEvent::VoiceJoin(id, username) =>
{
self.voice_roster.insert(id, username);
self.rebuild_voice();
},
ClientEvent::VoiceLeave(id) =>
{
self.voice_roster.remove(&id);
self.rebuild_voice();
},
ClientEvent::Join(uname) =>
{
self.push(Line::from(vec!
[
Span::styled(format!("[{}] ", options::get_server_username()), theme::DIM),
Span::styled(format!("{uname} connected."), theme::OK),
]));
self.refresh_online = true;
},
ClientEvent::Leave(uname, id) =>
{
self.push(Line::from(vec!
[
Span::styled(format!("[{}] ", options::get_server_username()), theme::DIM),
Span::styled(format!("{uname} disconnected."), theme::DIM),
]));
//NO PacketCode::List HERE: A KICK WOULD PUT ONE RIGHT BEHIND THE ServerKick PACKET AND
//EARN A SpamWarning. THE Leave PACKET NAMES THE USER, SO THE ROSTER CAN DROP THEM ITSELF
self.online.retain(|user| user.id != id);
//A DISCONNECT IS BROADCAST TO EVERY CHANNEL AND CARRIES NO VoiceLeave OF ITS OWN
if self.voice_roster.remove(&id).is_some() { self.rebuild_voice(); }
//SAME RULE AS ClientEvent::List - A CHANNEL EXISTS EXACTLY AS LONG AS SOMEBODY IS IN IT
self.channels = self.online.iter().filter_map(|user| user.channel.clone()).collect();
self.prune_panes();
},
ClientEvent::Muted =>
{
self.push_styled("You have been muted by moderator.", theme::NOTICE);
},
ClientEvent::InvalidUsage =>
{
self.push_styled("Invalid usage! Press Ctrl+H for help.", theme::ERROR);
},
ClientEvent::UnsafeVersion(newer_versions, current_version, newest_version) =>
{
self.push_styled(format!("This release could be unsafe! You are {newer_versions} \
versions behind! ({current_version}/{newest_version})"), theme::NOTICE);
},
ClientEvent::Username(disabled_registration, min_uname, max_uname) =>
{
let hint = if disabled_registration
{
String::from("Registration is disabled.")
} else
{
format!("a-Z, 0-9; {min_uname}-{max_uname} characters")
};
if let Some(login) = self.login.as_mut() { login.ask(Stage::Username, Some(hint)); }
self.dirty = true;
},
ClientEvent::VoiceEnabled =>
{
self.voice_enabled = true;
self.rebuild_voice();
self.push_styled("Voice enabled.", theme::OK);
},
ClientEvent::VoiceDeviceFailed =>
{
self.push_styled("Switching the audio device failed - the previous one is still in use.", theme::ERROR);
//THE VOICE CLIENT POINTED THE CONFIG BACK AT THE DEVICE THAT IS ACTUALLY PLAYING
#[cfg(feature = "client_voice")]
self.settings.refresh_devices();
},
ClientEvent::VoiceHandshakeFailed =>
{
self.push_styled("The server never answered the voice handshake - is UDP getting through?", theme::ERROR);
},
ClientEvent::VoiceDisabled =>
{
//ONLY OUR OWN HALF OF THE PANEL GOES - THE OTHERS ARE STILL IN VOICE, WE JUST STOPPED HEARING THEM
self.voice_enabled = false;
self.voice_activity.clear();
self.rebuild_voice();
self.push_styled("Voice disabled.", theme::DIM);
},
//SERVER MESSAGE
ClientEvent::ServerSay(message) =>
{
self.push(Line::from(vec!
[
Span::styled(format!("[{}] ", options::get_server_username()), theme::DIM),
Span::styled(message, theme::NOTICE),
]));
},
//A ROLE WAS SET. THE SERVER NAMES THE USER WHEN IT IS SOMEBODY ELSE, SO THE ONE WITHOUT A NAME
//IS OURS - AND THAT ONE HAS TO LAND IN App::role, WHICH IS WHAT THE PALETTE AND /help READ
ClientEvent::Role(role, username) =>
{
match username
{
Some(username) => self.push_styled(format!("{username} is now {role}."), theme::NOTICE),
None =>
{
self.role = role;
self.push_styled(format!("You are now {role}."), theme::NOTICE);
},
}
},
//THE LOBBY'S STORED MESSAGES
ClientEvent::History(messages) =>
{
self.push_styled(format!("Message history ({}):", messages.len()), theme::TITLE);
for message in messages
{
self.push_history(message.username, message.text, message.colors);
}
},
//server.toml CAME BACK - EITHER THE COPY WE ASKED FOR, OR THE ONE THE SERVER JUST STORED
ClientEvent::ServerSettings(settings, saved) =>
{
match saved
{
//THE ANSWER TO A SAVE IS THE CONFIG AS IT ACTUALLY STANDS, SO A REFUSED ROW SNAPS BACK
true =>
{
if self.settings.open && self.settings.server { self.settings.stored(settings); }
self.push_styled("Server settings saved.", theme::OK);
},
false => self.settings.open_server(settings),
}
self.dirty = true;
},
//ASKED FOR BY /server bans, AND SENT AGAIN AFTER EVERY PARDON - THE IDS RENUMBER WHEN ONE
//IS LIFTED, SO THE ANSWER TO A PARDON IS THE NEW LIST RATHER THAN AN 'OK' OVER A STALE ONE
ClientEvent::ServerBans(users, ips) =>
{
if users.is_empty() && ips.is_empty()
{
self.push_styled("No bans.", theme::DIM);
} else
{
self.push_styled(format!("Bans ({}):", users.len() + ips.len()), theme::TITLE);
//TWO SECTIONS, EACH NUMBERED FROM ITS OWN ZERO - THE HEADING NAMES THE ACTION THAT LIFTS IT
let sections = [("users", users), ("addresses", ips)];
let last_section = sections.iter().filter(|(_, bans)| !bans.is_empty()).count().saturating_sub(1);
let mut section_index = 0;
for (name, bans) in sections
{
if bans.is_empty() { continue; }
let last = section_index == last_section;
section_index += 1;
self.push(Line::from(vec!
[
Span::styled(super::branch(last), theme::BORDER),
Span::raw(name),
]));
//THE TRUNK KEEPS RUNNING PAST THE SUBJECTS UNLESS THIS IS THE LAST SECTION
let trunk = format!("{} ", if last { " " } else { "│" });
let width = id_width(bans.iter().map(|ban| ban.id));
let last_ban = bans.len() - 1;
for (index, ban) in bans.into_iter().enumerate()
{
let mut spans = vec![Span::styled(format!("{trunk}{}", super::branch(index == last_ban)), theme::BORDER)];
spans.extend(id_column(ban.id, width));
spans.push(Span::raw(ban.subject));
self.push(Line::from(spans));
}
}
}
},
ClientEvent::List(users) =>
{
//ALWAYS REFRESH THE SIDEBAR; ONLY ECHO A BLOCK WHEN THE USER ASKED FOR ONE
self.online = users;
//AUTHORITATIVE: A CHANNEL EXISTS EXACTLY AS LONG AS SOMEBODY IS IN IT
self.channels = self.online.iter().filter_map(|user| user.channel.clone()).collect();
self.prune_panes();
if self.list_requested
{
self.list_requested = false;
let here = options::get_channel();
let width = id_width(self.online.iter().map(|user| user.id));
let last = self.online.len().saturating_sub(1);
self.push_styled(format!("Online clients ({}):", self.online.len()), theme::TITLE);
let rows = self.online.iter().enumerate().map(|(index, user)|
{
let mut spans = vec![Span::styled(super::branch(index == last), theme::BORDER)];
spans.extend(id_column(user.id, width));
spans.push(Span::raw(user.username.clone()));
//OUR OWN CHANNEL IS ACCENTED SO THE ROSTER SPLITS AT A GLANCE
if let Some(channel) = user.channel.clone()
{
let style = if channel == here { theme::ACCENT } else { theme::DIM };
spans.push(Span::styled(format!(" #{channel}"), style));
}
Line::from(spans)
}).collect::<Vec<Line<'static>>>();
for row in rows { self.push(row); }
}
self.dirty = true;
},
ClientEvent::Upload(filename) =>
{
self.push_text(format!("Uploading file \"{filename}\"..."));
},
ClientEvent::Uploaded(username, filename) =>
{
self.push(Line::from(vec!
[
Span::styled(format!("[{}] ", options::get_server_username()), theme::DIM),
Span::raw(format!("{username} uploaded file \"{filename}\".")),
]));
},
ClientEvent::Download(filename) =>
{
self.push_text(format!("Downloading file \"{filename}\"..."));
},
ClientEvent::Downloaded(filename) =>
{
self.push_styled(format!("File \"{filename}\" downloaded."), theme::OK);
},
ClientEvent::DownloadFailed(filename) =>
{
self.push_styled(format!("Downloading \"{filename}\" failed."), theme::ERROR);
},
ClientEvent::Files(users) =>
{
if users.is_empty()
{
self.push_styled("No available files.", theme::DIM);
} else
{
self.push_styled(format!("Available files ({}):", users.len()), theme::TITLE);
//THE OWNER IS THE BRANCH, THEIR FILES HANG OFF IT - THE TWO IDS SIDE BY SIDE
//ARE THE TWO ARGUMENTS TO /download
let width = id_width(users.iter().map(|user| user.id));
let last = users.len() - 1;
for (index, user) in users.into_iter().enumerate()
{
let mut spans = vec![Span::styled(super::branch(index == last), theme::BORDER)];
spans.extend(id_column(user.id, width));
spans.push(Span::raw(user.username.clone()));
self.push(Line::from(spans));
//THE TRUNK KEEPS RUNNING PAST THE FILES UNLESS THIS IS THE LAST OWNER
let trunk = format!("{} ", if index == last { " " } else { "│" });
let file_width = id_width(user.upload.iter().map(|(_, id)| *id));
let last_file = user.upload.len().saturating_sub(1);
for (file, (filename, file_id)) in user.upload.into_iter().enumerate()
{
let mut spans = vec![Span::styled(format!("{trunk}{}", super::branch(file == last_file)), theme::BORDER)];
spans.extend(id_column(file_id, file_width));
spans.push(Span::raw(filename));
self.push(Line::from(spans));
}
}
}
},
ClientEvent::Screens(users) =>
{
#[cfg(feature = "client_screen")]
{ self.screens_requested = false; }
if users.is_empty()
{
self.push_styled("No available screenshares.", theme::DIM);
} else
{
self.push_styled(format!("Screensharing clients ({}):", users.len()), theme::TITLE);
let width = id_width(users.iter().map(|user| user.id));
let last = users.len() - 1;
for (index, user) in users.into_iter().enumerate()
{
let mut spans = vec![Span::styled(super::branch(index == last), theme::BORDER)];
spans.extend(id_column(user.id, width));
spans.push(Span::raw(user.username));
self.push(Line::from(spans));
}
}
},
ClientEvent::UploadLimit =>
{
self.push_styled("Maximum concurrent uploads reached!", theme::ERROR);
},
ClientEvent::Screen(enabled) =>
{
self.push_styled(format!("{} screen sharing.", if enabled { "Started" } else { "Stopped" }), theme::OK);
},
ClientEvent::ScreenFailed(reason) =>
{
self.push_styled(format!("Screen sharing failed: {reason}."), theme::ERROR);
},
ClientEvent::Attach(username) =>
{
self.push_text(format!("Attached {username}'s screen sharing."));
},
ClientEvent::Deattach(username) =>
{
self.push_text(format!("Deattached {username}'s screen sharing."));
},
//BROADCAST TO EVERYBODY, US INCLUDED - ClientEvent::Screen ALREADY SAID IT ON THIS END
ClientEvent::Screenshare(username) if username != self.username =>
{
self.push(Line::from(vec!
[
Span::styled(format!("[{}] ", options::get_server_username()), theme::DIM),
Span::styled(format!("{username} started screen sharing."), theme::NOTICE),
]));
},
ClientEvent::ScreenshareEnd(username) if username != self.username =>
{
self.push(Line::from(vec!
[
Span::styled(format!("[{}] ", options::get_server_username()), theme::DIM),
Span::styled(format!("{username} stopped screen sharing."), theme::DIM),
]));
},
ClientEvent::Screenshare(_) | ClientEvent::ScreenshareEnd(_) => {},
ClientEvent::Attached(username) =>
{
self.push_text(format!("{username} attached your screen sharing."));
},
ClientEvent::Deattached(username) =>
{
self.push_text(format!("{username} deattached your screen sharing."));
},
ClientEvent::IncompatibleVersion(version, server_version) =>
{
self.push_styled(format!("Incompatible version! ({version}/{server_version})"), theme::ERROR);
},
ClientEvent::VersionMismatch(client_version, server_version) =>
{
self.push_styled(format!("Version mismatch - some features may not work \
({client_version}/{server_version})"), theme::NOTICE);
},
//A REJECTION IS ALWAYS FOLLOWED BY THE RE-PROMPT, AND Login::ask KEEPS THE ERROR ON SCREEN
ClientEvent::UsernameRejected =>
{
match self.login.as_mut()
{
Some(login) => login.error = Some(String::from("Username rejected!")),
None => self.push_styled("Username rejected!", theme::ERROR),
}
self.dirty = true;
},
ClientEvent::PasswordRejected(min_pass) =>
{
let message = format!("Password rejected! Enter at least {min_pass} characters.");
match self.login.as_mut()
{
Some(login) => login.error = Some(message),
None => self.push_styled(message, theme::ERROR),
}
self.dirty = true;
},
ClientEvent::SpamWarning =>
{
self.push_styled("Slow down! You're sending messages too quickly.", theme::NOTICE);
},
ClientEvent::Socks5Voice =>
{
self.push_styled("Voice chat cannot be enabled while using SOCKS5.", theme::ERROR);
},
ClientEvent::DisabledFeature =>
{
self.push_styled("Server has disabled the feature you requested.", theme::ERROR);
},
ClientEvent::VersionFailed =>
{
self.push_styled("Fetching versions failed, this release could be unsafe!", theme::NOTICE);
},
//THE SOCKET IS GONE, BUT THE CLIENT IS NOT: THE CONNECT BOX COMES BACK SO ANOTHER SERVER (OR THE
//SAME ONE AGAIN) IS ONE ENTER AWAY. ONLY A DISCONNECT THE USER ASKED FOR ENDS THE PROCESS.
ClientEvent::Quit =>
{
if self.leaving
{
self.quit(0, Some(String::from("Disconnected from the server.")));
} else if self.logging_out
{
self.disconnected("Logged out.");
} else { self.disconnected("Server quit communication."); }
},
//SIDEBAR-ONLY - THE CHANNEL LIST TRACKS THESE, THE HISTORY DOES NOT.
//NONE OF THEM ASKS THE SERVER FOR ANYTHING: A PacketCode::List HERE WOULD FOLLOW THE /channel
//THAT CAUSED IT INSIDE min_message_delay AND EARN A SPAM WARNING. THE SERVER BROADCASTS
//ChannelCreated/ChannelDestroyed TO EVERYONE, WHICH IS ALREADY THE WHOLE TRUTH ABOUT WHICH
//CHANNELS EXIST - A CHANNEL LIVES EXACTLY AS LONG AS SOMEBODY SITS IN IT.
ClientEvent::ChannelChanged(channel) =>
{
self.switch_channel(channel.clone().unwrap_or_default());
if let Some(name) = channel.clone() { self.channels.insert(name); }
//KEEP OUR OWN ROW HONEST UNTIL THE NEXT LIST REFRESHES EVERYBODY ELSE'S
let me = self.username.clone();
if let Some(user) = self.online.iter_mut().find(|user| user.username == me)
{
user.channel = channel;
}
//THE VOICE ROSTER IS PER CHANNEL - THE NEW ONE'S ARRIVES RIGHT BEHIND THIS PACKET
self.voice_roster.clear();
self.voice_activity.clear();
self.rebuild_voice();
},
ClientEvent::ChannelCreated(name) =>
{
self.channels.insert(name);
self.dirty = true;
},
ClientEvent::ChannelDestroyed(name) =>
{
self.channels.remove(&name);
self.panes.remove(&name);
self.dirty = true;
},
}
}
pub fn quit(&mut self, code: i32, message: Option<String>)
{
self.should_quit = true;
self.exit_code = code;
self.quit_message = message;
self.dirty = true;
}
}
//PRIVATE
//EVERY LIST BLOCK IS A TREE: ONE BRANCH PER ROW, THEN A RIGHT-ALIGNED ID COLUMN, THEN THE NAME
fn id_width(ids: impl Iterator<Item = usize>) -> usize
{
ids.map(|id| id.to_string().len()).max().unwrap_or(1)
}
fn id_column(id: usize, width: usize) -> Vec<Span<'static>>
{
vec![Span::styled(format!("{id:>width$} "), theme::DIM)]
}