-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
1808 lines (1718 loc) · 78.4 KB
/
main.cpp
File metadata and controls
1808 lines (1718 loc) · 78.4 KB
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
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Terminal Messenger - client
* Build: g++ -std=c++17 -Wall -Wextra -O2 -pthread -o messenger main.cpp
*/
#include <string>
#include <vector>
#include <map>
#include <set>
#include <deque>
#include <fstream>
#include <sstream>
#include <filesystem>
#include <ctime>
#include <algorithm>
#include <cctype>
#include <stdexcept>
#include <cstdio>
#include <cstring>
#include <optional>
#include <atomic>
#include <mutex>
#include <thread>
#include <functional>
#include <cstdint>
#include <unistd.h>
#include <termios.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <fcntl.h>
#include <locale.h>
#include <wchar.h>
#include <csignal>
// ── SYMBOLS ───────────────────────────────────────────────────────────────────
static const std::string B_TL="╭",B_TR="╮",B_BL="╰",B_BR="╯";
static const std::string B_H="─",B_V="│",SEP="─";
static const std::string BACK_LABEL="← Back";
static const std::string SCROLL_UP=" ↑ more ";
static const std::string INPUT_FILL="░";
static const std::string INPUT_LABEL="Type a message...";
static const std::string ST_SENT="✓",ST_DELIV="✓✓",ST_READ="✓✓";
static const std::string DATA_DIR="./chats";
static const std::string DL_DIR="./downloads";
static const std::string CFG_FILE="./config.ini";
static const double BUB_FRAC=0.55;
// ── Color scheme ──────────────────────────────────────────────────────────────
enum class CS{DEFAULT,WHITE,TERM};
static CS g_cs=CS::DEFAULT;
static std::string C(const char* a){
if(g_cs==CS::TERM)return "";
if(g_cs==CS::WHITE)return "\x1b[97m";
return a;
}
static std::string CB(const char* a){
if(g_cs==CS::TERM)return "\x1b[1m";
if(g_cs==CS::WHITE)return "\x1b[1;97m";
return std::string("\x1b[1m")+a;
}
static std::string CDIM(){return "\x1b[2m";}
// ── ANSI ──────────────────────────────────────────────────────────────────────
static std::string g_buf;
static void buf(const std::string& s){g_buf+=s;}
static void buf(const char* s){g_buf+=s;}
static void flush(){write(STDOUT_FILENO,g_buf.data(),g_buf.size());g_buf.clear();}
static std::string mv(int r,int c){char t[32];snprintf(t,32,"\x1b[%d;%dH",r,c);return t;}
static const char*RESET="\x1b[0m",*BOLD="\x1b[1m",*DIM="\x1b[2m";
static const char*FC="\x1b[36m",*FG="\x1b[32m",*FY="\x1b[33m",*FW="\x1b[97m";
static const char*FM="\x1b[35m",*FR="\x1b[31m",*FB="\x1b[34m";
static const char*BC="\x1b[46m",*FK="\x1b[30m",*BSEL="\x1b[48;5;236m";
static void cls(){buf("\x1b[2J");}
static void hidec(){buf("\x1b[?25l");}
static void showc(){buf("\x1b[?25h");}
// ── UTF-8 ─────────────────────────────────────────────────────────────────────
static int dw(const std::string& s){
std::vector<wchar_t>wb(s.size()+1,0);
size_t n=mbstowcs(wb.data(),s.c_str(),wb.size());
if(n==size_t(-1))return s.size();
int w=wcswidth(wb.data(),n);return w<0?n:w;
}
static std::string tw(const std::string& s,int mx){
if(mx<=0)return "";
int c=0;size_t i=0;
while(i<s.size()){
unsigned char ch=(unsigned char)s[i];
size_t cl=(ch>=0xF0)?4:(ch>=0xE0)?3:(ch>=0xC0)?2:1;
if(i+cl>s.size())break;
int cw=dw(s.substr(i,cl));
if(c+cw>mx)break;
c+=cw;i+=cl;
}
return s.substr(0,i);
}
static std::vector<std::string> wrap(const std::string& t,int w){
std::vector<std::string>ls;
if(w<=0){ls.push_back(t);return ls;}
size_t i=0;
while(i<t.size()){
int c=0;size_t s=i;
while(i<t.size()){
unsigned char ch=(unsigned char)t[i];
size_t cl=(ch>=0xF0)?4:(ch>=0xE0)?3:(ch>=0xC0)?2:1;
if(i+cl>t.size()){i=t.size();break;}
int cw=dw(t.substr(i,cl));
if(c+cw>w)break;
c+=cw;i+=cl;
}
ls.push_back(t.substr(s,i-s));
}
if(ls.empty())ls.emplace_back("");
return ls;
}
static std::string rtw(const std::string& tile,int n){
int tw2=dw(tile);if(tw2<1)return std::string(n,'-');
std::string r;while(dw(r)<n)r+=tile;return tw(r,n);
}
static void pat(int row,int col,const std::string& ansi,const std::string& text,int mx=9999){
if(col<1)col=1;buf(mv(row,col));
if(!ansi.empty())buf(ansi);
buf(tw(text,mx));
if(!ansi.empty())buf(RESET);
}
// ── Raw mode ──────────────────────────────────────────────────────────────────
static struct termios g_orig,g_raw;
static void enRaw(){
tcgetattr(STDIN_FILENO,&g_orig);g_raw=g_orig;
g_raw.c_iflag&=~(IXON|ICRNL|BRKINT|INPCK|ISTRIP);
g_raw.c_oflag&=~(OPOST);g_raw.c_cflag|=(CS8);
g_raw.c_lflag&=~(ECHO|ICANON|ISIG|IEXTEN);
g_raw.c_cc[VMIN]=1;g_raw.c_cc[VTIME]=0;
tcsetattr(STDIN_FILENO,TCSAFLUSH,&g_raw);
}
static void disRaw(){tcsetattr(STDIN_FILENO,TCSAFLUSH,&g_orig);}
static void tsz(int& r,int& c){
struct winsize ws;
if(ioctl(STDOUT_FILENO,TIOCGWINSZ,&ws)==0&&ws.ws_row>0){r=ws.ws_row;c=ws.ws_col;}
else{r=24;c=80;}
}
// ── Keys ──────────────────────────────────────────────────────────────────────
enum class K{NONE,CHAR,ENTER,BS,ESC,UP,DN,LT,RT,PU,PD,SHIFT_ESC,UNK};
struct KE{K key=K::NONE;std::string ch;};
static KE rk(){
KE ev;unsigned char c;
if(read(STDIN_FILENO,&c,1)!=1)return ev;
if(c=='\r'||c=='\n'){ev.key=K::ENTER;return ev;}
if(c==127||c==8){ev.key=K::BS;return ev;}
if(c==27){
struct termios p=g_raw;p.c_cc[VMIN]=0;p.c_cc[VTIME]=1;
tcsetattr(STDIN_FILENO,TCSANOW,&p);
unsigned char sq[16]={};int n=read(STDIN_FILENO,sq,15);
tcsetattr(STDIN_FILENO,TCSANOW,&g_raw);
if(n<=0){ev.key=K::ESC;return ev;}
if(sq[0]=='['){
if(sq[1]=='A')ev.key=K::UP;
else if(sq[1]=='B')ev.key=K::DN;
else if(sq[1]=='C')ev.key=K::RT;
else if(sq[1]=='D')ev.key=K::LT;
else if(sq[1]=='5'&&sq[2]=='~')ev.key=K::PU;
else if(sq[1]=='6'&&sq[2]=='~')ev.key=K::PD;
else ev.key=K::UNK;
} else if(sq[0]==27){ev.key=K::SHIFT_ESC;} // ESC ESC = Shift+Esc approximation
else ev.key=K::UNK;
return ev;
}
ev.key=K::CHAR;ev.ch+=(char)c;
if(c>=0xC0){int e=(c>=0xF0)?3:(c>=0xE0)?2:1;
for(int i=0;i<e;++i){unsigned char b;if(read(STDIN_FILENO,&b,1)==1)ev.ch+=(char)b;}}
return ev;
}
// ── SHA-256 (same as server) ──────────────────────────────────────────────────
static uint32_t rotr32(uint32_t x,int n){return(x>>n)|(x<<(32-n));}
static std::string sha256(const std::string& msg){
static const uint32_t K[64]={
0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,
0x923f82a4,0xab1c5ed5,0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,
0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,
0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,
0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,
0x06ca6351,0x14292967,0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,
0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,
0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,
0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,
0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,
0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2};
uint32_t h[8]={0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19};
std::vector<uint8_t>data(msg.begin(),msg.end());
uint64_t bl=(uint64_t)data.size()*8;
data.push_back(0x80);
while(data.size()%64!=56)data.push_back(0);
for(int i=7;i>=0;--i)data.push_back((bl>>(i*8))&0xff);
for(size_t ck=0;ck<data.size();ck+=64){
uint32_t w[64]={};
for(int i=0;i<16;++i)
w[i]=((uint32_t)data[ck+i*4]<<24)|((uint32_t)data[ck+i*4+1]<<16)|
((uint32_t)data[ck+i*4+2]<<8)|(uint32_t)data[ck+i*4+3];
for(int i=16;i<64;++i){
uint32_t s0=rotr32(w[i-15],7)^rotr32(w[i-15],18)^(w[i-15]>>3);
uint32_t s1=rotr32(w[i-2],17)^rotr32(w[i-2],19)^(w[i-2]>>10);
w[i]=w[i-16]+s0+w[i-7]+s1;
}
uint32_t a=h[0],b2=h[1],c2=h[2],d=h[3],e=h[4],f=h[5],g2=h[6],hh=h[7];
for(int i=0;i<64;++i){
uint32_t S1=rotr32(e,6)^rotr32(e,11)^rotr32(e,25);
uint32_t ch=(e&f)^(~e&g2);
uint32_t t1=hh+S1+ch+K[i]+w[i];
uint32_t S0=rotr32(a,2)^rotr32(a,13)^rotr32(a,22);
uint32_t maj=(a&b2)^(a&c2)^(b2&c2);
uint32_t t2=S0+maj;
hh=g2;g2=f;f=e;e=d+t1;d=c2;c2=b2;b2=a;a=t1+t2;
}
h[0]+=a;h[1]+=b2;h[2]+=c2;h[3]+=d;h[4]+=e;h[5]+=f;h[6]+=g2;h[7]+=hh;
}
char hex[65];for(int i=0;i<8;++i)snprintf(hex+i*8,9,"%08x",h[i]);
return std::string(hex,64);
}
// ── Base64 ────────────────────────────────────────────────────────────────────
static const std::string B64="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
static std::string b64enc(const std::vector<uint8_t>&in){
std::string out;int val=0,valb=-6;
for(uint8_t c:in){val=(val<<8)+c;valb+=8;while(valb>=0){out.push_back(B64[(val>>valb)&0x3F]);valb-=6;}}
if(valb>-6)out.push_back(B64[((val<<8)>>(valb+8))&0x3F]);
while(out.size()%4)out.push_back('=');return out;
}
// ── JSON helpers ──────────────────────────────────────────────────────────────
static std::string jesc(const std::string& s){
std::string r;
for(char c:s){if(c=='"')r+="\\\"";else if(c=='\\')r+="\\\\";else if(c=='\n')r+="\\n";else r+=c;}
return r;
}
static std::string jget(const std::string& j,const std::string& k){
std::string nd="\""+k+"\"";
size_t pos=j.find(nd);if(pos==std::string::npos)return "";
pos+=nd.size();
while(pos<j.size()&&(j[pos]==' '||j[pos]=='\t'||j[pos]==':'))++pos;
if(pos>=j.size())return "";
if(j[pos]=='"'){
++pos;std::string val;bool esc=false;
while(pos<j.size()){char c=j[pos++];
if(esc){if(c=='"')val+='"';else if(c=='\\')val+='\\';else if(c=='n')val+='\n';else{val+='\\';val+=c;}esc=false;}
else if(c=='\\')esc=true;else if(c=='"')break;else val+=c;}
return val;
}
size_t end=pos;while(end<j.size()&&j[end]!=','&&j[end]!='}'&&j[end]!=']')++end;
std::string val=j.substr(pos,end-pos);
while(!val.empty()&&(val.back()==' '||val.back()=='\t'))val.pop_back();
return val;
}
static std::string jb(std::initializer_list<std::pair<std::string,std::string>>kv){
std::string r="{";bool f=true;
for(const auto&p:kv){if(!f)r+=",";r+="\""+p.first+"\":\""+jesc(p.second)+"\"";f=false;}
return r+"}";
}
// ── File helpers ──────────────────────────────────────────────────────────────
static std::string fext(const std::string& p){
auto pos=p.rfind('.');if(pos==std::string::npos)return "FILE";
std::string e=p.substr(pos+1);for(auto&c:e)c=toupper((unsigned char)c);return e;
}
static std::string fname(const std::string& p){
auto pos=p.rfind('/');return pos==std::string::npos?p:p.substr(pos+1);
}
// ── Config ────────────────────────────────────────────────────────────────────
static std::string g_user,g_host,g_passhash;
static int g_port=7777;
static bool g_showHints=true;
static bool g_notifyEnabled=true;
static void saveCfg(){
std::ofstream f(CFG_FILE);if(!f.is_open())return;
std::string s="default";
if(g_cs==CS::WHITE)s="white";else if(g_cs==CS::TERM)s="term";
f<<"color_scheme="<<s<<"\n"<<"username="<<g_user<<"\n";
if(!g_passhash.empty())f<<"passhash="<<g_passhash<<"\n";
if(!g_host.empty())f<<"server_host="<<g_host<<"\n"<<"server_port="<<g_port<<"\n";
f<<"show_hints="<<(g_showHints?"1":"0")<<"\n";
f<<"notify="<<(g_notifyEnabled?"1":"0")<<"\n";
}
static void loadCfg(){
std::ifstream f(CFG_FILE);if(!f.is_open())return;
std::string line;
while(std::getline(f,line)){
auto eq=line.find('=');if(eq==std::string::npos)continue;
std::string k=line.substr(0,eq),v=line.substr(eq+1);
if(k=="color_scheme"){
if(v=="white")g_cs=CS::WHITE;else if(v=="term")g_cs=CS::TERM;else g_cs=CS::DEFAULT;
}else if(k=="username")g_user=v;
else if(k=="passhash")g_passhash=v;
else if(k=="server_host")g_host=v;
else if(k=="server_port"){try{g_port=std::stoi(v);}catch(...){}}
else if(k=="show_hints")g_showHints=(v=="1");
else if(k=="notify")g_notifyEnabled=(v=="1");
}
}
// ── Notifications ─────────────────────────────────────────────────────────────
enum class NotifyBackend { NONE, DUNSTIFY, NOTIFY_SEND, HERBE, BELL };
static NotifyBackend g_notifyBackend = NotifyBackend::NONE;
static bool cmdExists(const std::string& cmd){
return system(("command -v "+cmd+" >/dev/null 2>&1").c_str())==0;
}
static void detectNotifyBackend(){
if(cmdExists("dunstify")) g_notifyBackend=NotifyBackend::DUNSTIFY;
else if(cmdExists("notify-send")) g_notifyBackend=NotifyBackend::NOTIFY_SEND;
else if(cmdExists("herbe")) g_notifyBackend=NotifyBackend::HERBE;
else g_notifyBackend=NotifyBackend::BELL;
}
static std::string shellEscape(const std::string& s){
std::string r="'";
for(char c:s){if(c=='\'')r+="'\\''";else r+=c;}
return r+"'";
}
static void sendNotify(const std::string& title,const std::string& body){
if(!g_notifyEnabled)return;
std::string t=shellEscape(tw(title,64));
std::string b=shellEscape(tw(body,128));
switch(g_notifyBackend){
case NotifyBackend::DUNSTIFY:
system(("dunstify -a 'Terminal Messenger' -u normal -t 4000 "+t+" "+b+" &").c_str());
break;
case NotifyBackend::NOTIFY_SEND:
system(("notify-send -a 'Terminal Messenger' -u normal -t 4000 "+t+" "+b+" &").c_str());
break;
case NotifyBackend::HERBE:
system(("herbe "+t+": "+b+" &").c_str());
break;
case NotifyBackend::BELL:
write(STDOUT_FILENO,"\a",1);
break;
case NotifyBackend::NONE:
break;
}
}
// ── Network ───────────────────────────────────────────────────────────────────
static int g_fd=-1;
static std::atomic<bool> g_conn{false};
static std::string g_rbuf;
static std::mutex g_inMu;
static std::deque<std::string> g_inLines;
static std::thread g_netTh;
static std::atomic<bool> g_netRun{false};
static bool netConn(const std::string& host,int port){
int fd=socket(AF_INET,SOCK_STREAM,0);if(fd<0)return false;
struct hostent* he=gethostbyname(host.c_str());
if(!he){close(fd);return false;}
sockaddr_in a{};a.sin_family=AF_INET;a.sin_port=htons((uint16_t)port);
memcpy(&a.sin_addr,he->h_addr_list[0],he->h_length);
fcntl(fd,F_SETFL,O_NONBLOCK);
connect(fd,(sockaddr*)&a,sizeof(a));
fd_set ws;FD_ZERO(&ws);FD_SET(fd,&ws);
struct timeval tv{5,0};
if(select(fd+1,nullptr,&ws,nullptr,&tv)<=0){close(fd);return false;}
int err=0;socklen_t len=sizeof(err);
getsockopt(fd,SOL_SOCKET,SO_ERROR,&err,&len);
if(err){close(fd);return false;}
int fl=fcntl(fd,F_GETFL,0);fcntl(fd,F_SETFL,fl&~O_NONBLOCK);
g_fd=fd;g_conn=true;return true;
}
static void netSend(const std::string& l){
if(!g_conn||g_fd<0)return;
std::string m=l+"\n";send(g_fd,m.data(),m.size(),MSG_NOSIGNAL);
}
static void netThread(){
char buf[8192];
while(g_netRun&&g_conn){
fd_set rs;FD_ZERO(&rs);FD_SET(g_fd,&rs);
struct timeval tv{1,0};
if(select(g_fd+1,&rs,nullptr,nullptr,&tv)<=0)continue;
ssize_t n=recv(g_fd,buf,sizeof(buf)-1,0);
if(n<=0){g_conn=false;break;}
buf[n]='\0';g_rbuf+=std::string(buf,n);
size_t pos;
while((pos=g_rbuf.find('\n'))!=std::string::npos){
std::string ln=g_rbuf.substr(0,pos);g_rbuf.erase(0,pos+1);
if(!ln.empty()&&ln.back()=='\r')ln.pop_back();
if(ln.empty())continue;
std::lock_guard<std::mutex>lk(g_inMu);g_inLines.push_back(ln);
}
}
g_conn=false;
}
static void netDisc(){
g_netRun=false;g_conn=false;
if(g_netTh.joinable())g_netTh.join();
if(g_fd>=0){close(g_fd);g_fd=-1;}
}
// ── Data ──────────────────────────────────────────────────────────────────────
enum class MS{NONE,SENT,DELIV,READ};
enum class MT{TEXT,CMD,FILE_,LINK};
struct Msg{
std::string author,text,ts,id;
MT type=MT::TEXT;MS status=MS::NONE;
std::string fp,fext2,replyTo,replyAuth;
int uploadPct=-1; // -1=done, 0-99=uploading
};
struct Chat{
std::string name,filename;
std::vector<Msg> msgs;
bool isNet=false;
int unread=0;
bool histLoaded=false;
};
// ── Persistence ───────────────────────────────────────────────────────────────
static std::string ts(){
std::time_t t=std::time(nullptr);char b[16];
std::strftime(b,sizeof(b),"%H:%M",std::localtime(&t));return b;
}
static std::string cfp(const std::string& n){return DATA_DIR+"/"+n+".txt";}
static void mkdirs(){
std::filesystem::create_directories(DATA_DIR);
std::filesystem::create_directories(DL_DIR);
}
static std::string enl(const std::string& s){
std::string r;for(char c:s){if(c=='\n')r+="\\n";else r+=c;}return r;
}
static std::string unl(const std::string& s){
std::string r;size_t i=0;
while(i<s.size()){if(s[i]=='\\'&&i+1<s.size()&&s[i+1]=='n'){r+='\n';i+=2;}else r+=s[i++];}
return r;
}
static void appendMsg(const std::string& path,const Msg& m){
std::ofstream f(path,std::ios::app);if(!f.is_open())return;
f<<m.author<<'\t'<<m.ts<<'\t'<<(int)m.type<<'\t'
<<enl(m.fp)<<'\t'<<enl(m.replyAuth)<<'\t'
<<enl(m.replyTo)<<'\t'<<(int)m.status<<'\t'
<<enl(m.id)<<'\t'<<enl(m.text)<<'\n';
}
static std::vector<Msg> loadMsgs(const std::string& path){
std::vector<Msg>ms;
std::ifstream f(path);if(!f.is_open())return ms;
std::string line;
while(std::getline(f,line)){
if(line.empty())continue;
std::istringstream ss(line);
std::string au,tss,ty,fp,ra,rt,st,id,tx;
if(!std::getline(ss,au,'\t'))continue;
if(!std::getline(ss,tss,'\t'))continue;
if(!std::getline(ss,ty,'\t')){Msg m;m.author=au;m.ts=tss;m.text=unl(ty);ms.push_back(m);continue;}
std::getline(ss,fp,'\t');std::getline(ss,ra,'\t');std::getline(ss,rt,'\t');
std::getline(ss,st,'\t');std::getline(ss,id,'\t');std::getline(ss,tx);
Msg m;m.author=au;m.ts=tss;
m.type=(MT)std::stoi(ty.empty()?"0":ty);
m.fp=unl(fp);m.replyAuth=unl(ra);m.replyTo=unl(rt);
m.status=(MS)std::stoi(st.empty()?"0":st);
m.id=unl(id);m.text=unl(tx);m.fext2=fext(m.fp);
ms.push_back(m);
}
return ms;
}
static void rewriteMsgs(const std::string& path,const std::vector<Msg>& ms){
std::ofstream f(path,std::ios::trunc);if(!f.is_open())return;
for(const auto&m:ms)
f<<m.author<<'\t'<<m.ts<<'\t'<<(int)m.type<<'\t'
<<enl(m.fp)<<'\t'<<enl(m.replyAuth)<<'\t'
<<enl(m.replyTo)<<'\t'<<(int)m.status<<'\t'
<<enl(m.id)<<'\t'<<enl(m.text)<<'\n';
}
// ── ASCII art font ────────────────────────────────────────────────────────────
static const std::map<char,std::vector<std::string>> AFONT={
{'A',{" /\\ "," / \\ ","/----\\","\\ /","\\ / "}},
{'B',{"|-----","| \\","|-----/","| \\","|-----/"}},
{'C',{" /----","/ ","| ","\\ "," \\----"}},
{'D',{"|----\\","| \\","| |","| /","|----/"}},
{'E',{"|------","| ","|---- ","| ","|------"}},
{'H',{"| |","| |","|----| ","| |","| |"}},
{'I',{"------"," || "," || "," || ","------"}},
{'L',{"| ","| ","| ","| ","|-----"}},
{'M',{"|\\ /|","| \\ / |","| V |","| |","| |"}},
{'N',{"|\\ |","| \\ |","| \\ |","| \\|","| |"}},
{'O',{" /---\\ ","/ \\","| |","\\ /"," \\---/ "}},
{'R',{"|----\\ ","| / ","|---/ ","| \\ ","| \\ "}},
{'S',{" /----","/ "," \\---\\ "," \\"," \\----/"}},
{'T',{"------"," || "," || "," || "," || "}},
{'U',{"| |","| |","| |","\\ /"," \\---/ "}},
{'0',{" /---\\ ","/ / \\","| / |","|/ |"," \\---/ "}},
{'1',{" /| "," / | "," | "," | "," | "}},
{'2',{" /---\\ "," /"," /-- "," / ","/------"}},
{'3',{" /---\\ "," /"," ---/ "," \\"," \\---/ "}},
{' ',{" "," "," "," "," "}},
{'!',{"| ","| ","| "," ",". "}},
{'?',{" /--\\ "," |"," --/ "," "," . "}},
{'-',{" "," ","----"," "," "}},
};
static std::string translit(const std::string& s){
static const std::map<std::string,std::string>CYR={
{"А","A"},{"Б","B"},{"В","V"},{"Г","G"},{"Д","D"},{"Е","E"},{"Ж","ZH"},
{"З","Z"},{"И","I"},{"К","K"},{"Л","L"},{"М","M"},{"Н","N"},{"О","O"},
{"П","P"},{"Р","R"},{"С","S"},{"Т","T"},{"У","U"},{"Ф","F"},{"Х","KH"},
{"Ц","TS"},{"Ч","CH"},{"Ш","SH"},{"Щ","SCH"},{"Ъ",""},{"Ы","Y"},
{"Ь",""},{"Э","E"},{"Ю","YU"},{"Я","YA"},
{"а","A"},{"б","B"},{"в","V"},{"г","G"},{"д","D"},{"е","E"},{"ж","ZH"},
{"з","Z"},{"и","I"},{"к","K"},{"л","L"},{"м","M"},{"н","N"},{"о","O"},
{"п","P"},{"р","R"},{"с","S"},{"т","T"},{"у","U"},{"ф","F"},{"х","KH"},
{"ц","TS"},{"ч","CH"},{"ш","SH"},{"щ","SCH"},{"ъ",""},{"ы","Y"},
{"ь",""},{"э","E"},{"ю","YU"},{"я","YA"},
};
std::string r;size_t i=0;
while(i<s.size()){
unsigned char c=(unsigned char)s[i];
size_t cl=(c>=0xF0)?4:(c>=0xE0)?3:(c>=0xC0)?2:1;
if(i+cl>s.size()){r+=s[i];++i;continue;}
std::string cp=s.substr(i,cl);
auto it=CYR.find(cp);r+=(it!=CYR.end())?it->second:cp;i+=cl;
}
return r;
}
static std::vector<std::string> ascii_art(const std::string& text){
std::string input=translit(text);
const int ROWS=5,GAP=2;
std::vector<std::string>rows(ROWS,"");
for(size_t ci=0;ci<input.size();++ci){
char c=toupper((unsigned char)input[ci]);
auto it=AFONT.find(c);if(it==AFONT.end())it=AFONT.find(' ');if(it==AFONT.end())continue;
const auto&g=it->second;size_t gw=0;
for(const auto&r:g)gw=std::max(gw,r.size());
for(int r=0;r<ROWS;++r){
std::string ln=(r<(int)g.size())?g[r]:"";
while(ln.size()<gw)ln+=' ';rows[r]+=ln;
if(ci+1<input.size())rows[r]+=std::string(GAP,' ');
}
}
return rows;
}
// ── Command parser ────────────────────────────────────────────────────────────
struct CP{std::string n,v;};
struct Cmd{std::string n;std::vector<CP>p;bool ok=false;};
static Cmd parseCmd(const std::string& in){
Cmd c;if(in.empty()||in[0]!='/')return c;
// Normalize aliases
std::string s=in;
// /sf → /sendfile, /s → /select
if(s.substr(0,3)=="/sf"&&(s.size()==3||s[3]=='('))
s="/sendfile"+s.substr(3);
else if(s.substr(0,2)=="/s"&&(s.size()==2||s[2]=='('))
s="/select"+s.substr(2);
size_t po=s.find('(');
if(po==std::string::npos){c.n=s.substr(1);c.ok=true;return c;}
c.n=s.substr(1,po-1);if(c.n.empty())return c;
size_t pc=s.rfind(')');if(pc==std::string::npos||pc<po)return c;
std::string ps=s.substr(po+1,pc-po-1);
std::istringstream ss(ps);std::string tok;
while(ss>>tok){
// Handle positional args (no colon) — treat as value for first param
size_t col=tok.find(':');
if(col==std::string::npos){c.p.push_back({"_",tok});}
else{c.p.push_back({tok.substr(0,col),tok.substr(col+1)});}
}
c.ok=true;return c;
}
static std::string gp(const Cmd& c,const std::string& n,const std::string& d=""){
for(const auto&p:c.p)if(p.n==n)return p.v;
return d;
}
// ── Panel helper ──────────────────────────────────────────────────────────────
static void drawPanel(int top,int left,int pw,const std::string& title,
const std::vector<std::string>& items,int sel){
int inner=pw-2;
int dt=inner-dw(title)-2;
int dl=dt/2,dr=dt-dl;if(dl<0)dl=0;if(dr<0)dr=0;
pat(top,left,CB(FC),B_TL+rtw(B_H,dl)+" "+title+" "+rtw(B_H,dr)+B_TR);
int r=top+1;
for(int i=0;i<(int)items.size();++i){
int iw=dw(items[i]);int pl=(inner-iw)/2,pr=inner-iw-pl;
if(pl<0)pl=0;if(pr<0)pr=0;
std::string ln=B_V+std::string(pl,' ')+items[i]+std::string(pr,' ')+B_V;
pat(r,left,i==sel?CB(FC):C(FC),ln);++r;
if(i<(int)items.size()-1){pat(r,left,C(FC),B_V+rtw(SEP,inner)+B_V);++r;}
}
pat(r,left,CB(FC),B_BL+rtw(B_H,inner)+B_BR);
}
// ── File browser ──────────────────────────────────────────────────────────────
struct FileBrowser{
std::filesystem::path cwd;
std::vector<std::filesystem::path> entries;
int cursor=0,scroll=0;
bool active=false;
void open(const std::filesystem::path& p){
cwd=p;cursor=0;scroll=0;active=true;reload();
}
void reload(){
entries.clear();
try{
for(const auto& e:std::filesystem::directory_iterator(cwd))
entries.push_back(e.path());
}catch(...){}
std::sort(entries.begin(),entries.end(),[](const auto& a,const auto& b){
bool ad=std::filesystem::is_directory(a);
bool bd=std::filesystem::is_directory(b);
if(ad!=bd)return ad>bd;
return a.filename()<b.filename();
});
}
// Returns selected file path or empty
std::string enter(){
if(cursor<0||cursor>=(int)entries.size())return "";
auto& e=entries[cursor];
if(std::filesystem::is_directory(e)){
open(e);return "";
}
return e.string();
}
void goUp(){
auto parent=cwd.parent_path();
if(parent!=cwd){open(parent);}
}
};
// ── App ───────────────────────────────────────────────────────────────────────
class App{
public:
App();~App();void run();
private:
enum class Sc{LOGIN,CHAT_LIST,CHAT_VIEW,SELECT,
SETTINGS,APPEARANCE,LAYOUT,CONNECT,
PROFILE,LOGOUT_CONFIRM,SEARCH,
CMD_HELP,FILE_BROWSER};
Sc sc=Sc::LOGIN;
std::vector<Chat>chats;
int selChat=0,listScr=0,chatScr=0;
std::string inputBuf,loginBuf,passBuf,pass2Buf,connBuf,searchBuf;
int loginStep=0; // 0=username 1=password 2=confirm(register)
bool isRegister=false;
int rows=24,cols=80;
int setsCur=0,appCur=0,layCur=0,logoutCur=0;
int selCur=0;std::set<int>selMark;std::optional<int>replyTo;
std::string statusMsg;
FileBrowser fb;
// Search results
std::vector<std::string>searchRes;
int searchCur=0;
void upd(){tsz(rows,cols);}
void initChats();
Chat*findChat(const std::string&n);
Chat&getChat(const std::string&n);
void processNet();
void updateStatus(const std::string&id,MS st);
void sendFile(const std::string&path,const std::string&peer);
void drawLogin();
void drawChatList();
void drawChatView();
void drawSelect();
void drawSettings();
void drawAppearance();
void drawLayout();
void drawConnect();
void drawProfile();
void drawLogoutConfirm();
void drawSearch();
void drawCmdHelp();
void drawFileBrowser();
void hLogin(const KE&);
void hChatList(const KE&);
void hChatView(const KE&);
void hSelect(const KE&);
void hSettings(const KE&);
void hAppearance(const KE&);
void hLayout(const KE&);
void hConnect(const KE&);
void hProfile(const KE&);
void hLogoutConfirm(const KE&);
void hSearch(const KE&);
void hCmdHelp(const KE&);
void hFileBrowser(const KE&);
void doSend();
void openChat(int i);
void dlSel();void delSel();
void tryConn();
struct RL{int col;std::string ansi,text;bool sr=false;};
std::vector<RL> buildBub(const Chat&,int w)const;
void drawInput(int row,int innerW,const std::string&buf,const std::string&hint,int col=4);
};
App::App(){
loadCfg();enRaw();hidec();buf("\x1b[?1049h");flush();
upd();mkdirs();detectNotifyBackend();
// Pre-fill server buffer from config
connBuf=g_host.empty()?"":g_host+":"+std::to_string(g_port);
loginBuf=g_user;
if(!g_user.empty()&&!g_passhash.empty()){
// Auto-connect and login
sc=Sc::CHAT_LIST;initChats();
if(!g_host.empty()&&netConn(g_host,g_port)){
g_netRun=true;g_netTh=std::thread(netThread);
netSend(jb({{"type","login"},{"username",g_user},{"password",g_passhash}}));
}
}
}
App::~App(){
netDisc();buf("\x1b[?1049l");showc();buf(RESET);flush();disRaw();
}
void App::initChats(){
chats.clear();
{Chat c;c.name="Saved Messages";c.filename=cfp("saved");
c.msgs=loadMsgs(c.filename);c.histLoaded=true;chats.push_back(std::move(c));}
}
Chat*App::findChat(const std::string&n){
for(auto&c:chats)if(c.name==n)return&c;return nullptr;
}
Chat&App::getChat(const std::string&n){
auto*c=findChat(n);if(c)return*c;
Chat nc;nc.name=n;nc.isNet=true;nc.filename=cfp("net_"+n);
chats.push_back(std::move(nc));
return chats.back();
}
// ── Process incoming ──────────────────────────────────────────────────────────
void App::processNet(){
std::deque<std::string>lines;
{std::lock_guard<std::mutex>lk(g_inMu);lines.swap(g_inLines);}
for(const auto&line:lines){
std::string type=jget(line,"type");
if(type=="msg"){
std::string from=jget(line,"from"),text=jget(line,"text");
std::string id=jget(line,"id"),tss=jget(line,"ts"),to=jget(line,"to");
std::string rTo=jget(line,"replyTo"),rAuth=jget(line,"replyAuth");
if(from.empty())continue;
std::string chatName=(to=="@world")?"@world":(from==g_user)?to:from;
Chat&chat=getChat(chatName);
if(!id.empty())for(const auto&m:chat.msgs)if(m.id==id)goto skip_msg;
{
Msg m;m.author=from;m.text=text;m.ts=tss;m.id=id;m.type=MT::TEXT;
m.replyTo=rTo;m.replyAuth=rAuth;
chat.msgs.push_back(m);
if(chat.histLoaded)appendMsg(chat.filename,m);
bool view=(sc==Sc::CHAT_VIEW&&selChat<(int)chats.size()&&chats[selChat].name==chatName);
if(!view){chat.unread++;sendNotify(from,text);}
else if(view)netSend(jb({{"type","read"},{"id",id},{"from",from}}));
}
skip_msg:;
}
else if(type=="ack"){
updateStatus(jget(line,"id"),
jget(line,"status")=="read"?MS::READ:
jget(line,"status")=="delivered"?MS::DELIV:MS::SENT);
}
else if(type=="login_ok"){
statusMsg="";
saveCfg();
initChats();
sc=Sc::CHAT_LIST;
Chat*wc=findChat("@world");
if(!wc){
Chat w;w.name="@world";w.filename=cfp("world");w.isNet=true;
chats.push_back(std::move(w));wc=findChat("@world");
}
if(wc&&!wc->histLoaded)
netSend(jb({{"type","get_history"},{"peer","@world"}}));
}
else if(type=="register_ok"){
statusMsg="Registered! Logging in...";
netSend(jb({{"type","login"},{"username",g_user},{"password",g_passhash}}));
}
else if(type=="login_err"||type=="register_err"){
statusMsg=jget(line,"reason");
sc=Sc::LOGIN;
}
else if(type=="history_end"){
std::string peer=jget(line,"peer");
Chat*c=findChat(peer);
if(c){
c->histLoaded=true;
rewriteMsgs(c->filename,c->msgs);
}
}
else if(type=="search_result"){
searchRes.clear();
std::string arr=line;
size_t start=arr.find('[');size_t end=arr.rfind(']');
if(start!=std::string::npos&&end!=std::string::npos){
std::string inner=arr.substr(start+1,end-start-1);size_t p=0;
while(p<inner.size()){
while(p<inner.size()&&inner[p]!='"')++p;if(p>=inner.size())break;++p;
std::string u;while(p<inner.size()&&inner[p]!='"')u+=inner[p++];++p;
if(!u.empty())searchRes.push_back(u);
}
}
}
else if(type=="file_start"){
std::string from=jget(line,"from"),id=jget(line,"id");
std::string fn=jget(line,"filename"),tss=jget(line,"ts"),to=jget(line,"to");
if(from.empty()||id.empty())continue;
if(tss.empty()){std::time_t t=std::time(nullptr);char b[16];std::strftime(b,sizeof(b),"%H:%M",std::localtime(&t));tss=b;}
std::string chatName=(to=="@world")?"@world":from;
Chat&chat=getChat(chatName);
for(const auto&m:chat.msgs)if(m.id==id)goto skip_file_start;
{
Msg m;m.author=from;m.type=MT::FILE_;m.id=id;m.text=fn;m.ts=tss;
m.fp=DL_DIR+"/"+id+"_"+fn;m.fext2=fext(fn);m.uploadPct=0;
chat.msgs.push_back(m);
bool view=(sc==Sc::CHAT_VIEW&&selChat<(int)chats.size()&&chats[selChat].name==chatName);
if(!view){chat.unread++;sendNotify(from,"[file] "+fn);}
}
skip_file_start:;
}
else if(type=="file_chunk"){
std::string id=jget(line,"id");
for(auto&chat:chats)for(auto&m:chat.msgs)
if(m.id==id&&m.type==MT::FILE_){
m.uploadPct=std::min(99,m.uploadPct+5);
break;
}
}
else if(type=="file_end"){
std::string id=jget(line,"id");
for(auto&chat:chats){
for(auto&m:chat.msgs){
if(m.id==id&&m.type==MT::FILE_){
m.uploadPct=-1;
appendMsg(chat.filename,m);
break;
}
}
}
}
else if(type=="file_data"){
std::string id=jget(line,"id"),data=jget(line,"data"),fn=jget(line,"filename");
if(id.empty()||data.empty())continue;
std::filesystem::create_directories(DL_DIR);
std::string dest=DL_DIR+"/"+fn;
std::vector<uint8_t>decoded;
static const std::string B64c="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
std::vector<int>T(256,-1);for(int i=0;i<64;++i)T[(uint8_t)B64c[i]]=i;
int val=0,valb=-8;
for(char c:data){if(T[(uint8_t)c]==-1)break;val=(val<<6)+T[(uint8_t)c];valb+=6;if(valb>=0){decoded.push_back((val>>valb)&0xFF);valb-=8;}}
std::ofstream f(dest,std::ios::binary|std::ios::trunc);
if(f.is_open())f.write((char*)decoded.data(),decoded.size());
statusMsg="Saved: "+dest;
}
else if(type=="file_progress"){
std::string id=jget(line,"id"),pct=jget(line,"percent");
int p=pct.empty()?0:std::stoi(pct);
for(auto&chat:chats)for(auto&m:chat.msgs)
if(m.id==id&&m.type==MT::FILE_){
m.uploadPct=(p>=100)?-1:p;
if(p>=100){m.status=MS::DELIV;rewriteMsgs(chat.filename,chat.msgs);}
break;
}
}
else if(type=="online"){
std::string u=jget(line,"username"),on=jget(line,"online");
if(on=="true"&&u!=g_user)getChat(u);
}
}
}
void App::updateStatus(const std::string&id,MS st){
for(auto&chat:chats)for(auto&m:chat.msgs)
if(m.id==id){if((int)st>(int)m.status){m.status=st;rewriteMsgs(chat.filename,chat.msgs);}return;}
}
// ── File upload ───────────────────────────────────────────────────────────────
void App::sendFile(const std::string&path,const std::string&peer){
if(!g_conn){statusMsg="Not connected";return;}
if(!std::filesystem::exists(path)){statusMsg="File not found";return;}
auto sz=std::filesystem::file_size(path);
char idbuf[64];snprintf(idbuf,64,"%lx-%d",(unsigned long)std::time(nullptr),rand());
std::string id=idbuf;
std::string tss=ts();
netSend(jb({{"type","file_start"},{"to",peer},{"id",id},
{"filename",fname(path)},{"size",std::to_string(sz)},{"ts",tss}}));
Msg m;m.author=g_user.empty()?"me":g_user;m.type=MT::FILE_;
m.fp=path;m.fext2=fext(path);m.text=fname(path);
m.ts=tss;m.id=id;m.uploadPct=0;m.status=MS::SENT;
Chat&chat=getChat(peer);
chat.msgs.push_back(m);
if(chat.histLoaded)appendMsg(chat.filename,m);
std::thread([path,peer,id,sz](){
std::ifstream f(path,std::ios::binary);if(!f.is_open())return;
const size_t CHUNK=4096;std::vector<uint8_t>buf(CHUNK);int seq=0;
while(f){
f.read((char*)buf.data(),CHUNK);size_t n=f.gcount();if(n==0)break;
buf.resize(n);
netSend(jb({{"type","file_chunk"},{"id",id},{"seq",std::to_string(seq++)},{"data",b64enc(buf)}}));
buf.resize(CHUNK);
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
netSend(jb({{"type","file_end"},{"id",id}}));
(void)sz;(void)peer;
}).detach();
}
// ── Draw helpers ──────────────────────────────────────────────────────────────
void App::drawInput(int row,int innerW,const std::string&ibuf,const std::string&hint,int col){
if(ibuf.empty()){pat(row,col,CDIM(),tw(hint,innerW));}
else{
std::vector<std::string>cps;size_t k=0;
while(k<ibuf.size()){
unsigned char c=(unsigned char)ibuf[k];
size_t cl=(c>=0xF0)?4:(c>=0xE0)?3:(c>=0xC0)?2:1;
if(k+cl>ibuf.size())cl=1;cps.push_back(ibuf.substr(k,cl));k+=cl;
}
int take=(int)cps.size();
while(take>0){int w=0;
for(int j=(int)cps.size()-take;j<(int)cps.size();++j)w+=dw(cps[j]);
if(w<=innerW)break;--take;}
std::string vis;for(int j=(int)cps.size()-take;j<(int)cps.size();++j)vis+=cps[j];
pat(row,col,C(FW),vis);
}
}
// ── Login ─────────────────────────────────────────────────────────────────────
// loginStep: 0=username 1=password 2=confirm_pw(register) 3=server
// Fields shown depend on isRegister flag.
// Layout (login): Username / Password / Server
// Layout (register): Username / Password / Confirm / Server
void App::drawLogin(){
upd();cls();
std::string title="TERMINAL MESSENGER";
pat(2,(cols-dw(title))/2+1,CB(FC),title);
int bw=std::min(44,cols-8);
int bl=(cols-bw)/2+1;
int startRow=rows/2-4;
// Determine fields
// login: 0=user 1=pass 2=server
// register: 0=user 1=pass 2=confirm 3=server
struct Field{ std::string label; std::string* buf; bool mask; };
std::vector<Field> fields;
fields.push_back({"Username:", &loginBuf, false});
fields.push_back({"Password:", &passBuf, true});
if(isRegister) fields.push_back({"Confirm password:", &pass2Buf, true});
fields.push_back({"Server (host:port):", &connBuf, false});
for(int i=0;i<(int)fields.size();++i){
int row=startRow+i*3;
bool active=(i==loginStep);
pat(row,bl,active?CB(FC):CDIM(),fields[i].label);
// Box
pat(row+1,bl,active?CB(FC):CDIM(),B_TL+rtw(B_H,bw-2)+B_TR);
pat(row+1,bl,active?CB(FC):CDIM(),B_V);
pat(row+1,bl+bw-1,active?CB(FC):CDIM(),B_V);
pat(row+2,bl,active?CB(FC):CDIM(),B_BL+rtw(B_H,bw-2)+B_BR);
// Fill
pat(row+1,bl+2,CDIM(),rtw(INPUT_FILL,bw-4));
// Value
std::string disp=fields[i].mask?std::string(fields[i].buf->size(),'*'):*fields[i].buf;
pat(row+1,bl+2,active?CB(FW):CDIM(),tw(disp,bw-4));
}
// Mode toggle hint
int modeRow=startRow+(int)fields.size()*3;
std::string modeStr=isRegister?"Mode: REGISTER (Esc to switch to Login)":
"Mode: LOGIN (Esc to switch to Register)";
pat(modeRow,bl,CDIM(),tw(modeStr,bw));
if(!statusMsg.empty())
pat(modeRow+2,(cols-dw(statusMsg))/2+1,std::string(BOLD)+FR,statusMsg);
pat(rows,bl,CDIM()," Enter:next/confirm Backspace:delete Esc:toggle mode");
flush();
}
void App::hLogin(const KE&ev){
// Determine max step
int maxStep=isRegister?3:2; // last step = server field
// Current buffer
std::string* cur=nullptr;
if(loginStep==0)cur=&loginBuf;
else if(loginStep==1)cur=&passBuf;
else if(loginStep==2&&isRegister)cur=&pass2Buf;
else cur=&connBuf;
if(ev.key==K::ENTER){
// Validate current step
if(loginStep==0){
if(loginBuf.size()<3){statusMsg="Min 3 chars";return;}