why2-chat 2.1.4

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
/*
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 std::
{
    mem,
    iter,
    time::Instant,
    collections::
    {
        BTreeMap,
        BTreeSet,
        HashMap,
        VecDeque,
    },
};

use ratatui::
{
    layout::Rect,
    style::Style,
    text::{ Line, Span },
};

use unicode_width::UnicodeWidthChar;

use image::DynamicImage;

use ratatui_image::
{
    FontSize,
    FilterType,
    picker::Picker,
    protocol::StatefulProtocol,
};

use crate::
{
    role::Role,
    options::{ self, LoginState },
    network::
    {
        codes::{ MessageColors, OnlineUser },
        client::{ self, Animation, ImageFrame, VoiceUser },
    },
};

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

#[cfg(feature = "client_screen")]
use crate::network::screen::client::options as screen_options;

use super::
{
    consts,
    input::InputBuffer,
    login::{ Login, Reconnect, Stage },
    palette::Palette,
    settings::Settings,
    tofu::Prompt,
    theme::Theme,
};

//ENUMS
pub enum Entry //ONE ROW OF HISTORY
{
    Line(Line<'static>), //ALREADY STYLED - CLIENT OUTPUT, NOTICES, BLOCK COMMANDS

    //A CHAT MESSAGE, STORED UNRENDERED
    Message
    {
        username: String,
        id: usize,
        text: String,
        colors: MessageColors,
    },

    //A REPLAYED MESSAGE, WITHOUT AN ID
    History
    {
        username: String,
        text: String,
        colors: MessageColors,
    },

    //A CLIENT PREFIX IN FRONT OF TYPED TEXT
    Prefixed
    {
        prefix: Vec<Span<'static>>,
        text: String,
    },

    //A PICTURE AND ITS CAPTION
    Image
    {
        username: String,
        filename: String,
        username_color: Option<u8>, //THE SENDER'S, LIKE A MESSAGE'S
        hash: Option<[u8; 32]>,     //WHAT TO ASK THE SERVER FOR
        picture: Picture,
    },
}

//WHAT THERE IS TO DRAW UNDER A CAPTION
pub enum Picture
{
    Absent,            //NOT ASKED FOR YET
    Waiting,           //ASKED FOR, NOT HERE YET
    Gone,              //THE SERVER DOES NOT HAVE IT ANY MORE
    Ready(Box<Fitted>),
}

//STRUCTS
pub struct Fitted //A PICTURE AT THE SIZE THE PANE DRAWS IT AT
{
    pub frames: Animation,                  //THE PICTURE ITSELF, KEPT TO FIT AGAIN AT A NEW PANE WIDTH
    pub current: usize,                     //WHICH FRAME `protocol` HOLDS - A STILL HAS ONLY THE ONE
    pub next: Instant,                      //WHEN THE FRAME AFTER IT IS DUE
    pub rows: u16,                          //ROWS IT RESERVES AT THAT WIDTH
    pub fitted: u16,                        //THE WIDTH `protocol` WAS FITTED TO
    pub protocol: Option<StatefulProtocol>, //None UNTIL THE FIRST WRAP KNOWS HOW WIDE THE PANE IS
}

#[derive(Clone, Copy)]
pub struct Placement //WHERE ONE IMAGE SITS IN THE WRAPPED VIEW
{
    pub entry: usize,  //WHICH App::messages ENTRY IT BELONGS TO
    pub caption: u16,  //FIRST ROW OF THE CAPTION
    pub row: u16,      //FIRST RESERVED ROW (WHERE THE CAPTION ENDS)
    pub height: u16,   //RESERVED ROWS - 0 WHILE THERE IS NO PICTURE
}

//A DRAG, IN WRAPPED-VIEW ROWS
#[derive(Clone, Copy)]
pub struct Selection
{
    pub anchor: (u16, u16), //(ROW IN THE WRAPPED VIEW, COLUMN INSIDE THE PANE)
    pub cursor: (u16, u16),
    pub dragged: bool,      //A DRAG EVER ARRIVED
}

//STRUCTS
pub struct App
{
    //MESSAGE PANE
    pub messages: VecDeque<Entry>, //THE PANE BEING LOOKED AT - THE CHANNEL WE ARE STANDING IN
    pub channel: String,           //WHICH CHANNEL THAT IS ("" = THE LOBBY)
    pub panes: HashMap<String, VecDeque<Entry>>, //THE OTHER CHANNELS' SCROLLBACK, PARKED WHILE WE ARE AWAY
    pub scroll: Option<u16>, //None = STUCK TO THE BOTTOM
    pub unread: usize,       //MESSAGES ARRIVED WHILE SCROLLED AWAY

    //SIDEBAR
    pub username: String, //OUR OWN USERNAME (options::get_server_username IS THE SERVER'S NAME)
    pub role: Role,       //OUR OWN ROLE
    pub online: Vec<OnlineUser>,
    pub channels: BTreeSet<String>, //NAMED CHANNELS THE SERVER CURRENTLY HOLDS
    pub voice: Vec<VoiceUser>, //WHAT THE VOICE PANEL DRAWS
    pub voice_roster: BTreeMap<usize, String>, //WHO THE SERVER SAYS IS IN VOICE IN OUR CHANNEL (US EXCLUDED)
    pub voice_activity: Vec<VoiceUser>, //WHO WE ARE ACTUALLY HEARING
    pub voice_enabled: bool,

    //CONNECTION (SHOWN IN THE MESSAGE PANE TITLE)
    pub address: String,     //AS THE USER TYPED IT - NO IMPLICIT PORT
    pub server_name: String, //THE SERVER'S OWN NAME, ONCE IT HAS INTRODUCED ITSELF

    //INPUT
    pub input: InputBuffer,
    pub palette: Palette,
    pub settings: Settings, //SETTINGS OVERLAY (CLOSED UNLESS THE USER OPENED IT)
    pub login: Option<Login>, //CONNECT BOX
    pub tofu: Option<Prompt>, //SERVER IDENTITY PROMPT
    pub theme: Theme,
    pub picker: Picker, //WHAT THE TERMINAL CAN DRAW, AND HOW BIG ITS CELLS ARE

    //WHERE THE MESSAGE PANE WAS LAST DRAWN
    pub pane: Rect,
    pub pane_offset: u16,
    pub selection: Option<Selection>, //A DRAG-SELECTED RUN OF THE PANE, KEPT UNTIL THE NEXT PRESS

    //A TOAST IN THE CHROME, WHICH EXPIRES
    pub notice: Option<(String, Instant)>,

    //REQUEST BOOKKEEPING
    pub list_requested: bool,
    #[cfg(feature = "client_screen")]
    pub screens_requested: bool,
    pub refresh_online: bool, //THE LOOP SHOULD SEND A SILENT PacketCode::List

    //PICTURES TO ASK THE SERVER FOR
    pub image_requests: Vec<[u8; 32]>,

    //LIFECYCLE
    pub leaving: bool,      //THE USER ASKED TO LEAVE
    pub logging_out: bool,  //THE USER ASKED TO LOG OUT
    pub disconnect_reason: Option<String>, //WHY THE SERVER IS ABOUT TO DROP US
    pub reconnect: Reconnect, //DIALS ITSELF BACK AFTER A DROP THE USER DID NOT ASK FOR
    pub drop_stream: bool,  //THE LOOP OWNS THE WRITE HALF
    pub should_quit: bool,
    pub exit_code: i32,
    pub quit_message: Option<String>, //PRINTED ON THE NORMAL SCREEN AFTER TEARDOWN
    pub dirty: bool,

    //WRAP CACHE
    generation: u64,
    wrapped: Option<(u16, u64, Vec<Line<'static>>, Vec<Placement>)>,
}

//IMPLEMENTATIONS
impl Selection
{
    pub fn ordered(&self) -> ((u16, u16), (u16, u16)) //THE TWO ENDS IN READING ORDER
    {
        if self.cursor < self.anchor { (self.cursor, self.anchor) } else { (self.anchor, self.cursor) }
    }
}

impl Default for App
{
    fn default() -> Self { Self::new() }
}

impl App
{
    pub fn new() -> Self
    {
        Self
        {
            messages: VecDeque::new(),
            channel: String::new(),
            panes: HashMap::new(),
            scroll: None,
            unread: 0,
            username: String::new(),
            role: Role::default(),
            online: Vec::new(),
            channels: BTreeSet::new(),
            voice: Vec::new(),
            voice_roster: BTreeMap::new(),
            voice_activity: Vec::new(),
            voice_enabled: false,
            address: String::new(),
            server_name: String::new(),
            input: InputBuffer::new(),
            palette: Palette::new(),
            settings: Settings::new(),
            login: Some(Login::new()),
            tofu: None,
            theme: Theme::load(),
            picker: Picker::halfblocks(), //UNTIL init_picker HAS ASKED THE TERMINAL
            pane: Rect::ZERO,
            pane_offset: 0,
            selection: None,
            notice: None,
            list_requested: false,
            #[cfg(feature = "client_screen")]
            screens_requested: false,
            refresh_online: false,
            image_requests: Vec::new(),
            leaving: false,
            logging_out: false,
            disconnect_reason: None,
            reconnect: Reconnect::default(),
            drop_stream: false,
            should_quit: false,
            exit_code: 0,
            quit_message: None,
            dirty: true,
            generation: 0,
            wrapped: None,
        }
    }

    //BUILD THE PANEL FROM ROSTER + LOCAL SESSION
    pub fn rebuild_voice(&mut self)
    {
        let mut users: Vec<VoiceUser> = Vec::with_capacity(self.voice_roster.len() + 1);

        //US, FROM THE LOCAL SESSION
        if self.voice_enabled
        {
            users.push(match self.voice_activity.iter().find(|user| user.is_local)
            {
                Some(local) => VoiceUser { username: self.username.clone(), ..*local },

                //THE FIRST TICK IS UP TO 100 ms AWAY
                None => VoiceUser
                {
                    id: 0,
                    username: self.username.clone(),
                    is_speaking: false,
                    latency: None,
                    is_local: true,
                },
            });
        }

        //EVERYBODY ELSE, IN ID ORDER
        for (id, username) in self.voice_roster.iter()
        {
            let heard = self.voice_activity.iter().find(|user| !user.is_local && user.id == *id);

            users.push(VoiceUser
            {
                id: *id,
                username: username.clone(),
                is_speaking: heard.is_some_and(|user| user.is_speaking),
                latency: heard.and_then(|user| user.latency),
                is_local: false,
            });
        }

        self.voice = users;
        self.dirty = true;
    }

    //OUTPUT
    pub fn push(&mut self, line: Line<'static>)
    {
        self.push_entry(Entry::Line(line));
    }

    //STORE A CHAT MESSAGE UNRENDERED
    pub fn push_message(&mut self, username: String, id: usize, text: String, colors: MessageColors)
    {
        self.push_entry(Entry::Message { username, id, text, colors });
    }

    //A PRIVATE MESSAGE, BEHIND A PREFIX
    pub fn push_prefixed(&mut self, prefix: Vec<Span<'static>>, text: String)
    {
        self.push_entry(Entry::Prefixed { prefix, text });
    }

    //STORE A REPLAYED MESSAGE UNRENDERED
    pub fn push_history(&mut self, username: String, text: String, colors: MessageColors)
    {
        self.push_entry(Entry::History { username, text, colors });
    }

    //A PICTURE THAT CAME WITH ITS BYTES
    pub fn push_image(&mut self, username: String, filename: String, image: Animation,
        username_color: Option<u8>)
    {
        let picture = self.fit(image);

        self.push_entry(Entry::Image { username, filename, username_color, hash: None, picture });
    }

    //A CAPTION WITHOUT ITS PICTURE
    pub fn push_caption(&mut self, username: String, filename: String, hash: [u8; 32], pending: bool,
        username_color: Option<u8>)
    {
        let picture = match pending
        {
            true => Picture::Waiting,
            false => Picture::Absent,
        };

        self.push_entry(Entry::Image { username, filename, username_color, hash: Some(hash), picture });
    }

    //A CLICKED CAPTION
    pub fn request_image(&mut self, entry: usize) -> Option<[u8; 32]>
    {
        let Some(Entry::Image { hash, picture, .. }) = self.messages.get_mut(entry) else { return None };

        if !matches!(picture, Picture::Absent | Picture::Gone) { return None; }

        *picture = Picture::Waiting;

        self.generation += 1;
        self.dirty = true;

        *hash
    }

    //FILL THE OLDEST LINE STILL WAITING
    pub fn deliver_image(&mut self, hash: [u8; 32], image: Option<Animation>)
    {
        let (picture, asked) = match image
        {
            Some(image) => (self.fit(image), false),
            None => (Picture::Gone, true),
        };

        let waiting = self.messages.iter().position(|entry| match entry
        {
            Entry::Image { hash: Some(h), picture: slot, .. } if *h == hash => match asked
            {
                true => matches!(slot, Picture::Waiting),
                false => matches!(slot, Picture::Absent | Picture::Waiting),
            },

            _ => false,
        });

        let Some(entry) = waiting else { return };

        if let Some(Entry::Image { picture: slot, .. }) = self.messages.get_mut(entry) { *slot = picture; }

        self.generation += 1;
        self.dirty = true;
    }

    //CUT EVERY FRAME DOWN TO IMAGE_ROWS
    fn fit(&self, image: Animation) -> Picture
    {
        let font = self.picker.font_size();
        let limit = consts::IMAGE_ROWS as u32 * font.height as u32;

        //EVERY FRAME IS HELD AT ONCE
        let frames = image.into_iter().map(|ImageFrame { image, delay }|
        {
            let image = match image.height() > limit
            {
                true => image.resize(image.width(), limit, FilterType::Triangle),
                false => image,
            };

            ImageFrame { image, delay }
        }).collect::<Animation>();

        let next = Instant::now() + frames.first().map(|frame| frame.delay).unwrap_or_default();

        Picture::Ready(Box::new(Fitted { frames, current: 0, next, rows: 1, fitted: 0, protocol: None }))
    }

    //STEP EVERY ANIMATION THAT IS DUE
    pub fn advance_animations(&mut self)
    {
        let pane = self.pane;

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

        let now = Instant::now();
        let offset = self.pane_offset;
        let font = self.picker.font_size();

        //ONLY THE PICTURES ON SCREEN
        let visible = self.placements(pane.width).into_iter()
            .filter(|placement| placement.height > 0
                && placement.row < offset + pane.height
                && placement.row + placement.height > offset)
            .map(|placement| placement.entry)
            .collect::<Vec<usize>>();

        for entry in visible
        {
            let Some(Entry::Image { picture: Picture::Ready(ready), .. }) = self.messages.get_mut(entry)
                else { continue };

            //A STILL NEVER ADVANCES
            if ready.frames.len() < 2 || ready.protocol.is_none() || now < ready.next { continue; }

            //TOO FAR BEHIND TO CATCH UP
            if now.duration_since(ready.next) > consts::ANIMATION_CATCHUP { ready.next = now; }

            while now >= ready.next
            {
                ready.current = (ready.current + 1) % ready.frames.len();
                ready.next += ready.frames[ready.current].delay;
            }

            let image = fit_image(&ready.frames[ready.current].image, ready.fitted, font);

            //REUSE THE PROTOCOL TYPE TO KEEP THE IMAGE ID
            ready.protocol = ready.protocol.take().map(|protocol|
            {
                let background = protocol.background_color();

                StatefulProtocol::new(image, font, background, protocol.protocol_type_owned())
            });

            self.dirty = true;
        }
    }

    //THE QUERY WANTS STDIO TO ITSELF
    pub fn init_picker(&mut self)
    {
        if let Ok(picker) = Picker::from_query_stdio() { self.picker = picker; }
    }

    fn push_entry(&mut self, entry: Entry)
    {
        self.messages.push_back(entry);

        while self.messages.len() > consts::HISTORY_LIMIT { self.messages.pop_front(); }

        self.generation += 1;
        self.dirty = true;

        if self.scroll.is_some() { self.unread += 1; }
    }

    pub fn push_text(&mut self, text: impl Into<String>)
    {
        self.push(Line::from(Span::raw(text.into())));
    }

    pub fn push_styled(&mut self, text: impl Into<String>, style: Style)
    {
        self.push(Line::from(Span::styled(text.into(), style)));
    }

    //CLEAR THE PANE BEING LOOKED AT
    pub fn clear_messages(&mut self)
    {
        self.messages.clear();
        self.wrapped = None;
        self.selection = None;
        self.scroll = None;
        self.unread = 0;

        self.generation += 1;
        self.dirty = true;
    }

    //PARK THE OLD PANE, PUT BACK THE NEW ONE
    pub fn switch_channel(&mut self, channel: String)
    {
        if channel == self.channel { return; }

        let parked = mem::take(&mut self.messages);

        if !parked.is_empty() { self.panes.insert(mem::take(&mut self.channel), parked); }

        self.messages = self.panes.remove(&channel).unwrap_or_default();
        self.channel = channel;

        self.wrapped = None;
        self.selection = None;
        self.scroll = None;
        self.unread = 0;

        self.generation += 1;
        self.dirty = true;
    }

    //DROP THE SCROLLBACK OF AN EMPTY CHANNEL
    pub fn prune_panes(&mut self)
    {
        self.panes.retain(|channel, _| channel.is_empty() || self.channels.contains(channel));
    }

    //RE-READ THE STYLING AND REPAINT THE HISTORY
    pub fn reload_theme(&mut self)
    {
        self.theme.reload();

        //THE WRAP CACHE HOLDS RENDERED LINES
        self.generation += 1;
        self.wrapped = None;
        self.dirty = true;
    }

    //PUT A REPLAYED ANSWER IN THE FIELD FOR THE TICK TO SEND
    pub fn answer_step(&mut self, stage: Stage)
    {
        let Some(answer) = self.reconnect.answer(stage) else { return };

        if let Some(login) = self.login.as_mut() { login.input.insert_str(&answer); }

        self.reconnect.submit = true;
    }

    //THROW THE SESSION AWAY, BRING BACK THE BOX
    pub fn disconnected(&mut self, reason: impl Into<String>)
    {
        //CARRY THE DIAL COUNTER OVER
        let attempt = self.login.as_ref().map_or(0, Login::attempt);
        //A LOGOUT IS NOT A NET FAIL - IT ASKED FOR THIS
        if self.logging_out { self.reconnect.forget(); }

        //DIAL BACK UNLESS WE HAVE RUN OUT OF TRIES - THE REASON IS WHAT IS LEFT ON SCREEN IF WE HAVE
        let retrying = self.reconnect.arm();

        self.login = Some(Login::again(&self.address, attempt, reason.into()));
        self.drop_stream = true; //THE WRITE HALF BELONGS TO THE EVENT LOOP

        //A NEW SESSION STARTS BLANK
        self.clear_messages();
        self.panes.clear();
        self.channel.clear();

        self.input = InputBuffer::new();
        self.palette.dismiss();
        self.settings.close();
        self.tofu = None;

        self.username.clear();
        self.role = Role::default(); //THE NEXT SERVER GRANTS ITS OWN
        self.server_name.clear();
        self.online.clear();
        self.channels.clear();
        self.voice.clear();
        self.voice_roster.clear();
        self.voice_activity.clear();
        self.voice_enabled = false;

        self.list_requested = false;
        #[cfg(feature = "client_screen")]
        { self.screens_requested = false; }
        self.refresh_online = false;
        self.image_requests.clear();
        self.logging_out = false; //THE NEXT DROP IS THE NEXT SESSION'S TO EXPLAIN
        self.disconnect_reason = None;

        reset_session();

        //THE BOX IS BUSY UNTIL THE WAIT IS UP
        if retrying && let Some(login) = self.login.as_mut() { login.busy = true; }

        self.dirty = true;
    }

    //SCROLLING
    pub fn scroll_up(&mut self, amount: u16, viewport: u16)
    {
        let total = self.wrapped_len();
        let max_offset = total.saturating_sub(viewport);
        let current = self.scroll.unwrap_or(max_offset);

        self.scroll = Some(current.saturating_sub(amount));
        self.dirty = true;
    }

    pub fn scroll_down(&mut self, amount: u16, viewport: u16)
    {
        let total = self.wrapped_len();
        let max_offset = total.saturating_sub(viewport);

        if let Some(current) = self.scroll
        {
            let next = current.saturating_add(amount);

            if next >= max_offset { self.stick_to_bottom(); } else { self.scroll = Some(next); }
        }

        self.dirty = true;
    }

    pub fn stick_to_bottom(&mut self)
    {
        self.scroll = None;
        self.unread = 0;
        self.dirty = true;
    }

    //WRAPPED VIEW (CACHED PER WIDTH + GENERATION)
    pub fn wrapped_lines(&mut self, width: u16) -> &[Line<'static>]
    {
        self.rewrap(width);

        &self.wrapped.as_ref().unwrap().2
    }

    //WHICH IMAGE'S CAPTION IS UNDER THE POINTER
    pub fn image_at(&mut self, column: u16, row: u16) -> Option<usize>
    {
        let pane = self.pane;

        if column < pane.x || column >= pane.x + pane.width { return None; }
        if row < pane.y || row >= pane.y + pane.height { return None; }

        let row = self.pane_offset + (row - pane.y);

        self.placements(pane.width).into_iter()
            .find(|placement| row >= placement.caption && row < placement.row)
            .map(|placement| placement.entry)
    }

    //SELECTION
    //A PRESS STARTS ONE; A DRAG MAKES IT A SELECTION
    pub fn selection_start(&mut self, column: u16, row: u16) -> bool
    {
        let pane = self.pane;

        if column < pane.x || column >= pane.x + pane.width { return false; }
        if row < pane.y || row >= pane.y + pane.height { return false; }

        let cell = self.pane_cell(column, row);

        self.selection = Some(Selection { anchor: cell, cursor: cell, dragged: false });
        self.dirty = true;

        true
    }

    //A DRAG PAST AN EDGE SCROLLS THE PANE
    pub fn selection_extend(&mut self, column: u16, row: u16)
    {
        let pane = self.pane;

        if self.selection.is_none() || pane.height == 0 { return; }

        //NAME THE ROW THE SCROLL IS ABOUT TO REVEAL
        let cell = match row
        {
            _ if row < pane.y =>
            {
                self.scroll_up(1, pane.height);

                (self.pane_offset.saturating_sub(1), self.pane_cell(column, row).1)
            },

            _ if row >= pane.y + pane.height =>
            {
                self.scroll_down(1, pane.height);

                (self.pane_offset + pane.height, self.pane_cell(column, row).1)
            },

            _ => self.pane_cell(column, row),
        };

        if let Some(selection) = self.selection.as_mut()
        {
            selection.cursor = cell;
            selection.dragged = true;
        }

        self.dirty = true;
    }

    //TOAST
    //A TOAST IN THE PANE'S BOTTOM BORDER
    pub fn notify(&mut self, text: impl Into<String>)
    {
        self.notice = Some((text.into(), Instant::now()));
        self.dirty = true;
    }

    pub fn notice(&self) -> Option<&str>
    {
        self.notice.as_ref()
            .filter(|(_, shown)| shown.elapsed() < consts::NOTICE_DURATION)
            .map(|(text, _)| text.as_str())
    }

    //DROP THE TOAST ONCE IT IS OLD
    pub fn expire_notice(&mut self)
    {
        if self.notice.is_some() && self.notice().is_none()
        {
            self.notice = None;
            self.dirty = true;
        }
    }

    pub fn clear_selection(&mut self)
    {
        if self.selection.take().is_some() { self.dirty = true; }
    }

    //WHICH COLUMNS OF A ROW ARE SELECTED
    pub fn selection_columns(&self, row: u16) -> Option<(u16, u16)>
    {
        let selection = self.selection?;

        if !selection.dragged { return None; }

        let (start, end) = selection.ordered();

        if row < start.0 || row > end.0 { return None; }

        let last = self.pane.width.saturating_sub(1);

        let first = if row == start.0 { start.1 } else { 0 };
        let final_column = if row == end.0 { end.1 } else { last };

        (first <= final_column).then_some((first, final_column))
    }

    //THE SELECTED TEXT
    pub fn selection_text(&mut self) -> Option<String>
    {
        let selection = self.selection?;

        if !selection.dragged { return None; }

        let width = self.pane.width;
        let (start, end) = selection.ordered();

        self.rewrap(width);

        let lines = &self.wrapped.as_ref().unwrap().2;
        let last = width.saturating_sub(1);

        let mut out: Vec<String> = Vec::new();

        for row in start.0..=end.0
        {
            let Some(line) = lines.get(row as usize) else { break };

            let first = if row == start.0 { start.1 } else { 0 };
            let final_column = if row == end.0 { end.1 } else { last };

            if first > final_column { continue; }

            out.push(slice_cells(line, first as usize, final_column as usize).trim_end().to_owned());
        }

        let text = out.join("\n");

        (!text.trim().is_empty()).then_some(text)
    }

    //A TERMINAL CELL AS A WRAPPED-VIEW PLACE
    fn pane_cell(&self, column: u16, row: u16) -> (u16, u16)
    {
        let pane = self.pane;

        let column = column.clamp(pane.x, pane.x + pane.width.saturating_sub(1)) - pane.x;
        let row = row.clamp(pane.y, pane.y + pane.height.saturating_sub(1)) - pane.y;

        (self.pane_offset + row, column)
    }

    //WHERE THE PICTURES SIT IN THE WRAPPED VIEW
    pub fn placements(&mut self, width: u16) -> Vec<Placement>
    {
        self.rewrap(width);

        self.wrapped.as_ref().unwrap().3.clone()
    }

    fn rewrap(&mut self, width: u16)
    {
        let stale = match &self.wrapped
        {
            Some((w, g, _, _)) => *w != width || *g != self.generation,
            None => true,
        };

        if !stale { return; }

        let font = self.picker.font_size();

        let mut lines: Vec<Line<'static>> = Vec::new();
        let mut placements: Vec<Placement> = Vec::new();

        for entry in 0..self.messages.len()
        {
            let row = lines.len() as u16;

            lines.extend(self.theme.render(&self.messages[entry], width));

            //AN IMAGE RESERVES ITS ROWS AS BLANK LINES
            if let Entry::Image { picture, .. } = &mut self.messages[entry]
            {
                let caption = row;
                let row = lines.len() as u16;

                //FIT THE PICTURE HERE AND NOWHERE ELSE
                let height = match picture
                {
                    Picture::Ready(ready) =>
                    {
                        if ready.fitted != width || ready.protocol.is_none()
                        {
                            let image = fit_image(&ready.frames[ready.current].image, width, font);

                            ready.rows = (image.height().div_ceil(font.height as u32) as u16).clamp(1, consts::IMAGE_ROWS);
                            ready.protocol = Some(self.picker.new_resize_protocol(image));
                            ready.fitted = width;
                        }

                        ready.rows
                    },

                    //A CAPTION WITHOUT A PICTURE RESERVES NOTHING
                    _ => 0,
                };

                placements.push(Placement { entry, caption, row, height });
                lines.extend(iter::repeat_n(Line::default(), height as usize));
            }
        }

        self.wrapped = Some((width, self.generation, lines, placements));
    }

    fn wrapped_len(&self) -> u16
    {
        self.wrapped.as_ref().map(|(_, _, lines, _)| lines.len() as u16).unwrap_or(0)
    }
}

//FUNCTIONS
//SHRINK A PICTURE INTO THE PANE, NEVER GROW IT
fn fit_image(image: &DynamicImage, width: u16, font: FontSize) -> DynamicImage
{
    let available_width = width.max(1) as u32 * font.width as u32;
    let available_height = consts::IMAGE_ROWS as u32 * font.height as u32;

    match image.width() > available_width || image.height() > available_height
    {
        true => image.resize(available_width, available_height, FilterType::Triangle),
        false => image.clone(),
    }
}

//ONE WRAPPED LINE BETWEEN TWO CELL COLUMNS
fn slice_cells(line: &Line<'static>, from: usize, to: usize) -> String
{
    let mut out = String::new();
    let mut column = 0usize;

    for span in &line.spans
    {
        for c in span.content.chars()
        {
            let w = c.width().unwrap_or(0).max(1);

            if column + w > from && column <= to { out.push(c); }

            column += w;

            if column > to { return out; }
        }
    }

    out
}

pub fn wrap_line(line: &Line<'static>, width: u16) -> Vec<Line<'static>> //WORD-WRAP ONE LOGICAL LINE, KEEPING SPAN STYLES
{
    let width = width.max(1) as usize;

    let mut out: Vec<Line<'static>> = Vec::new();
    let mut current: Vec<Span<'static>> = Vec::new();
    let mut column = 0usize;

    for span in &line.spans
    {
        let style = span.style;

        for word in split_words(span.content.as_ref())
        {
            let word_width = text_width(word);

            //BREAK BEFORE A WORD THAT NO LONGER FITS
            if column + word_width > width && column > 0
            {
                out.push(Line::from(mem::take(&mut current)));
                column = 0;

                if word.chars().all(char::is_whitespace) { continue; } //DROP THE SPACE THAT CAUSED THE BREAK
            }

            if word_width > width //A SINGLE WORD LONGER THAN THE PANE - HARD SPLIT IT
            {
                let mut chunk = String::new();

                for c in word.chars()
                {
                    let w = c.width().unwrap_or(0);

                    if column + w > width && column > 0
                    {
                        current.push(Span::styled(mem::take(&mut chunk), style));
                        out.push(Line::from(mem::take(&mut current)));
                        column = 0;
                    }

                    chunk.push(c);
                    column += w;
                }

                if !chunk.is_empty() { current.push(Span::styled(chunk, style)); }
            } else
            {
                current.push(Span::styled(word.to_owned(), style));
                column += word_width;
            }
        }
    }

    out.push(Line::from(current));
    out
}

fn split_words(text: &str) -> Vec<&str> //SPLIT INTO RUNS OF WHITESPACE AND WORDS
{
    let mut out = Vec::new();
    let mut start = 0usize;
    let mut space: Option<bool> = None;

    for (i, c) in text.char_indices()
    {
        let is_space = c.is_whitespace();

        match space
        {
            Some(prev) if prev != is_space =>
            {
                out.push(&text[start..i]);
                start = i;
            },

            _ => {}
        }

        space = Some(is_space);
    }

    if start < text.len() { out.push(&text[start..]); }

    out
}

fn text_width(text: &str) -> usize
{
    text.chars().map(|c| c.width().unwrap_or(0)).sum()
}

//SESSION STATE THAT LIVES OUTSIDE App
fn reset_session()
{
    options::set_seq(0);
    options::set_server_seq(0);
    options::set_login_state(LoginState::None);
    options::set_sending_messages(false);
    options::set_asking_password(false);
    options::set_channel(String::new());
    options::set_server_username("");

    //A HALF-FINISHED UPLOAD IS GONE WITH THE SOCKET
    client::ACTIVE_UPLOADS.lock().unwrap().clear();

    #[cfg(feature = "client_voice")]
    voice_options::set_use_voice(false);

    #[cfg(feature = "client_screen")]
    {
        screen_options::set_use_screen(false);
        screen_options::set_attach_screen(false);
        screen_options::set_monitor(None);
    }
}