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
/*
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 crossterm::event::
{
    KeyCode,
    KeyEvent,
    KeyModifiers,
};

use why2_chat::
{
    config,
    network::codes::{ ServerSetting, SettingValue },
};

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

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

use super::
{
    consts,
    state::App,
};

//ENUMS
pub enum Value
{
    //A CONFIG KEY, invert FOR A NEGATIVE ONE
    Toggle { on: bool, invert: bool },

    //THE TWO SERVER-ONLY DATATYPES, EDITED BY TYPING
    Number(i64),
    Text(String),

    #[cfg(feature = "client_voice")]
    Volume(u32), //PERCENT

    //THE cpal DEVICE ID; THE LABEL IS DISPLAY ONLY
    #[cfg(feature = "client_voice")]
    Device { id: String, input: bool }, //EMPTY ID = SYSTEM DEFAULT
}

pub enum Row
{
    Header(String),
    Item(Item),
    Action(&'static str), //A BUTTON - THE SERVER ROWS ARE THE ONLY THING THAT NEEDS ONE
}

//STRUCTS
pub struct Item
{
    pub label: String,
    pub key: String, //THE CONFIG KEY THIS ROW OWNS - client.toml's OR THE SERVER'S
    pub value: Value,
    pub hint: String,   //THE COMMENT THE SERVER SENT ALONG (EMPTY ON A CLIENT ROW)
    pub changed: bool,  //EDITED AND NOT SAVED YET
    pub restart: bool,  //STORED ON SAVE, BUT ONLY READ AT STARTUP
}

//ONE DEVICE AS THE PICKER SHOWS IT
#[derive(Clone, Default)]
pub struct DeviceEntry
{
    pub id: String,
    pub label: String,
}

pub struct Picker //DEVICE LIST OPENED ON TOP OF THE SETTINGS ROWS
{
    pub title: &'static str,
    pub entries: Vec<DeviceEntry>, //ENTRY 0 IS ALWAYS THE SYSTEM DEFAULT
    pub selected: usize,
    pub row: usize,    //THE SETTINGS ROW THAT OPENED IT
    pub offset: usize, //FIRST VISIBLE ENTRY
}

#[derive(Default)]
pub struct Devices //WHAT cpal REPORTED, ENUMERATED ONCE WHEN /settings IS TYPED
{
    #[cfg(feature = "client_voice")]
    pub input: Vec<DeviceEntry>,

    #[cfg(feature = "client_voice")]
    pub output: Vec<DeviceEntry>,
}

pub struct Settings //THE /settings OVERLAY, IN EITHER OF ITS TWO MODES
{
    pub open: bool,
    pub rows: Vec<Row>,
    pub selected: usize,
    pub picker: Option<Picker>,

    //WHERE THE VIEW STANDS, WRITTEN BY THE DRAW PATH
    pub offset: usize,
    pub page: usize, //ROWS THE LAST FRAME FIT

    //server.toml's ROWS, SAVED IN ONE GO
    pub server: bool,
    pub edit: Option<String>, //WHAT IS BEING TYPED INTO THE SELECTED ROW
    pub saving: bool,         //A SAVE IS ON THE WIRE

    save: Option<Vec<ServerSetting>>, //ROWS THE EVENT LOOP STILL HAS TO PUT ON THE WIRE

    //THE STARTUP-ONLY KEYS IN THAT SAVE
    pub restart_note: Option<String>,

    //ONE PRESS ARMS THE RESTART, THE NEXT FIRES IT
    pub confirm: bool,
    restart: bool, //ARMED, CONFIRMED

    #[cfg(feature = "client_voice")]
    devices: Devices,
}

//IMPLEMENTATIONS
impl Default for Settings
{
    fn default() -> Self { Self::new() }
}

impl Item
{
    fn client(label: &str, key: &str, value: Value) -> Self //A ROW BACKED BY client.toml
    {
        Self { label: label.to_string(), key: key.to_string(), value, hint: String::new(), changed: false, restart: false }
    }
}

impl Settings
{
    pub fn new() -> Self
    {
        Self
        {
            open: false,
            rows: Vec::new(),
            selected: 0,
            picker: None,
            offset: 0,
            page: 0,
            server: false,
            edit: None,
            saving: false,
            save: None,
            restart_note: None,
            confirm: false,
            restart: false,

            #[cfg(feature = "client_voice")]
            devices: Devices::default(),
        }
    }

    //OPEN THE OVERLAY, READING THE CONFIG ONCE
    pub fn open(&mut self, devices: Devices)
    {
        let mut rows: Vec<Row> = Vec::new();

        #[cfg(feature = "client_voice")]
        {
            rows.push(Row::Header(String::from("Audio")));

            rows.push(Row::Item(Item::client("Input device", "input_device",
                Value::Device { id: config::read_config::<String>("input_device"), input: true })));

            rows.push(Row::Item(Item::client("Output device", "output_device",
                Value::Device { id: config::read_config::<String>("output_device"), input: false })));

            rows.push(Row::Item(Item::client("Input volume", "input_volume",
                Value::Volume(voice_options::clamp_volume(config::read_config::<u32>("input_volume"))))));

            rows.push(Row::Item(Item::client("Output volume", "output_volume",
                Value::Volume(voice_options::clamp_volume(config::read_config::<u32>("output_volume"))))));

            #[cfg(feature = "client_screen")]
            rows.push(Row::Item(Item::client("Screen share volume", "screen_volume",
                Value::Volume(voice_options::clamp_volume(config::read_config::<u32>("screen_volume"))))));

            rows.push(Row::Item(Item::client("Noise suppression", "noise_suppression",
                toggle_value("noise_suppression", false))));

            rows.push(Row::Item(Item::client("Automatic gain", "automatic_gain",
                toggle_value("automatic_gain", false))));
        }

        rows.push(Row::Header(String::from("Interface")));

        rows.push(Row::Item(Item::client("Message colors", "disable_colors", toggle_value("disable_colors", true))));
        rows.push(Row::Item(Item::client("Background logo", "disable_logo", toggle_value("disable_logo", true))));
        rows.push(Row::Item(Item::client("Show images automatically", "auto_show_images",
            toggle_value("auto_show_images", false))));

        rows.push(Row::Item(Item::client("Math rendering", "render_math", toggle_value("render_math", false))));

        rows.push(Row::Item(Item::client("Show client IDs", "show_id", toggle_value("show_id", false))));

        self.rows = rows;
        self.picker = None;
        self.open = true;
        self.server = false;
        self.edit = None;
        self.saving = false;
        self.selected = 0;
        self.offset = 0;

        #[cfg(feature = "client_voice")]
        {
            self.devices = devices;
        }

        #[cfg(not(feature = "client_voice"))]
        let _ = devices;

        self.step(1); //LAND ON THE FIRST ITEM, NOT ON THE HEADER ABOVE IT
    }

    //THE SERVER'S OWN CONFIG ROWS
    pub fn open_server(&mut self, settings: Vec<ServerSetting>)
    {
        let mut rows: Vec<Row> = Vec::new();
        let mut section = String::new();

        for setting in settings
        {
            if setting.section != section
            {
                section = setting.section.clone();

                if !section.is_empty() { rows.push(Row::Header(section.clone())); }
            }

            rows.push(Row::Item(Item
            {
                label: setting.key.replace('_', " "),
                key: setting.key,
                value: match setting.value
                {
                    SettingValue::Toggle(on) => Value::Toggle { on, invert: false },
                    SettingValue::Number(number) => Value::Number(number),
                    SettingValue::Text(text) => Value::Text(text),
                },
                hint: setting.description,
                changed: false,
                restart: setting.restart, //THE SERVER NAMES ITS STARTUP-ONLY KEYS
            }));
        }

        rows.push(Row::Action(consts::SAVE_LABEL)); //NOTHING LEAVES THIS BOX UNTIL THIS IS PRESSED
        rows.push(Row::Action(consts::RESTART_LABEL));

        self.rows = rows;
        self.picker = None;
        self.open = true;
        self.server = true;
        self.edit = None;
        self.saving = false;
        self.confirm = false;
        self.selected = 0;
        self.offset = 0;

        self.step(1);
    }

    pub fn close(&mut self)
    {
        self.open = false;
        self.picker = None;
        self.edit = None;
        self.server = false;
        self.saving = false;
        self.confirm = false;
        self.rows = Vec::new();
        self.offset = 0;
        self.page = 0;
    }

    pub fn title(&self) -> String //WHAT THE BOX CALLS ITSELF
    {
        if !self.server { return String::from(" Settings "); }

        if self.saving { return String::from(" Server settings · saving… "); }

        if self.unsaved() { String::from(" Server settings · unsaved ") } else { String::from(" Server settings ") }
    }

    pub fn unsaved(&self) -> bool //A ROW HAS BEEN EDITED AND NOT SENT BACK YET
    {
        self.rows.iter().any(|row| matches!(row, Row::Item(item) if item.changed))
    }

    //THE ROWS THE EVENT LOOP STILL HAS TO SEND
    pub fn take_save(&mut self) -> Option<Vec<ServerSetting>> { self.save.take() }

    //AND A CONFIRMED RESTART
    pub fn take_restart(&mut self) -> bool { std::mem::take(&mut self.restart) }

    //TAKE THE SAVED CONFIG, KEEPING THE SELECTION
    pub fn stored(&mut self, settings: Vec<ServerSetting>)
    {
        let selected = self.selected;
        let offset = self.offset; //THE VIEW STAYS WHERE IT WAS TOO

        self.open_server(settings);
        self.selected = selected.min(self.rows.len().saturating_sub(1));
        self.offset = offset;

        //THE ROW LANDED ON MAY BE A HEADING NOW
        if matches!(self.rows.get(self.selected), Some(Row::Header(_))) { self.step(1); }
    }

    //MOVE THE SELECTION, SKIPPING HEADERS
    fn step(&mut self, delta: isize)
    {
        if self.rows.is_empty() { return; }

        let mut index = self.selected as isize;

        loop
        {
            index += delta;

            //RAN OUT OF ROWS - KEEP WHATEVER WAS SELECTED
            if index < 0 || index as usize >= self.rows.len() { return; }

            if !matches!(self.rows[index as usize], Row::Header(_))
            {
                self.selected = index as usize;
                return;
            }
        }
    }

    //PageUp/PageDown MOVE BY WHAT THE FRAME FIT
    fn page_move(&mut self, direction: isize)
    {
        if self.rows.is_empty() { return; }

        let page = self.page.max(1) as isize;

        self.offset = (self.offset as isize + direction * page).max(0) as usize;

        let target = (self.selected as isize + direction * page).clamp(0, self.rows.len() as isize - 1);

        self.land(target as usize, direction);
    }

    //LAND ON index, OR THE NEAREST NON-HEADING ROW
    fn land(&mut self, index: usize, direction: isize)
    {
        if self.rows.is_empty() { return; }

        self.selected = index.min(self.rows.len() - 1);

        if !matches!(self.rows[self.selected], Row::Header(_)) { return; }

        let before = self.selected;

        self.step(direction);

        if self.selected == before { self.step(-direction); }
    }

    //Home/End GO TO THE ENDS OF THE LIST
    fn first_row(&mut self)
    {
        self.offset = 0;
        self.land(0, 1);
    }

    fn last_row(&mut self)
    {
        self.offset = self.rows.len();
        self.land(self.rows.len().saturating_sub(1), -1);
    }

    //WHAT A STORED DEVICE ID IS CALLED
    #[cfg(feature = "client_voice")]
    pub fn device_label(&self, id: &str, input: bool) -> String
    {
        if id.is_empty() { return String::from(consts::DEFAULT_DEVICE); }

        let devices = if input { &self.devices.input } else { &self.devices.output };

        devices.iter().find(|device| device.id == id).map(|device| device.label.clone()).unwrap_or_else(|| String::from(id))
    }

    //RE-READ THE DEVICE ROWS OUT OF THE CONFIG
    #[cfg(feature = "client_voice")]
    pub fn refresh_devices(&mut self)
    {
        for row in self.rows.iter_mut()
        {
            let Row::Item(item) = row else { continue };

            if let Value::Device { input, .. } = item.value
            {
                item.value = Value::Device { id: config::read_config::<String>(&item.key), input };
            }
        }
    }
}

//READ A BOOLEAN AS THE ROW SHOWS IT
fn toggle_value(key: &str, invert: bool) -> Value
{
    let stored = config::read_config::<bool>(key);

    Value::Toggle { on: if invert { !stored } else { stored }, invert }
}

//FUNCTIONS
//PUBLIC
//ONE KEYPRESS WHILE THE OVERLAY IS UP
pub fn handle_key(app: &mut App, key: KeyEvent)
{
    //THE DEVICE PICKER OWNS THE KEYBOARD
    if app.settings.picker.is_some()
    {
        handle_picker_key(app, key);
        return;
    }

    //SO DOES A ROW THAT IS BEING TYPED INTO
    if app.settings.edit.is_some()
    {
        handle_edit_key(app, key);
        return;
    }

    //ANYTHING BUT THE CONFIRMING KEY DISARMS IT
    if !matches!(key.code, KeyCode::Enter | KeyCode::Char(' ')) { app.settings.confirm = false; }

    //Ctrl+S SAVES FROM ANY ROW
    if app.settings.server && key.modifiers.contains(KeyModifiers::CONTROL) && key.code == KeyCode::Char('s')
    {
        save(app);
        return;
    }

    match key.code
    {
        KeyCode::Esc => app.settings.close(),

        KeyCode::Up => app.settings.step(-1),
        KeyCode::Down => app.settings.step(1),

        KeyCode::PageUp => app.settings.page_move(-1),
        KeyCode::PageDown => app.settings.page_move(1),

        KeyCode::Home => app.settings.first_row(),
        KeyCode::End => app.settings.last_row(),

        KeyCode::Left => adjust(app, -1),
        KeyCode::Right => adjust(app, 1),

        KeyCode::Enter | KeyCode::Char(' ') => activate(app),

        _ => {},
    }
}

//MOUSE WHEEL - MOVES WHICHEVER LIST IS IN FRONT
pub fn scroll(app: &mut App, delta: isize)
{
    if app.settings.edit.is_some() { return; } //A ROW BEING TYPED INTO IS NOT SCROLLED AWAY FROM

    match app.settings.picker.as_mut()
    {
        Some(picker) =>
        {
            let next = picker.selected as isize + delta;
            picker.selected = next.clamp(0, picker.entries.len() as isize - 1) as usize;
        },

        None => app.settings.step(delta),
    }
}

//PRIVATE
fn handle_picker_key(app: &mut App, key: KeyEvent)
{
    //CLOSING THE PICKER TAKES IT OUT OF App
    match key.code
    {
        KeyCode::Esc =>
        {
            app.settings.picker = None;
            return;
        },

        KeyCode::Enter =>
        {
            let Some(picker) = app.settings.picker.take() else { return };

            //ENTRY 0 IS THE SYSTEM DEFAULT
            let chosen = picker.entries.get(picker.selected).map(|entry| entry.id.clone()).unwrap_or_default();

            set_device(app, picker.row, chosen);
            return;
        },

        _ => {},
    }

    let page = app.settings.page.max(1) as isize; //READ BEFORE THE BORROW BELOW TAKES app.settings

    let Some(picker) = app.settings.picker.as_mut() else { return };

    match key.code
    {
        KeyCode::Up => picker.selected = if picker.selected == 0 { picker.entries.len() - 1 } else { picker.selected - 1 },
        KeyCode::Down => picker.selected = (picker.selected + 1) % picker.entries.len(),

        //THE PICKER HAS NO HEADINGS, SO A PAGE IS A JUMP
        KeyCode::PageUp | KeyCode::PageDown =>
        {
            let direction: isize = if key.code == KeyCode::PageUp { -1 } else { 1 };

            picker.offset = (picker.offset as isize + direction * page).max(0) as usize;

            picker.selected = (picker.selected as isize + direction * page)
                .clamp(0, picker.entries.len() as isize - 1) as usize;
        },

        KeyCode::Home => { picker.selected = 0; picker.offset = 0; },
        KeyCode::End => { picker.selected = picker.entries.len() - 1; picker.offset = picker.entries.len(); },

        _ => {},
    }
}

//TYPING INTO A Number/Text ROW
fn handle_edit_key(app: &mut App, key: KeyEvent)
{
    match key.code
    {
        KeyCode::Esc => app.settings.edit = None,

        KeyCode::Enter => commit_edit(app),

        KeyCode::Backspace => { if let Some(edit) = app.settings.edit.as_mut() { edit.pop(); } },

        KeyCode::Char(c) =>
        {
            //A NUMBER ROW ONLY TAKES DIGITS AND A LEADING -
            let numeric = matches!(app.settings.rows.get(app.settings.selected), Some(Row::Item(item))
                if matches!(item.value, Value::Number(_)));

            if let Some(edit) = app.settings.edit.as_mut()
                && (!numeric || c.is_ascii_digit() || (c == '-' && edit.is_empty()))
            {
                edit.push(c);
            }
        },

        _ => {},
    }
}

fn commit_edit(app: &mut App) //KEEP WHAT WAS TYPED, IF THE ROW CAN HOLD IT
{
    let Some(edit) = app.settings.edit.take() else { return };

    let Some(Row::Item(item)) = app.settings.rows.get_mut(app.settings.selected) else { return };

    match &item.value
    {
        //AN UNPARSEABLE NUMBER IS NOT A CHANGE
        Value::Number(current) => match edit.trim().parse::<i64>()
        {
            Ok(number) if number != *current =>
            {
                item.value = Value::Number(number);
                item.changed = true;
            },

            _ => {},
        },

        Value::Text(current) => if edit != *current
        {
            item.value = Value::Text(edit);
            item.changed = true;
        },

        _ => {},
    }
}

//WHAT THE SELECTED ROW HOLDS, COPIED OUT
enum Selected
{
    Toggle(bool),
    Number(i64),
    Text(String),
    Action(&'static str), //WHICH BUTTON - THE SERVER ROWS HAVE TWO OF THEM

    #[cfg(feature = "client_voice")]
    Volume(String, u32),

    #[cfg(feature = "client_voice")]
    Device(String, bool),
}

fn selected(app: &App) -> Option<Selected>
{
    match app.settings.rows.get(app.settings.selected)?
    {
        Row::Header(_) => None,
        Row::Action(label) => Some(Selected::Action(label)),

        Row::Item(item) => Some(match &item.value
        {
            Value::Toggle { on, .. } => Selected::Toggle(*on),
            Value::Number(number) => Selected::Number(*number),
            Value::Text(text) => Selected::Text(text.clone()),

            #[cfg(feature = "client_voice")]
            Value::Volume(percent) => Selected::Volume(item.key.clone(), *percent),

            #[cfg(feature = "client_voice")]
            Value::Device { id, input } => Selected::Device(id.clone(), *input),
        }),
    }
}

//LEFT/RIGHT: SLIDE, FLIP, STEP OR CYCLE A ROW
fn adjust(app: &mut App, direction: i32)
{
    let row = app.settings.selected;

    match selected(app)
    {
        //EITHER DIRECTION FLIPS A TOGGLE
        Some(Selected::Toggle(on)) => if (direction > 0) != on { toggle(app) },

        Some(Selected::Number(number)) =>
        {
            let next = number.saturating_add(direction as i64);

            if let Some(Row::Item(item)) = app.settings.rows.get_mut(row)
            {
                item.value = Value::Number(next);
                item.changed = true;
            }
        },

        //A FREE-FORM STRING IS TYPED, NOT STEPPED
        Some(Selected::Text(_)) | Some(Selected::Action(_)) => {},

        #[cfg(feature = "client_voice")]
        Some(Selected::Volume(key, percent)) =>
        {
            let next = if direction > 0
            {
                voice_options::clamp_volume(percent.saturating_add(consts::VOLUME_STEP))
            } else
            {
                percent.saturating_sub(consts::VOLUME_STEP)
            };

            if next == percent { return; }

            if let Some(Row::Item(item)) = app.settings.rows.get_mut(row) { item.value = Value::Volume(next); }

            config::client_write_int(&key, next as i64);
            apply_volume(&key, next);
        },

        #[cfg(feature = "client_voice")]
        Some(Selected::Device(id, input)) =>
        {
            let entries = device_entries(app, input);
            let current = entries.iter().position(|entry| entry.id == id).unwrap_or(0);

            let next = (current as isize + direction as isize).rem_euclid(entries.len() as isize) as usize;
            let chosen = entries[next].id.clone();

            set_device(app, row, chosen);
        },

        None => {},
    }
}

//ENTER/SPACE: FLIP, TYPE, PRESS OR OPEN A ROW
fn activate(app: &mut App)
{
    let _row = app.settings.selected; //ONLY THE AUDIO ROWS NEED TO KNOW WHICH ROW THEY ARE

    match selected(app)
    {
        Some(Selected::Toggle(_)) => toggle(app),

        Some(Selected::Number(number)) => app.settings.edit = Some(number.to_string()),
        Some(Selected::Text(text)) => app.settings.edit = Some(text),

        Some(Selected::Action(consts::RESTART_LABEL)) => restart(app),
        Some(Selected::Action(_)) => save(app),

        #[cfg(feature = "client_voice")]
        Some(Selected::Volume(..)) => adjust(app, 1),

        #[cfg(feature = "client_voice")]
        Some(Selected::Device(id, input)) =>
        {
            let entries = device_entries(app, input);

            app.settings.picker = Some(Picker
            {
                title: if input { " Input device " } else { " Output device " },
                selected: entries.iter().position(|entry| entry.id == id).unwrap_or(0),
                entries,
                row: _row,
                offset: 0,
            });
        },

        None => {},
    }
}

//ARM THE RESTART, THEN FIRE IT
fn restart(app: &mut App)
{
    if !app.settings.server || app.settings.saving || app.settings.unsaved() { return; }

    //THE FIRST PRESS ONLY ARMS IT
    if !app.settings.confirm
    {
        app.settings.confirm = true;
        return;
    }

    app.settings.restart = true;

    //THE SERVER GOES DOWN WITH THIS
    app.settings.close();
}

//HAND THE EDITED ROWS TO THE EVENT LOOP
fn save(app: &mut App)
{
    if !app.settings.server { return; }

    let changed: Vec<ServerSetting> = app.settings.rows.iter().filter_map(|row|
    {
        let Row::Item(item) = row else { return None };

        if !item.changed { return None; }

        Some(ServerSetting
        {
            key: item.key.clone(),
            value: match &item.value
            {
                Value::Toggle { on, .. } => SettingValue::Toggle(*on),
                Value::Number(number) => SettingValue::Number(*number),
                Value::Text(text) => SettingValue::Text(text.clone()),

                #[allow(unreachable_patterns)] //THE OTHER VARIANTS ONLY EXIST ON A CLIENT ROW
                _ => return None,
            },

            //THE SERVER ALREADY KNOWS THESE
            section: String::new(),
            description: String::new(),
            restart: false,
        })
    }).collect();

    if changed.is_empty() { return; }

    //A STARTUP-ONLY KEY IS STORED LIKE ANY OTHER
    let restart: Vec<&str> = app.settings.rows.iter().filter_map(|row| match row
    {
        Row::Item(item) if item.changed && item.restart => Some(item.key.as_str()),
        _ => None,
    }).collect();

    app.settings.restart_note = (!restart.is_empty()).then(|| restart.join(", "));

    app.settings.saving = true;
    app.settings.save = Some(changed);
}

fn toggle(app: &mut App)
{
    let server = app.settings.server;

    //FLIP THE ROW, THEN LET GO OF IT
    let changed = match app.settings.rows.get_mut(app.settings.selected)
    {
        Some(Row::Item(item)) => match &item.value
        {
            Value::Toggle { on, invert } =>
            {
                let (next, invert) = (!*on, *invert);
                item.value = Value::Toggle { on: next, invert };
                item.changed = item.changed || server;

                Some((item.key.clone(), next, invert))
            },

            #[allow(unreachable_patterns)] //THE OTHER VARIANTS ARE NOT TOGGLES
            _ => None,
        },

        _ => None,
    };

    let Some((key, next, invert)) = changed else { return };

    //A SERVER ROW GOES BACK OVER THE WIRE ON Save
    if server { return; }

    config::client_write_bool(&key, if invert { !next } else { next });

    //THE INTERFACE ROWS ARE READ THROUGH App::theme
    app.reload_theme();

    #[cfg(feature = "client_voice")]
    match key.as_str()
    {
        "noise_suppression" => voice_options::set_noise_suppression(next),
        "automatic_gain" => voice_options::set_automatic_gain(next),
        _ => {},
    }
}

#[cfg(feature = "client_voice")]
fn set_device(app: &mut App, row: usize, chosen: String)
{
    let Some(Row::Item(item)) = app.settings.rows.get_mut(row) else { return };

    let Value::Device { id, input } = &item.value else { return };

    if *id == chosen { return; }

    let (key, input) = (item.key.clone(), *input);
    item.value = Value::Device { id: chosen.clone(), input };

    config::client_write(&key, &chosen);

    //A RUNNING VOICE SESSION REBUILDS ITS STREAMS
    voice_options::mark_devices_changed();
}

#[cfg(not(feature = "client_voice"))]
fn set_device(_app: &mut App, _row: usize, _chosen: String) {}

//THE SYSTEM DEFAULT PLUS EVERY REPORTED DEVICE
#[cfg(feature = "client_voice")]
fn device_entries(app: &App, input: bool) -> Vec<DeviceEntry>
{
    let devices = if input { &app.settings.devices.input } else { &app.settings.devices.output };

    let mut entries = vec![DeviceEntry { id: String::new(), label: String::from(consts::DEFAULT_DEVICE) }];
    entries.extend(devices.iter().cloned());

    //A CONFIGURED BUT UNPLUGGED DEVICE KEEPS ITS ROW
    let configured = config::read_config::<String>(if input { "input_device" } else { "output_device" });
    if !configured.is_empty() && !entries.iter().any(|entry| entry.id == configured)
    {
        entries.push(DeviceEntry { label: configured.clone(), id: configured });
    }

    entries
}

#[cfg(feature = "client_voice")]
fn apply_volume(key: &str, percent: u32) //LIVE-UPDATE THE RUNNING AUDIO STREAMS
{
    match key
    {
        "input_volume" => voice_options::set_input_volume(percent),
        "output_volume" => voice_options::set_output_volume(percent),

        #[cfg(feature = "client_screen")]
        "screen_volume" => screen_options::set_screen_volume(percent),
        _ => {},
    }
}