why2-chat 2.2.3

Lightweight, fast and secure chat application powered by WHY2 encryption.
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
/*
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::
{
    Frame,
    backend::FromCrossterm,
    buffer::{ Cell, CellDiffOption },
    style::{ Color, Style },
    text::{ Line, Span },
    widgets::
    {
        Block,
        BorderType,
        Clear,
        Paragraph,
    },
    layout::
    {
        Constraint,
        Layout,
        Position,
        Rect,
    },
};

use unicode_width::UnicodeWidthStr;

use ratatui_image::{ CropOptions, FontSize, Resize, ResizeEncodeRender };

use crate::
{
    config,
    options,
    consts as chat_consts,
};

#[cfg(feature = "client_voice")]
use crate::network::voice::
{
    consts as voice_consts,
    client::options as voice_options,
};

use super::
{
    consts,
    theme,
    state::{ self, App },
    palette::
    {
        Entry,
        Values,
        PaletteMode,
    },
    tofu::
    {
        Prompt,
        Stage,
    },
    settings::
    {
        Mode,
        Row,
        Value,
        Settings,
        DeviceEntry,
    },
    login::
    {
        Login,
        Reconnect,
        Stage as LoginStage,
    },
};

//PROJECT LOGO WATERMARK
const LOGO: &str = include_str!("./assets/rexlogo");

//ENUMS
enum Panel //SIDEBAR SECTIONS, IN THE ORDER THEY ARE STACKED
{
    Online,
    Offline,
    Channels,
    Voice,
}

//PUBLIC
pub fn draw(frame: &mut Frame, app: &mut App)
{
    let area = frame.area();

    //NO INPUT BAR OR SIDEBAR BEFORE LOGIN
    let connecting = app.login.is_some();

    //PAINT THE BASE FOREGROUND FIRST
    frame.buffer_mut().set_style(area, theme::TEXT);

    //MEASURE THE INPUT FIRST
    let input_width = area.width.saturating_sub(4).max(1); //BORDERS + "> "
    let (input_lines, cursor) = app.input.render(input_width, false);
    let input_height = if connecting { 0 }
        else { (input_lines.len() as u16 + 2).clamp(consts::INPUT_MIN_HEIGHT, consts::INPUT_MAX_HEIGHT) };

    let [main_area, input_area] = Layout::vertical
    ([
        Constraint::Min(consts::INPUT_MIN_HEIGHT),
        Constraint::Length(input_height),
    ]).areas(area);

    //MESSAGES + SIDEBAR
    let (messages_area, sidebar_area) = if area.width >= consts::SIDEBAR_MIN_TERM_WIDTH && options::get_sending_messages()
    {
        let [m, s] = Layout::horizontal([Constraint::Min(0), Constraint::Length(consts::SIDEBAR_WIDTH)]).areas(main_area);
        (m, Some(s))
    } else
    {
        (main_area, None)
    };

    draw_messages(frame, app, messages_area);

    if let Some(sidebar_area) = sidebar_area { draw_sidebar(frame, app, sidebar_area); }

    if !connecting { draw_input(frame, app, input_area, input_lines, cursor); }

    //LOGO BEHIND EVERYTHING
    if !app.theme.disable_logo { draw_logo(frame, area); }

    //EVERY BOX SAYS WHAT IT COVERED
    let mut overlays: Vec<Rect> = Vec::new();

    //PALETTE OVER THE MESSAGE PANE
    if app.palette.is_visible() { overlays.push(draw_palette(frame, app, messages_area)); }

    //SETTINGS OVERLAY
    if app.settings.open
    {
        let font = app.picker.font_size();

        overlays.push(draw_settings(frame, &mut app.settings, area, font));
    }

    //CONNECT BOX
    if let Some(login) = &app.login { overlays.push(draw_login(frame, login, &app.reconnect, area)); }

    //SERVER-KEY PROMPT ON TOP
    if let Some(prompt) = &app.tofu { overlays.push(draw_tofu(frame, prompt, area)); }

    //PICTURES LAST, WITH WHATEVER A BOX HAS ON THEM PUT BACK ON TOP
    let rewritten = draw_pictures(frame, app, &overlays);

    //AND A PROFILE PICTURE ON TOP OF THE BOX THAT RESERVED THE ROWS FOR IT
    draw_avatar(frame, app, &rewritten);
}

//THE PROFILE PICTURE, INSIDE THE SETTINGS BOX
fn draw_avatar(frame: &mut Frame, app: &mut App, rewritten: &[u16])
{
    let area = app.settings.picture_area;

    if area.width == 0 || area.height == 0 { return; }

    //A BOX ABOVE IT OWNS THOSE CELLS, AND NOTHING DIFFS A PICTURE AWAY
    if app.login.is_some() || app.tofu.is_some() { return; }

    app.load_avatar(area.width);

    if let Some(ready) = app.settings.picture.as_mut() && let Some(protocol) = ready.protocol.as_mut()
    {
        protocol.resize_encode_render(&Resize::Crop(None), area, frame.buffer_mut());

        //A PANE PICTURE REWRITTEN ACROSS OUR ROWS TAKES THEM, SO THEY GO AGAIN AFTER IT
        let marks = rewritten.iter().copied().filter(|y| (area.y..area.y + area.height).contains(y)).map(|y|
        {
            //NEVER THE SAME MARK TWICE IN A ROW
            let times = match app.avatar_marks.iter().find(|(row, _)| *row == y) { Some((_, 1)) => 2, _ => 1 };

            mark(frame, area.x, y, times);

            (y, times)
        }).collect();

        app.avatar_marks = marks;
    }
}

//PRIVATE
fn draw_messages(frame: &mut Frame, app: &mut App, area: Rect)
{
    //TITLE: WHY2 ── NAME ── ADDRESS ── SOCKS5
    let mut parts = vec![String::from("WHY2")];

    if !app.server_name.is_empty() { parts.push(app.server_name.clone()); }
    if !app.address.is_empty() { parts.push(app.address.clone()); }
    if options::socks5_enabled() { parts.push(String::from("SOCKS5")); }

    let title = format!(" {} ", parts.join(" ── "));

    let mut block = Block::bordered()
        .border_type(BorderType::Rounded)
        .border_style(theme::BORDER)
        .title(Span::styled(title, theme::TITLE));

    //SCROLLED AWAY - ADVERTISE THE BACKLOG
    if app.scroll.is_some() && app.unread > 0
    {
        block = block.title_bottom(Line::from(Span::styled(format!(" ↓ {} new ", app.unread), theme::NOTICE)).right_aligned());
    }

    //TOAST ON THE SAME BORDER
    if let Some(notice) = app.notice()
    {
        block = block.title_bottom(Span::styled(format!(" {notice} "), theme::OK));
    }

    //AND WHOEVER IS WRITING
    if let Some(typing) = app.typing_line()
    {
        block = block.title_bottom(Span::styled(format!(" {typing} "), theme::DIM));
    }

    let inner = block.inner(area);
    frame.render_widget(block, area);

    if inner.width == 0 || inner.height == 0 { return; }

    //WRAP OURSELVES SO THE SCROLL OFFSET IS EXACT
    let viewport = inner.height;
    let total = app.wrapped_lines(inner.width).len() as u16;
    let max_offset = total.saturating_sub(viewport);
    let offset = app.scroll.map(|o| o.min(max_offset)).unwrap_or(max_offset);

    //REMEMBER THE PANE'S GEOMETRY FOR CLICKS
    app.pane = inner;
    app.pane_offset = offset;

    let visible = app.wrapped_lines(inner.width)
        .iter()
        .skip(offset as usize)
        .take(viewport as usize)
        .cloned()
        .collect::<Vec<Line<'static>>>();

    frame.render_widget(Paragraph::new(visible), inner);

    //PAINT THE DRAG SELECTION
    for y in inner.y..inner.y + viewport
    {
        let Some((first, last)) = app.selection_columns(offset + (y - inner.y)) else { continue };

        for x in first..=last.min(inner.width.saturating_sub(1))
        {
            if let Some(cell) = frame.buffer_mut().cell_mut((inner.x + x, y)) { cell.set_style(theme::SELECTION); }
        }
    }

    //ONLY THE PICTURES ON SCREEN ARE HELD
    app.load_visible(inner.width, offset, viewport);

    //SHOW THE BACKLOG
    draw_scrollbar(frame, area, total as usize, viewport as usize, offset as usize);
}

//PICTURES GO ON LAST, AND A BOX IS PUT BACK OVER WHATEVER ROW ONE CLAIMS
fn draw_pictures(frame: &mut Frame, app: &mut App, overlays: &[Rect]) -> Vec<u16>
{
    let inner = app.pane;

    if inner.width == 0 || inner.height == 0 { return app.picture_rows_drawn(Vec::new()); }

    let (offset, viewport) = (app.pane_offset, inner.height);

    //WHERE THE BOXES WERE ON THE LAST FRAME
    let previous = app.overlays_drawn(overlays);

    //A BOX THAT MOVED GETS ONE MORE FRAME
    if previous != overlays { app.dirty = true; }

    let mut rows = Vec::new();

    for placement in app.placements(inner.width)
    {
        let bottom = placement.row + placement.height;

        let first = placement.row.max(offset);
        let last = bottom.min(offset + viewport);

        if last <= first { continue; }

        //CROP WHICHEVER END IS FURTHER OFF SCREEN
        let clip_top = offset.saturating_sub(placement.row) > bottom.saturating_sub(offset + viewport);

        let area = Rect
        {
            x: inner.x,
            y: inner.y + (first - offset),
            width: inner.width,
            height: last - first,
        };

        let covered = overlays.iter().any(|overlay| overlay.intersects(area));

        //WHAT A BOX HAS ON THESE CELLS, BEFORE THE PICTURE CLAIMS THE WHOLE ROW
        let kept = if covered { overlay_cells(frame, area, overlays) } else { Vec::new() };

        let (mut drawn, mut encoded) = (false, false);

        if let Some(state::Entry::Image { picture: state::Picture::Ready(ready), .. }) =
            app.messages.get_mut(placement.entry) && let Some(protocol) = ready.protocol.as_mut()
        {
            let resize = Resize::Crop(Some(CropOptions { clip_top, clip_left: false }));

            protocol.resize_encode_render(&resize, area, frame.buffer_mut());

            drawn = true;
            encoded = protocol.last_encoding_result().is_some();
        }

        //A BOX THAT MOVED OR WENT LEAVES GLYPHS ONLY THE ROW'S OWN WRITE CAN RUB OUT
        if drawn && previous != overlays && previous.iter().any(|overlay| overlay.intersects(area))
        {
            replace_rows(frame, area, overlays);
        }

        //A RETRANSMITTED PICTURE SENDS EVERY ROW AGAIN
        if drawn && encoded { resend_rows(frame, app, area, overlays); }

        //WHAT EACH ROW'S FIRST CELL WILL SEND
        if drawn
        {
            for y in area.y..area.y + area.height
            {
                if overlays.iter().any(|overlay| overlay.contains((area.x, y).into())) { continue; }

                if let Some(cell) = frame.buffer_mut().cell((area.x, y)) { rows.push((y, cell.symbol().to_string())); }
            }
        }

        //THE BOX GOES BACK ON TOP OF THE ROW THE PICTURE JUST WROTE
        for (x, y, cell) in kept
        {
            if let Some(target) = frame.buffer_mut().cell_mut((x, y))
            {
                *target = cell;
                target.set_diff_option(CellDiffOption::AlwaysUpdate);
            }
        }
    }

    //THE ROWS THE TERMINAL IS SENT AGAIN
    app.picture_rows_drawn(rows)
}

//THE CELLS A BOX HAS INSIDE area, COPIED OUT
fn overlay_cells(frame: &mut Frame, area: Rect, overlays: &[Rect]) -> Vec<(u16, u16, Cell)>
{
    let mut cells = Vec::new();

    for y in area.y..area.y + area.height
    {
        for x in area.x..area.x + area.width
        {
            if !overlays.iter().any(|overlay| overlay.contains((x, y).into())) { continue; }

            if let Some(cell) = frame.buffer_mut().cell((x, y)) { cells.push((x, y, cell.clone())); }
        }
    }

    cells
}

//ONE CELL CARRIES A WHOLE ROW OF A PICTURE, AND THE DIFF WRITES IT AGAIN ONLY IF IT READS DIFFERENTLY
fn replace_rows(frame: &mut Frame, area: Rect, overlays: &[Rect])
{
    for y in area.y..area.y + area.height
    {
        //A ROW WHOSE FIRST CELL IS A BOX'S IS NOT THE PICTURE'S
        if overlays.iter().any(|overlay| overlay.contains((area.x, y).into())) { continue; }

        let Some(cell) = frame.buffer_mut().cell_mut((area.x, y)) else { continue };

        //SAVING THE CURSOR TWICE IS THE SAME AS SAVING IT ONCE - THE CELL'S WIDTH STAYS THE ONE IT IS FORCED TO
        let symbol = format!("\x1b[s{}", cell.symbol());

        cell.set_symbol(&symbol);
    }
}

//MAKE EACH ROW'S FIRST CELL DIFFER FROM THE LAST FRAME'S
fn resend_rows(frame: &mut Frame, app: &App, area: Rect, overlays: &[Rect])
{
    for y in area.y..area.y + area.height
    {
        if overlays.iter().any(|overlay| overlay.contains((area.x, y).into())) { continue; }

        let Some(cell) = frame.buffer_mut().cell_mut((area.x, y)) else { continue };

        while app.picture_row_sent(y, cell.symbol())
        {
            let symbol = format!("\x1b[s{}", cell.symbol());

            cell.set_symbol(&symbol);
        }
    }
}

//MAKE ONE PICTURE ROW'S FIRST CELL READ DIFFERENTLY
fn mark(frame: &mut Frame, x: u16, y: u16, times: usize)
{
    let Some(cell) = frame.buffer_mut().cell_mut((x, y)) else { return };

    let symbol = format!("{}{}", "\x1b[s".repeat(times), cell.symbol());

    cell.set_symbol(&symbol);
}

//FIRST VISIBLE ROW OF A SCROLLING LIST
fn window(offset: usize, selected: usize, total: usize, visible: usize) -> usize
{
    let max = total.saturating_sub(visible);

    //A SHORT LIST KEEPS WHAT IT CAN
    let gap = consts::SCROLL_GAP.min(visible.saturating_sub(1) / 2);

    let mut first = offset.min(max);

    if selected < first + gap { first = selected.saturating_sub(gap); }

    if selected + gap >= first + visible { first = (selected + gap + 1).saturating_sub(visible); }

    first.min(max)
}

//SCROLLBAR DOWN A BOX'S RIGHT BORDER
fn draw_scrollbar(frame: &mut Frame, area: Rect, total: usize, visible: usize, first: usize)
{
    if total <= visible || visible == 0 || area.width == 0 || area.height < 3 { return; }

    let track = area.height as usize - 2; //THE CORNERS STAY CORNERS

    if track == 0 { return; }

    let max_first = total - visible;

    //ROUND SO THE THUMB IS NEVER EMPTY
    let thumb = ((visible * track + total / 2) / total).clamp(1, track);
    let room = track - thumb;
    let start = if max_first == 0 { 0 } else { (first.min(max_first) * room + max_first / 2) / max_first };

    let x = area.x + area.width - 1;
    let buffer = frame.buffer_mut();

    for row in 0..track
    {
        let Some(cell) = buffer.cell_mut((x, area.y + 1 + row as u16)) else { continue; };

        if row >= start && row < start + thumb
        {
            cell.set_symbol("\u{2588}");
            cell.set_style(theme::ACCENT);
        } else
        {
            cell.set_symbol("\u{2502}");
            cell.set_style(theme::BORDER);
        }
    }
}

//DRAW THE LOGO ON FREE CELLS ONLY
fn draw_logo(frame: &mut Frame, area: Rect)
{
    let rows = LOGO.lines().collect::<Vec<&str>>();
    let height = rows.len() as u16;
    let width = rows.iter().map(|row| row.chars().count()).max().unwrap_or(0) as u16;

    if width == 0 || area.width < width || area.height < height { return; } //TOO CRAMPED TO READ - LEAVE IT OUT

    let x = area.x + (area.width - width) / 2;
    let y = area.y + (area.height - height) / 2;
    let buffer = frame.buffer_mut();

    for (row_index, row) in rows.iter().enumerate()
    {
        for (column, symbol) in row.chars().enumerate()
        {
            if symbol == ' ' { continue; }

            let Some(cell) = buffer.cell_mut((x + column as u16, y + row_index as u16)) else { continue; };

            //A PAINTED BACKGROUND IS A CLAIMED CELL
            if cell.symbol().trim().is_empty() && cell.bg == Color::Reset //FREE CELL - THE LOGO OWNS IT OUTRIGHT
            {
                cell.set_char(symbol);
                cell.set_style(theme::LOGO);
            } else if cell.bg == Color::Reset //TAKEN, BUT NOTHING IS PAINTED BEHIND IT YET
            {
                cell.set_style(theme::LOGO_UNDER);
            }
        }
    }
}

fn draw_sidebar(frame: &mut Frame, app: &App, area: Rect)
{
    let limit = area.height.saturating_sub(3).max(3);

    //max_clients BOUNDS THE ONLINE LIST, SO THE OFFLINE ONE TAKES THE REST
    let (mut constraints, mut panels) = match app.offline.is_empty()
    {
        true => (vec![Constraint::Min(3)], vec![Panel::Online]),

        false => (vec![Constraint::Length((app.online.len() as u16 + 2).clamp(3, limit)), Constraint::Min(3)],
            vec![Panel::Online, Panel::Offline]),
    };

    if area.height >= consts::CHANNELS_MIN_HEIGHT && !app.channels.is_empty()
    {
        constraints.push(Constraint::Length((app.channels.len() as u16 + 2).clamp(3, limit)));
        panels.push(Panel::Channels);
    }

    if voice_visible(app)
    {
        constraints.push(Constraint::Length((app.voice.len() as u16 + 2).clamp(3, limit)));
        panels.push(Panel::Voice);
    }

    let areas = Layout::vertical(constraints).split(area);

    for (area, panel) in areas.iter().zip(panels)
    {
        match panel
        {
            Panel::Online => draw_online(frame, app, *area),
            Panel::Offline => draw_offline(frame, app, *area),
            Panel::Channels => draw_channels(frame, app, *area),
            Panel::Voice => draw_voice(frame, app, *area),
        }
    }
}

fn draw_online(frame: &mut Frame, app: &App, area: Rect)
{
    let block = Block::bordered()
        .border_type(BorderType::Rounded)
        .border_style(theme::BORDER)
        .title(Span::styled(" Online ", theme::TITLE))
        .title_top(Line::from(Span::styled(format!(" {} ", app.online.len()), theme::TITLE)).right_aligned());

    let inner = block.inner(area);
    frame.render_widget(block, area);

    //ID COLUMN, RIGHT-ALIGNED
    let width = app.online.iter().map(|user| user.id.to_string().len()).max().unwrap_or(1);
    let room = inner.width as usize;

    let me = app.username.clone();
    let lines = app.online.iter().map(|user|
    {
        //OUR OWN ROW STAYS MARKED; EVERYBODY ELSE GETS THEIR COLOR
        let style = match user.username == me
        {
            true => theme::ACCENT,
            false => app.theme.style(user.username_color),
        };

        //WHAT THEY ARE ON, IF THEY SHARE IT
        let device = app.devices.get(&user.username).map(|device| super::device_label(device)).unwrap_or_default();
        let reserved = if device.is_empty() { 0 } else { device.width() + 2 };

        //THE NAME GIVES WAY TO THE DEVICE
        let name = truncate(&user.username, room.saturating_sub(width + 2 + reserved));

        let mut spans = vec!
        [
            Span::styled(format!("{id:>width$}  ", id = user.id), theme::DIM),
            Span::styled(name.clone(), style),
        ];

        //DEVICE ON THE RIGHT EDGE
        if !device.is_empty()
        {
            let pad = room.saturating_sub(width + 3 + name.width() + device.width());

            spans.push(Span::styled(format!("{:pad$}{device} ", ""), theme::DIM));
        }

        Line::from(spans)
    }).collect::<Vec<Line>>();

    frame.render_widget(Paragraph::new(lines), inner);
}

fn draw_offline(frame: &mut Frame, app: &App, area: Rect)
{
    let block = Block::bordered()
        .border_type(BorderType::Rounded)
        .border_style(theme::BORDER)
        .title(Span::styled(" Offline ", theme::TITLE))
        .title_top(Line::from(Span::styled(format!(" {} ", app.offline.len()), theme::TITLE)).right_aligned());

    let inner = block.inner(area);
    frame.render_widget(block, area);

    let room = inner.width as usize;

    let lines = app.offline.iter().map(|(username, color)|
    {
        let name = truncate(username, room);

        //THEIR OWN COLOR, ELSE DIM
        Line::from(match color
        {
            Some(_) => Span::styled(name, app.theme.style(*color)),
            None => Span::styled(name, theme::DIM),
        })
    }).collect::<Vec<Line>>();

    frame.render_widget(Paragraph::new(lines), inner);
}

fn draw_channels(frame: &mut Frame, app: &App, area: Rect)
{
    let block = Block::bordered()
        .border_type(BorderType::Rounded)
        .border_style(theme::BORDER)
        .title(Span::styled(" Channels ", theme::TITLE))
        .title_top(Line::from(Span::styled(format!(" {} ", app.channels.len()), theme::TITLE)).right_aligned());

    let inner = block.inner(area);
    frame.render_widget(block, area);

    let current = options::get_channel();

    let lines = app.channels.iter().map(|name|
    {
        let here = current == *name;

        Line::from(vec!
        [
            Span::styled(if here { "▸ " } else { "  " }, theme::ACCENT),
            Span::styled("#", theme::DIM),
            Span::styled(name.clone(), if here { theme::ACCENT } else { Style::default() }),
        ])
    }).collect::<Vec<Line>>();

    frame.render_widget(Paragraph::new(lines), inner);
}

fn draw_voice(frame: &mut Frame, app: &App, area: Rect)
{
    let block = Block::bordered()
        .border_type(BorderType::Rounded)
        .border_style(theme::BORDER)
        .title(Span::styled(" Voice ", theme::TITLE))
        .title_top(Line::from(Span::styled(format!(" {} ", app.voice.len()), theme::TITLE)).right_aligned());

    let inner = block.inner(area);
    frame.render_widget(block, area);

    let lines = app.voice.iter().map(|user|
    {
        //MUTE ONLY SHOWS WHILE WE LISTEN
        #[cfg(feature = "client_voice")]
        let muted = app.voice_enabled && options::is_muted(if user.is_local { None } else { Some(user.id) });

        #[cfg(not(feature = "client_voice"))]
        let muted = false;

        let marker = if muted { "✕" } else if user.is_speaking { "●" } else { "○" };
        let style = if muted
        {
            theme::ERROR
        } else if user.is_speaking
        {
            theme::SPEAKING
        } else
        {
            theme::DIM
        };

        //NO PING FOR SOMEBODY WE DO NOT RECEIVE
        let latency = match user.latency
        {
            Some(latency) => format!(" {latency}ms"),
            None => String::new(),
        };

        Line::from(vec!
        [
            Span::styled(format!("{marker} {}", user.username), style),
            Span::styled(latency, theme::DIM),
        ])
    }).collect::<Vec<Line>>();

    frame.render_widget(Paragraph::new(lines), inner);
}

fn draw_input(frame: &mut Frame, app: &App, area: Rect, lines: Vec<Line<'static>>, cursor: (u16, u16))
{
    //STATUS LINE - THE INPUT BLOCK'S BOTTOM BORDER
    let channel = match options::get_channel()
    {
        c if c.is_empty() => String::new(),
        c => format!(" #{c} "),
    };

    let left = match (channel.trim(), app.username.as_str())
    {
        ("", "") => String::new(),
        (c, "") => format!(" {c} "),
        ("", u) => format!(" {u} "),
        (c, u) => format!(" {c} │ {u} "),
    };

    let block = Block::bordered()
        .border_type(BorderType::Rounded)
        .border_style(theme::BORDER_ACTIVE)
        .title_bottom(Line::from(Span::styled(left, theme::DIM)))
        .title_bottom(Line::from(Span::styled(right_status(app), theme::DIM)).right_aligned());

    let inner = block.inner(area);
    frame.render_widget(block, area);

    if inner.width == 0 || inner.height == 0 { return; }

    //"> " GUTTER
    let [gutter, text_area] = Layout::horizontal([Constraint::Length(2), Constraint::Min(0)]).areas(inner);
    frame.render_widget(Paragraph::new(Span::styled("> ", theme::ACCENT)), gutter);

    //SCROLL THE INPUT TO THE CURSOR
    let offset = cursor.1.saturating_sub(text_area.height.saturating_sub(1));
    frame.render_widget(Paragraph::new(lines).scroll((offset, 0)), text_area);

    //NO CARET WHILE AN OVERLAY HAS THE KEYBOARD
    if app.settings.open || app.tofu.is_some() || app.login.is_some() { return; }

    frame.set_cursor_position(Position::new
    (
        text_area.x + cursor.0.min(text_area.width.saturating_sub(1)),
        text_area.y + cursor.1.saturating_sub(offset),
    ));
}

fn draw_palette(frame: &mut Frame, app: &mut App, area: Rect) -> Rect
{
    //ROW COUNT, VISIBLE ROWS AND LABELS
    let (total, selected, title) = match &app.palette.mode
    {
        PaletteMode::Hidden => return Rect::ZERO,

        PaletteMode::Menu(matches, selected) => (matches.len(), *selected, String::from(" Commands ")),

        //PARAMETER VALUE LIST
        PaletteMode::Values(values) =>
            (values.matches.len(), values.selected, format!(" {} ", capitalize(values.arg.name))),

        PaletteMode::Signature(..) => (1, 0, String::from(" Parameters ")),
    };

    let rows = total.min(consts::MAX_ROWS);

    //KEEP THE SELECTION IN VIEW
    let first = window(app.palette.offset, selected, total, rows);

    app.palette.offset = first;

    let height = rows as u16 + 2;

    if area.height < height || area.width < 10 { return Rect::ZERO; }

    //POPUP ABOVE THE INPUT
    let popup = Rect
    {
        x: area.x,
        y: area.y + area.height - height,
        width: area.width,
        height,
    };

    frame.render_widget(Clear, popup); //Clear RESETS THE CELLS

    frame.buffer_mut().set_style(popup, theme::TEXT);

    let block = Block::bordered()
        .border_type(BorderType::Rounded)
        .border_style(theme::BORDER_ACTIVE)
        .title(Span::styled(title, theme::TITLE));

    let inner = block.inner(popup);
    frame.render_widget(block, popup);

    let lines = match &app.palette.mode
    {
        PaletteMode::Values(values) => value_lines(values, rows, first),
        _ => entry_lines(app, rows, first, inner.width as usize),
    };

    frame.render_widget(Paragraph::new(lines), inner);

    draw_scrollbar(frame, popup, total, rows, first);

    popup
}

//ONE COLORED ROW PER ACCEPTED VALUE
fn value_lines(values: &Values, rows: usize, first: usize) -> Vec<Line<'static>>
{
    values.matches.iter().skip(first).take(rows).enumerate().map(|(row, value)|
    {
        let selected = first + row == values.selected;

        let mut spans = vec![Span::styled(if selected { "▌" } else { " " }, theme::ACCENT)];

        //PAINT THE SWATCH AS A BACKGROUND
        if let Some(color) = values.swatch(value)
        {
            spans.push(Span::styled("    ", Style::new().bg(Color::from_crossterm(color))));
            spans.push(Span::raw(" "));
        }

        spans.push(Span::raw(value.clone()));

        let line = Line::from(spans);

        if selected { line.style(theme::SELECTED) } else { line }
    }).collect()
}

//ONE ROW PER COMMAND, OR THE PARAMETER HINT
fn entry_lines(app: &App, rows: usize, first: usize, width: usize) -> Vec<Line<'static>>
{
    //ROWS, PLUS WHICH ONE IS SELECTED
    let (entries, selected) = match &app.palette.mode
    {
        PaletteMode::Menu(matches, selected) =>
        {
            let entries = matches.iter().copied()
                .skip(first)
                .take(rows)
                .map(|entry| (entry, None))
                .collect::<Vec<(Entry, Option<usize>)>>();

            (entries, Some(selected - first))
        },

        PaletteMode::Signature(entry, active) => (vec![(*entry, *active)], None),

        _ => return Vec::new(),
    };

    //MEASURE COLUMNS ACROSS VISIBLE ROWS
    let signature_width = entries.iter().map(|(entry, _)| entry.width()).max().unwrap_or(0);
    let shortcut_width = entries.iter().map(|(entry, _)| entry.shortcut().width()).max().unwrap_or(0);

    entries.iter().enumerate().map(|(row, (entry, active))|
    {
        let mut spans = vec![Span::styled(if Some(row) == selected { "▌" } else { " " }, theme::ACCENT)];

        //SHOW THE ACTIVE PARAMETER'S DESCRIPTION
        let description = active.and_then(|i| entry.args().get(i)).map_or(entry.description(), |arg| arg.description);

        spans.extend(entry.spans(*active));
        spans.push(Span::raw(" ".repeat(signature_width - entry.width() + 2)));
        spans.push(Span::styled(description.to_string(), theme::DIM));

        //SHORTCUTS IN THE RIGHT COLUMN
        if shortcut_width > 0
        {
            let used = 1 + signature_width + 2 + description.width();
            let shortcut = entry.shortcut();

            spans.push(Span::raw(" ".repeat(width.saturating_sub(used + shortcut_width + 1))));
            spans.push(Span::styled(format!("{shortcut:>shortcut_width$} "), theme::ACCENT));
        }

        let line = Line::from(spans);

        if Some(row) == selected { line.style(theme::SELECTED) } else { line }
    }).collect()
}

//"COLOR" -> "Color"
fn capitalize(name: &str) -> String
{
    let mut chars = name.chars();

    match chars.next()
    {
        Some(first) => first.to_uppercase().collect::<String>() + &chars.as_str().to_lowercase(),
        None => String::new(),
    }
}

//THE /settings OVERLAY
fn draw_settings(frame: &mut Frame, state: &mut Settings, area: Rect, font: FontSize) -> Rect
{
    let width = consts::SETTINGS_WIDTH.min(area.width.saturating_sub(2)).max(1);
    let inner_width = width.saturating_sub(2) as usize;

    if area.height < 5 || inner_width < 12 { return Rect::ZERO; }

    //BOTH MODES SHARE THE BOX
    let (title, total, selected) = match &state.picker
    {
        Some(picker) => (picker.title.to_string(), picker.entries.len(), picker.selected),
        None => (state.title(), state.rows.len(), state.selected),
    };

    //WRAP THE SELECTED KEY'S COMMENT
    let hint_lines = match state.picker.is_none().then(|| state.rows.get(state.selected)).flatten()
    {
        Some(row) => description_lines(state, row, inner_width as u16),
        None => Vec::new(),
    };

    //SIZE THE FOOT FOR THE LONGEST COMMENT
    let hint_height = match state.picker.is_some()
    {
        true => 0,
        false => state.rows.iter()
            .map(|row| description_lines(state, row, inner_width as u16).len())
            .max().unwrap_or(0),
    };

    //THE PICTURE CLAIMS ROWS AT THE TOP, AND THE ROWS GET WHAT IS LEFT
    let picture = match state.picker.is_some()
    {
        true => 0,
        false => state.picture_rows(),
    };

    let room = (area.height.saturating_sub(4) as usize).saturating_sub(picture as usize); //BORDERS PLUS A LINE OF AIR TOP AND BOTTOM

    //THE ROWS WIN WHEN THERE IS NO ROOM
    let footer = match hint_height { 0 => 0, height => height + 1 };
    let footer = if room > footer { footer } else { 0 };

    let rows_room = room - footer;

    let visible = match &state.picker
    {
        Some(_) => total.min(consts::MAX_PICKER_ROWS).min(rows_room),
        None => total.min(rows_room),
    }.max(1);

    //OFFSET AND VISIBLE ROW COUNT
    let offset = match &state.picker
    {
        Some(picker) => picker.offset,
        None => state.offset,
    };

    let first = window(offset, selected, total, visible);

    state.page = visible;

    match state.picker.as_mut()
    {
        Some(picker) => picker.offset = first,
        None => state.offset = first,
    }

    //VALUE COLUMN BEHIND THE LONGEST LABEL
    let label_width = state.rows.iter().filter_map(|row| match row
    {
        Row::Item(item) => Some(item.label.width()),
        Row::Header(_) | Row::Action(_) => None,
    }).max().unwrap_or(0).min(inner_width.saturating_sub(consts::SETTINGS_VALUE_WIDTH as usize + 3));

    //LABELS GIVE WAY FIRST ON A NARROW TERMINAL

    let mut lines = match &state.picker
    {
        Some(picker) => picker.entries.iter().enumerate()
            .skip(first)
            .take(visible)
            .map(|(index, entry)| picker_line(entry, index == picker.selected, inner_width))
            .collect::<Vec<Line>>(),

        None => state.rows.iter().enumerate()
            .skip(first)
            .take(visible)
            .map(|(index, row)| settings_line(state, row, index == state.selected, label_width, inner_width))
            .collect::<Vec<Line>>(),
    };

    let rows_height = lines.len() as u16 + 2; //WHAT THE SCROLLBAR IS ALLOWED TO RUN DOWN

    //THE PICTURE'S ROWS ARE RESERVED, NOT DRAWN INTO
    if picture > 0 { lines.splice(0..0, std::iter::repeat_n(Line::default(), picture as usize)); }

    //DESCRIPTION UNDER A RULE
    if footer > 0
    {
        lines.push(Line::from(Span::styled("\u{2500}".repeat(inner_width), theme::BORDER)));

        let blanks = hint_height - hint_lines.len(); //A SHORT COMMENT LEAVES THE REST OF THE FOOT EMPTY

        lines.extend(hint_lines);
        lines.extend(std::iter::repeat_n(Line::default(), blanks));
    }

    let height = lines.len() as u16 + 2;

    let popup = Rect
    {
        x: area.x + (area.width.saturating_sub(width)) / 2,
        y: area.y + (area.height.saturating_sub(height)) / 2,
        width,
        height,
    };

    frame.render_widget(Clear, popup); //Clear RESETS THE CELLS

    frame.buffer_mut().set_style(popup, theme::TEXT);

    let hint = match (state.picker.is_some(), state.edit.is_some())
    {
        (true, _) => " ↑↓ select │ ⏎ apply │ Esc back ",
        (_, true) if state.editing_avatar() => " ↑↓ select │ Tab complete │ ⏎ keep │ Esc cancel ",
        (_, true) => " type a value │ ⏎ keep │ Esc cancel ",

        _ => match state.mode
        {
            Mode::Client => " ↑↓ move │ ←→ change │ ⏎ select │ Esc close ",
            Mode::Server => " ↑↓ move │ ←→ change │ ⏎ edit │ ^S save │ Esc close ",
            Mode::Profile { own: true } => " ↑↓ move │ ⏎ edit │ ^S save │ Esc close ",

            //THE ONE THING A PROFILE THAT IS NOT OURS STILL DOES
            Mode::Profile { own: false } => match state.link().is_some()
            {
                true => " ↑↓ move │ ⏎ open link │ Esc close ",
                false => " ↑↓ move │ Esc close ",
            },
        },
    };

    let block = Block::bordered()
        .border_type(BorderType::Rounded)
        .border_style(theme::BORDER_ACTIVE)
        .title(Span::styled(title, theme::TITLE))
        .title_bottom(Line::from(Span::styled(hint, theme::DIM)).centered());

    let inner = block.inner(popup);
    frame.render_widget(block, popup);

    frame.render_widget(Paragraph::new(lines), inner);

    //WHERE THE PICTURE GOES, CENTRED IN THE ROWS IT CLAIMED
    state.picture_area = match state.picture.as_ref().filter(|_| picture > 0)
    {
        Some(ready) =>
        {
            let (width, height) = state::picture_cells(&ready.frames[ready.current].image,
                inner.width, consts::AVATAR_ROWS, font);

            Rect
            {
                x: inner.x + inner.width.saturating_sub(width) / 2,
                y: inner.y + consts::AVATAR_ROWS.saturating_sub(height) / 2,
                width,
                height,
            }
        },

        None => Rect::ZERO,
    };

    //THE TRACK IS THE ROWS' OWN HEIGHT, NOT THE BOX'S
    draw_scrollbar(frame, Rect { y: popup.y + picture, height: rows_height, ..popup }, total, visible, first);

    popup
}

//SERVER IDENTITY PROMPT
fn draw_tofu(frame: &mut Frame, prompt: &Prompt, area: Rect) -> Rect
{
    let width = consts::TOFU_WIDTH.min(area.width.saturating_sub(2)).max(1);
    let inner_width = width.saturating_sub(4); //BORDERS PLUS A COLUMN OF AIR EACH SIDE

    if area.height < 9 || inner_width < 20 { return Rect::ZERO; }

    let confirming = prompt.stage == Stage::Confirm;

    let warning = match (confirming, prompt.mismatch)
    {
        (true, _) => "Replacing a pinned key throws away the only thing that would \
            catch an interception. Do it only after checking the fingerprint with \
            the operator over a channel this server cannot touch.",

        (false, true) => "The server is presenting a different identity key than the one \
            pinned for this address. Either the operator replaced the server's \
            keys, or somebody is sitting between you and it.",

        (false, false) => "This address has no pinned identity key yet. Accept it only if the \
            fingerprint below matches the one the server's operator published.",
    };

    //WRAP THE BODY
    let mut lines = state::wrap_line(&Line::from(Span::styled(warning, theme::NOTICE)), inner_width);

    lines.push(Line::default());
    lines.push(Line::from(vec!
    [
        Span::styled("Server   ", theme::DIM),
        Span::raw(prompt.host.clone()),
    ]));

    //SHOW BOTH FINGERPRINTS ON A MISMATCH
    for (index, row) in prompt.pinned_fingerprint().into_iter().enumerate()
    {
        lines.push(Line::from(vec!
        [
            Span::styled(if index == 0 { "Pinned   " } else { "         " }, theme::DIM),
            Span::styled(row, theme::DIM),
        ]));
    }

    let label = if prompt.mismatch { "New key  " } else { "Key      " };

    for (index, row) in prompt.fingerprint().into_iter().enumerate()
    {
        lines.push(Line::from(vec!
        [
            Span::styled(if index == 0 { label } else { "         " }, theme::DIM),
            Span::styled(row, theme::ACCENT),
        ]));
    }

    lines.push(Line::default());

    if confirming
    {
        let typed = prompt.typed.chars().count();

        lines.append(&mut state::wrap_line(&Line::from(Span::styled(format!
        (
            "Type '{}' to replace the pinned key with this one:",
            consts::CHALLENGE,
        ), theme::TEXT)), inner_width));

        lines.push(Line::from(vec!
        [
            Span::styled(prompt.typed.clone(), theme::ACCENT),
            Span::styled("_".repeat(consts::CHALLENGE.chars().count().saturating_sub(typed)), theme::DIM),
        ]).centered());

        if prompt.wrong
        {
            lines.push(Line::from(Span::styled(format!("Type '{}' to go through with it.", consts::CHALLENGE),
                theme::ERROR)).centered());
        }
    } else
    {
        lines.push(Line::from(vec!
        [
            button(" Reject ", !prompt.accept, theme::ERROR),
            Span::raw("  "),
            button(if prompt.mismatch { " Replace pinned key " } else { " Trust & save " }, prompt.accept, theme::OK),
        ]).centered());
    }

    let height = (lines.len() as u16 + 2).min(area.height);

    let popup = Rect
    {
        x: area.x + (area.width.saturating_sub(width)) / 2,
        y: area.y + (area.height.saturating_sub(height)) / 2,
        width,
        height,
    };

    frame.render_widget(Clear, popup); //Clear RESETS THE CELLS

    frame.buffer_mut().set_style(popup, theme::TEXT);

    let block = Block::bordered()
        .border_type(BorderType::Rounded)
        .border_style(theme::ERROR)
        .title(Span::styled(prompt.title(), theme::ERROR))
        .title_bottom(Line::from(Span::styled(if confirming
        {
            " type the word │ ⏎ confirm │ ← back │ Esc reject "
        } else { " ←→ choose │ ⏎ confirm │ Esc reject " }, theme::DIM)).centered());

    let inner = block.inner(popup);
    frame.render_widget(block, popup);

    //ONE COLUMN OF AIR EACH SIDE
    let [_, text_area, _] = Layout::horizontal
    ([
        Constraint::Length(1),
        Constraint::Min(0),
        Constraint::Length(1),
    ]).areas(inner);

    frame.render_widget(Paragraph::new(lines), text_area);

    popup
}

fn draw_login(frame: &mut Frame, login: &Login, reconnect: &Reconnect, area: Rect) -> Rect
{
    let width = consts::LOGIN_WIDTH.min(area.width.saturating_sub(2)).max(1);
    let inner_width = width.saturating_sub(4); //BORDERS PLUS A COLUMN OF AIR EACH SIDE
    let field_width = inner_width.saturating_sub(2); //"> " GUTTER

    if area.height < 8 || field_width < 8 { return Rect::ZERO; }

    let (field, cursor) = login.input.render(field_width, login.masked());

    let mut lines = vec![Line::from(Span::styled(login.label(), theme::DIM))];

    for (index, line) in field.into_iter().enumerate()
    {
        let mut spans = vec![Span::styled(if index == 0 { "> " } else { "  " }, theme::ACCENT)];
        spans.extend(line.spans);

        lines.push(Line::from(spans));
    }

    lines.push(Line::default());

    //STATUS ROW, WRAPPED
    let status = match (login.busy, login.error.as_deref(), login.hint.as_deref())
    {
        //A RETRY SAYS SO INSTEAD, SINCE NOBODY ASKED FOR IT
        (true, ..) => Line::from(Span::styled(reconnect.status()
            .unwrap_or_else(|| login.waiting().to_owned()), theme::ACCENT)),
        (false, Some(error), _) => Line::from(Span::styled(error.to_string(), theme::ERROR)),
        (false, None, Some(hint)) => Line::from(Span::styled(hint.to_string(), theme::DIM)),
        (false, None, None) => Line::default(),
    };

    lines.extend(state::wrap_line(&status, inner_width));

    //THE PROXY BELONGS TO THE ADDRESS STEP
    if login.stage == LoginStage::Address && options::socks5_enabled()
    {
        let proxy = Line::from(Span::styled(format!("Through SOCKS5 {}",
            config::read_config::<String>("socks5_addr")), theme::DIM));

        lines.extend(state::wrap_line(&proxy, inner_width));
    }

    let height = (lines.len() as u16 + 2).min(area.height);

    let popup = Rect
    {
        x: area.x + (area.width.saturating_sub(width)) / 2,
        y: area.y + (area.height.saturating_sub(height)) / 2,
        width,
        height,
    };

    frame.render_widget(Clear, popup); //Clear RESETS THE CELLS

    frame.buffer_mut().set_style(popup, theme::TEXT);

    let block = Block::bordered()
        .border_type(BorderType::Rounded)
        .border_style(theme::BORDER_ACTIVE)
        .title(Span::styled(login.title(), theme::TITLE))
        .title_bottom(Line::from(Span::styled(match (login.stage, login.busy, login.cancellable())
        {
            (_, true, true) => " Esc cancel ",
            (_, true, false) => " Esc quit ",
            (LoginStage::Address, false, _) => " ⏎ connect │ Esc quit ",
            (_, false, _) => " ⏎ continue │ Esc quit ",
        }, theme::DIM)).centered());

    let inner = block.inner(popup);
    frame.render_widget(block, popup);

    //ONE COLUMN OF AIR EACH SIDE
    let [_, text_area, _] = Layout::horizontal
    ([
        Constraint::Length(1),
        Constraint::Min(0),
        Constraint::Length(1),
    ]).areas(inner);

    frame.render_widget(Paragraph::new(lines), text_area);

    //THIS BOX KEEPS THE CARET
    if !login.busy
    {
        frame.set_cursor_position(Position::new
        (
            text_area.x + 2 + cursor.0.min(field_width.saturating_sub(1)),
            text_area.y + consts::FIELD_ROW + cursor.1,
        ));
    }

    popup
}

fn button(label: &'static str, selected: bool, style: Style) -> Span<'static>
{
    if selected { Span::styled(label, style.patch(theme::SELECTED)) } else { Span::styled(label, theme::DIM) }
}

//WRAP THE SELECTED ROW'S DESCRIPTION
fn description_lines(state: &Settings, row: &Row, width: u16) -> Vec<Line<'static>>
{
    let mut spans = Vec::new();

    //THE PATHS BESIDE A TYPED AVATAR
    if let Row::Item(item) = row && item.key == consts::AVATAR_KEY && state.editing_avatar() && !state.paths.is_empty()
    {
        let visible = state.paths.len().min(consts::MAX_ROWS);
        let first = window(0, state.path, state.paths.len(), visible);

        return state.paths.iter().enumerate().skip(first).take(visible).map(|(index, path)|
        {
            let selected = index == state.path;

            let line = Line::from(vec!
            [
                Span::styled(if selected { "▌ " } else { "  " }, theme::ACCENT),
                Span::styled(truncate(path, (width as usize).saturating_sub(2)), if selected { theme::ACCENT } else { theme::TEXT }),
            ]);

            if selected { line.style(theme::SELECTED) } else { line }
        }).collect();
    }

    match row
    {
        Row::Header(_) => return Vec::new(),

        //SAY WHAT A BUTTON DOES, OR WHY IT WILL NOT
        Row::Action(label) if **label == *consts::RESTART_LABEL =>
        {
            spans.push(Span::styled("Restart the server \u{2014} every client is disconnected and the whole config is read again.", theme::DIM));

            if state.unsaved() { spans.push(Span::styled(" \u{b7} save your changes first", theme::NOTICE)); }
            else if state.confirm { spans.push(Span::styled(" \u{b7} press again to confirm", theme::ERROR)); }
        },

        Row::Action(_) if state.profile() =>
            spans.push(Span::styled("Send the description to the server.", theme::DIM)),

        Row::Action(_) => spans.push(Span::styled("Send the edited rows to the server.", theme::DIM)),

        //A FIELD IS PROSE OR A LINK, SO THE FOOT IS WHERE IT IS READ
        Row::Item(item) if state.profile() => match &item.value
        {
            Value::Avatar(Some(path)) if path.is_empty() =>
                spans.push(Span::styled("Your avatar is removed on save.", theme::NOTICE)),

            Value::Avatar(Some(path)) => spans.push(Span::styled(format!("{path} is uploaded on save."), theme::TEXT)),

            Value::Avatar(None) => spans.push(Span::styled(format!(
                "Type a path to an image (up to {}MB) to have its centre cut to a square, or clear it to remove your avatar.",
                chat_consts::MAX_IMAGE_SIZE / chat_consts::MEGABYTE), theme::DIM)),

            Value::Text(text) if text.is_empty() =>
                spans.push(Span::styled(format!("No {}.", item.label.to_lowercase()), theme::DIM)),

            Value::Text(text) => spans.push(Span::styled(text.clone(), theme::TEXT)),

            _ => {},
        },

        Row::Item(item) =>
        {
            if !item.hint.is_empty() { spans.push(Span::styled(item.hint.clone(), theme::DIM)); }

            //MARK A STARTUP-ONLY KEY
            if item.restart
            {
                let note = match spans.is_empty() { true => "restart required", false => " \u{b7} restart required" };

                spans.push(Span::styled(note, theme::NOTICE));
            }
        },
    }

    if spans.is_empty() { return Vec::new(); }

    state::wrap_line(&Line::from(spans), width)
}

fn settings_line(_state: &Settings, row: &Row, selected: bool, label_width: usize, width: usize) -> Line<'static>
{
    let item = match row
    {
        //SECTION HEADING WITH A RULE
        Row::Header(label) => return Line::from(vec!
        [
            Span::styled(format!(" {label} "), theme::TITLE),
            Span::styled("─".repeat(width.saturating_sub(label.width() + 2)), theme::BORDER),
        ]),

        //A BUTTON IS THE WHOLE ROW
        Row::Action(label) =>
        {
            //A BUTTON IS LIVE WHEN IT HAS SOMETHING TO DO
            let restart = **label == *consts::RESTART_LABEL;
            let live = if restart { !_state.unsaved() } else { _state.unsaved() };
            let armed = restart && _state.confirm;

            let style = match (armed, selected, live)
            {
                (true, _, _) => theme::ERROR,
                (_, true, _) => theme::ACCENT,
                (_, false, true) => theme::TEXT,
                (_, false, false) => theme::DIM,
            };

            let text = match armed
            {
                true => format!("[ {label} \u{b7} press again ]"),
                false => format!("[ {label} ]"),
            };
            let padding = width.saturating_sub(text.width() + 1) / 2;

            let line = Line::from(vec!
            [
                Span::styled(if selected { "▌" } else { " " }, theme::ACCENT),
                Span::raw(" ".repeat(padding)),
                Span::styled(text, style),
            ]);

            return if selected { line.style(theme::SELECTED) } else { line };
        },

        Row::Item(item) => item,
    };

    let mut spans = vec!
    [
        Span::styled(if selected { "▌" } else { " " }, theme::ACCENT),
        Span::styled
        (
            format!(" {:<label_width$}  ", truncate(&item.label, label_width)),
            if selected { theme::ACCENT } else { theme::TEXT },
        ),
    ];

    let value_width = width.saturating_sub(label_width + 3);

    //SHOW THE TEXT BEING TYPED, CARET AND ALL
    match _state.edit.as_ref().filter(|_| selected)
    {
        Some(edit) => spans.push(Span::styled(format!("{}▏", truncate(edit, value_width.saturating_sub(1))), theme::ACCENT)),
        None => spans.extend(value_spans(_state, &item.value, value_width)),
    }

    //MARK AN EDITED ROW
    if item.changed { spans.push(Span::styled(" ●", theme::NOTICE)); }

    //MARK A ROW NEEDING A RESTART
    if item.restart { spans.push(Span::styled(" ↻", theme::DIM)); }

    let line = Line::from(spans);

    if selected { line.style(theme::SELECTED) } else { line }
}

fn value_spans(_state: &Settings, value: &Value, _width: usize) -> Vec<Span<'static>>
{
    match value
    {
        Value::Toggle { on: true, .. } => vec![Span::styled("● on", theme::OK)],
        Value::Toggle { on: false, .. } => vec![Span::styled("○ off", theme::DIM)],

        Value::Number(number) => vec![Span::styled(number.to_string(), theme::TEXT)],

        Value::Text(text) if text.is_empty() => vec![Span::styled("(empty)", theme::DIM)],
        Value::Text(text) => vec![Span::styled(truncate(text, _width), theme::TEXT)],

        Value::Avatar(None) if _state.avatar.is_some() => vec![Span::styled("set", theme::TEXT)],
        Value::Avatar(None) => vec![Span::styled("(none)", theme::DIM)],
        Value::Avatar(Some(path)) if path.is_empty() => vec![Span::styled("remove", theme::NOTICE)],
        Value::Avatar(Some(path)) => vec![Span::styled(truncate(path, _width), theme::TEXT)],

        #[cfg(feature = "client_voice")]
        Value::Volume(percent) =>
        {
            //THE BAR IS THE WHOLE RANGE
            let filled = (*percent as usize * consts::SLIDER_WIDTH).div_ceil(voice_consts::VOLUME_MAX as usize);

            vec!
            [
                Span::styled("█".repeat(filled), theme::ACCENT),
                Span::styled("░".repeat(consts::SLIDER_WIDTH.saturating_sub(filled)), theme::BORDER),
                Span::styled(format!(" {percent:>3}%"), if *percent == 0 { theme::DIM } else { theme::TEXT }),
            ]
        },

        #[cfg(feature = "client_voice")]
        Value::Device { id, input } =>
        {
            if id.is_empty()
            {
                vec![Span::styled(consts::DEFAULT_DEVICE, theme::DIM)]
            } else
            {
                vec![Span::styled(truncate(&_state.device_label(id, *input), _width), theme::ACCENT)]
            }
        },
    }
}

#[cfg(feature = "client_voice")]
fn picker_line(entry: &DeviceEntry, selected: bool, width: usize) -> Line<'static>
{
    //ENTRY 0 IS THE SYSTEM DEFAULT
    let (text, style) = if entry.id.is_empty()
    {
        (String::from(consts::DEFAULT_DEVICE), theme::DIM)
    } else
    {
        (truncate(&entry.label, width.saturating_sub(3)), theme::TEXT)
    };

    let line = Line::from(vec!
    [
        Span::styled(if selected { "▌" } else { " " }, theme::ACCENT),
        Span::styled(format!(" {text}"), style),
    ]);

    if selected { line.style(theme::SELECTED) } else { line }
}

#[cfg(not(feature = "client_voice"))]
fn picker_line(_entry: &DeviceEntry, _selected: bool, _width: usize) -> Line<'static> { Line::default() }

fn truncate(text: &str, width: usize) -> String //FIT text INTO width CELLS, ELLIPSIS AND ALL
{
    if text.width() <= width { return text.to_string(); }

    let mut out = String::new();
    let mut used = 0;

    for c in text.chars()
    {
        let next = used + c.to_string().width();

        if next > width.saturating_sub(1) { break; }

        out.push(c);
        used = next;
    }

    out.push('…');
    out
}

fn right_status(_app: &App) -> String
{
    let mut parts: Vec<String> = Vec::new();

    #[cfg(feature = "client_voice")]
    if _app.voice_enabled
    {
        //0% IS OFF
        let off = options::is_muted(None) || voice_options::get_input_volume() == 0;

        parts.push(String::from(if off { "mic off" } else { "mic on" }));
    }

    parts.push(String::from("Ctrl+, settings"));

    format!(" {} ", parts.join(" │ "))
}

//THE CHANNEL'S VOICE ROSTER
fn voice_visible(app: &App) -> bool
{
    !app.voice.is_empty()
}