iamb 0.0.12-alpha.1

A Matrix chat client that uses Vim keybindings
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
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
//! # Logic for loading and validating application configuration
use std::borrow::Cow;
use std::collections::hash_map::DefaultHasher;
use std::collections::{BTreeMap, HashMap};
use std::env;
use std::fmt;
use std::fs::File;
use std::hash::{Hash, Hasher};
use std::io::{BufReader, BufWriter, Write};
use std::path::{Path, PathBuf};
use std::process;
use std::str::FromStr;

use clap::Parser;
use matrix_sdk::EncryptionState;
use matrix_sdk::authentication::matrix::MatrixSession;
use matrix_sdk::reqwest::header::{HeaderMap, HeaderValue};
use matrix_sdk::ruma::{OwnedDeviceId, OwnedRoomAliasId, OwnedRoomId, OwnedUserId, UserId};
use ratatui::style::{Color, Modifier as StyleModifier, Style};
use ratatui::text::Span;
use ratatui_image::picker::ProtocolType;
use serde::{Deserialize, Deserializer, Serialize, de::Error as SerdeError, de::Visitor};
use url::Url;

use modalkit::env::vim::VimMode;
use modalkit::key::TerminalKey;
use modalkit::keybindings::InputKey;
use modalkit::prelude::Axis;

use super::base::{
    IambError,
    IambId,
    RoomInfo,
    SortColumn,
    SortFieldRoom,
    SortFieldUser,
    SortOrder,
};

type Macros = HashMap<VimModes, HashMap<Keys, Keys>>;

macro_rules! usage {
    ( $($args: tt)* ) => {
        println!($($args)*);
        process::exit(2);
    }
}

const DEFAULT_MEMBERS_SORT: [SortColumn<SortFieldUser>; 2] = [
    SortColumn(SortFieldUser::PowerLevel, SortOrder::Ascending),
    SortColumn(SortFieldUser::UserId, SortOrder::Ascending),
];

const DEFAULT_ROOM_SORT: [SortColumn<SortFieldRoom>; 5] = [
    SortColumn(SortFieldRoom::Favorite, SortOrder::Ascending),
    SortColumn(SortFieldRoom::Invite, SortOrder::Ascending),
    SortColumn(SortFieldRoom::LowPriority, SortOrder::Ascending),
    SortColumn(SortFieldRoom::Unread, SortOrder::Ascending),
    SortColumn(SortFieldRoom::Name, SortOrder::Ascending),
];

const DEFAULT_ENABLE_TITLE: bool = true;
const DEFAULT_ENC_INDICATOR_LOC: EncryptionIndicatorLocation = EncryptionIndicatorLocation::PROMPT;
const DEFAULT_REQ_TIMEOUT: u64 = 120;

const DEFAULT_LOG_LEVEL: &str = if cfg!(feature = "max_level_error") {
    "error"
} else {
    "warn"
};

const COLORS: [Color; 13] = [
    Color::Blue,
    Color::Cyan,
    Color::Green,
    Color::LightBlue,
    Color::LightGreen,
    Color::LightCyan,
    Color::LightMagenta,
    Color::LightRed,
    Color::LightYellow,
    Color::Magenta,
    Color::Red,
    Color::Reset,
    Color::Yellow,
];

pub fn user_color(user: &str) -> Color {
    let mut hasher = DefaultHasher::new();
    user.hash(&mut hasher);
    let color = hasher.finish() as usize % COLORS.len();

    COLORS[color]
}

pub fn user_style_from_color(color: Color) -> Style {
    Style::default().fg(color).add_modifier(StyleModifier::BOLD)
}

fn is_profile_char(c: char) -> bool {
    c.is_ascii_alphanumeric() || c == '.' || c == '-'
}

fn default_true() -> bool {
    true
}

fn validate_profile_name(name: &str) -> bool {
    if name.is_empty() {
        return false;
    }

    let mut chars = name.chars();

    if !chars.next().is_some_and(|c| c.is_ascii_alphanumeric()) {
        return false;
    }

    name.chars().all(is_profile_char)
}

fn validate_profile_names(names: &BTreeMap<String, ProfileConfig>) {
    for name in names.keys() {
        if validate_profile_name(name.as_str()) {
            continue;
        }

        usage!(
            "{:?} is not a valid profile name.\n\n\
            Profile names can only contain the characters \
            a-z, A-Z, and 0-9. Period (.) and hyphen (-) are allowed after the first character.",
            name
        );
    }
}

fn deserialize_from_str_opt<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
where
    D: serde::de::Deserializer<'de>,
    T: FromStr,
    <T as FromStr>::Err: fmt::Display,
{
    <Option<&'de str>>::deserialize(deserializer)?
        .map(|s| {
            let t = T::from_str(s);
            t.map_err(|e| D::Error::custom(format!("failed to parse string: {e}")))
        })
        .transpose()
}

const VERSION: &str = match option_env!("VERGEN_GIT_SHA") {
    None => env!("CARGO_PKG_VERSION"),
    Some(_) => concat!(env!("CARGO_PKG_VERSION"), " (", env!("VERGEN_GIT_SHA"), ")"),
};

#[derive(Parser)]
#[clap(version = VERSION, about, long_about = None)]
#[clap(propagate_version = true)]
pub struct Iamb {
    #[clap(long, value_parser)]
    pub completions: Option<clap_complete::Shell>,

    #[clap(short = 'P', long, value_parser)]
    pub profile: Option<String>,

    #[clap(short = 'C', long, value_parser)]
    pub config_directory: Option<PathBuf>,
}

#[derive(thiserror::Error, Debug)]
pub enum ConfigError {
    #[error("Error reading configuration file: {0}")]
    IO(#[from] std::io::Error),

    #[error("Error loading configuration file: {0}")]
    Invalid(#[from] toml::de::Error),

    #[error("Error loading JSON configuration file: {0}")]
    InvalidJSON(#[from] serde_json::Error),
}

macro_rules! deserialize_str_with_visitor {
    ($t: ident, $v: ident) => {
        impl<'de> Deserialize<'de> for $t {
            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
            where
                D: Deserializer<'de>,
            {
                deserializer.deserialize_str($v)
            }
        }
    };
}

deserialize_str_with_visitor!(Keys, KeysVisitor);
deserialize_str_with_visitor!(VimModes, VimModesVisitor);
deserialize_str_with_visitor!(UserColor, UserColorVisitor);
deserialize_str_with_visitor!(EncryptionIndicatorLocation, EncryptionIndicatorLocationVisitor);
deserialize_str_with_visitor!(NotifyVia, NotifyViaVisitor);
deserialize_str_with_visitor!(ProxyUrl, ProxyUrlVisitor);

#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct Keys(pub Vec<TerminalKey>, pub String);
pub struct KeysVisitor;

impl Visitor<'_> for KeysVisitor {
    type Value = Keys;

    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        formatter.write_str("a valid Vim mode (e.g. \"normal\" or \"insert\")")
    }

    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
    where
        E: SerdeError,
    {
        match TerminalKey::from_macro_str(value) {
            Ok(keys) => Ok(Keys(keys, value.to_string())),
            Err(e) => Err(E::custom(format!("Could not parse key sequence: {e}"))),
        }
    }
}

#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct VimModes(pub Vec<VimMode>);
pub struct VimModesVisitor;

impl Visitor<'_> for VimModesVisitor {
    type Value = VimModes;

    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        formatter.write_str("a valid Vim mode (e.g. \"normal\" or \"insert\")")
    }

    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
    where
        E: SerdeError,
    {
        let mut modes = vec![];

        for mode in value.split('|') {
            let mode = match mode.to_ascii_lowercase().as_str() {
                "insert" | "i" => VimMode::Insert,
                "normal" | "n" => VimMode::Normal,
                "visual" | "v" => VimMode::Visual,
                "command" | "c" => VimMode::Command,
                "select" => VimMode::Select,
                "operator-pending" => VimMode::OperationPending,
                _ => return Err(E::custom("Could not parse into a Vim mode")),
            };

            modes.push(mode);
        }

        Ok(VimModes(modes))
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct UserColor(pub Color);
pub struct UserColorVisitor;

impl Visitor<'_> for UserColorVisitor {
    type Value = UserColor;

    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        formatter.write_str("a valid color")
    }

    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
    where
        E: SerdeError,
    {
        match value {
            "none" => Ok(UserColor(Color::Reset)),
            "red" => Ok(UserColor(Color::Red)),
            "black" => Ok(UserColor(Color::Black)),
            "green" => Ok(UserColor(Color::Green)),
            "yellow" => Ok(UserColor(Color::Yellow)),
            "blue" => Ok(UserColor(Color::Blue)),
            "magenta" => Ok(UserColor(Color::Magenta)),
            "cyan" => Ok(UserColor(Color::Cyan)),
            "gray" => Ok(UserColor(Color::Gray)),
            "dark-gray" => Ok(UserColor(Color::DarkGray)),
            "light-red" => Ok(UserColor(Color::LightRed)),
            "light-green" => Ok(UserColor(Color::LightGreen)),
            "light-yellow" => Ok(UserColor(Color::LightYellow)),
            "light-blue" => Ok(UserColor(Color::LightBlue)),
            "light-magenta" => Ok(UserColor(Color::LightMagenta)),
            "light-cyan" => Ok(UserColor(Color::LightCyan)),
            "white" => Ok(UserColor(Color::White)),
            _ => Err(E::custom("Could not parse color")),
        }
    }
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct Session {
    access_token: String,
    refresh_token: Option<String>,
    user_id: OwnedUserId,
    device_id: OwnedDeviceId,
}

impl From<Session> for MatrixSession {
    fn from(session: Session) -> Self {
        MatrixSession {
            tokens: matrix_sdk::authentication::SessionTokens {
                access_token: session.access_token,
                refresh_token: session.refresh_token,
            },
            meta: matrix_sdk::SessionMeta {
                user_id: session.user_id,
                device_id: session.device_id,
            },
        }
    }
}

impl From<MatrixSession> for Session {
    fn from(session: MatrixSession) -> Self {
        Session {
            access_token: session.tokens.access_token,
            refresh_token: session.tokens.refresh_token,
            user_id: session.meta.user_id,
            device_id: session.meta.device_id,
        }
    }
}

#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
pub struct UserDisplayTunables {
    pub color: Option<UserColor>,
    pub name: Option<String>,
}

pub type UserOverrides = HashMap<OwnedUserId, UserDisplayTunables>;

fn merge_maps<K, V>(
    profile: Option<HashMap<K, V>>,
    global: Option<HashMap<K, V>>,
) -> Option<HashMap<K, V>>
where
    K: Eq + Hash,
{
    match (global, profile) {
        (Some(m), None) | (None, Some(m)) => Some(m),
        (Some(mut global), Some(profile)) => {
            for (k, v) in profile {
                global.insert(k, v);
            }

            Some(global)
        },
        (None, None) => None,
    }
}

#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq)]
#[serde(rename_all = "kebab-case")]
#[repr(u8)]
pub enum ReadReceiptTrigger {
    /// Update read receipts for a room when a window for it is focused, and it is scrolled to the
    /// last message.
    #[default]
    Focused,
    /// Update read receipts for a room when a window for it is visible, and it is scrolled to the
    /// last message.
    Visible,
    /// Update read receipts for a room whenever some portion of its scrollback is rendered.
    Scrollback,
    /// Update read receipts for a room once the user sends a message to it.
    Message,
}

impl ReadReceiptTrigger {
    /// Whether to update read receipts when a room is being rendered.
    pub fn on_render(&self, last_visible: bool, room_focused: bool) -> bool {
        match self {
            Self::Scrollback => true,
            Self::Focused => last_visible && room_focused,
            Self::Visible => last_visible,
            Self::Message => false,
        }
    }

    pub fn on_message(&self) -> bool {
        matches!(self, Self::Message)
    }
}

#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq)]
#[serde(rename_all = "kebab-case")]
#[repr(u8)]
pub enum EncryptionIndicator {
    /// Always indicate the room's encryption status.
    #[default]
    Enabled,
    /// Never indicate the room's encryption status.
    Disabled,
    /// Only indicate the room's encryption status when it is encrypted.
    OnlyEncrypted,
    /// Only indicate the room's encryption status when it is unencrypted.
    OnlyUnencrypted,
}

bitflags::bitflags! {
    /// Available options for where to show the encryption status indicator.
    #[derive(Clone, Debug, Eq, PartialEq)]
    pub struct EncryptionIndicatorLocation: u8 {
        const NONE   = 0b00000000;
        const TITLE  = 0b00000001;
        const PROMPT = 0b00000010;
    }
}

pub struct EncryptionIndicatorLocationVisitor;

impl Visitor<'_> for EncryptionIndicatorLocationVisitor {
    type Value = EncryptionIndicatorLocation;

    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        formatter.write_str("a valid encryption indicator location (e.g. \"title\" or \"prompt\")")
    }

    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
    where
        E: SerdeError,
    {
        let mut location = EncryptionIndicatorLocation::NONE;

        for value in value.split('|') {
            match value.to_ascii_lowercase().as_str() {
                "title" => location |= EncryptionIndicatorLocation::TITLE,
                "prompt" => location |= EncryptionIndicatorLocation::PROMPT,
                _ => {
                    return Err(E::custom("could not parse into an encryption indicator location"));
                },
            };
        }

        Ok(location)
    }
}

#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum UserDisplayStyle {
    // The Matrix username for the sender (e.g., "@user:example.com").
    #[default]
    Username,

    // The localpart of the Matrix username (e.g., "@user").
    LocalPart,

    // The display name for the Matrix user, calculated according to the rules from the spec.
    //
    // This is usually something like "Ada Lovelace" if the user has configured a display name, but
    // it can wind up being the Matrix username if there are display name collisions in the room,
    // in order to avoid any confusion.
    DisplayName,
}

#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum SplitDirection {
    #[default]
    Horizontal,
    Vertical,
}

impl SplitDirection {
    pub fn to_axis(self) -> Axis {
        match self {
            Self::Horizontal => Axis::Horizontal,
            Self::Vertical => Axis::Vertical,
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct NotifyVia {
    /// Deliver notifications via terminal bell.
    pub bell: bool,
    /// Deliver notifications via desktop mechanism.
    #[cfg(feature = "desktop")]
    pub desktop: bool,
}
pub struct NotifyViaVisitor;

impl Default for NotifyVia {
    fn default() -> Self {
        Self {
            bell: cfg!(not(feature = "desktop")),
            #[cfg(feature = "desktop")]
            desktop: true,
        }
    }
}

impl Visitor<'_> for NotifyViaVisitor {
    type Value = NotifyVia;

    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        formatter.write_str("a valid notify destination (e.g. \"bell\" or \"desktop\")")
    }

    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
    where
        E: SerdeError,
    {
        let mut via = NotifyVia {
            bell: false,
            #[cfg(feature = "desktop")]
            desktop: false,
        };

        for value in value.split('|') {
            match value.to_ascii_lowercase().as_str() {
                "bell" => {
                    via.bell = true;
                },
                #[cfg(feature = "desktop")]
                "desktop" => {
                    via.desktop = true;
                },
                #[cfg(not(feature = "desktop"))]
                "desktop" => {
                    return Err(E::custom("desktop notification support was compiled out"));
                },
                _ => return Err(E::custom("could not parse into a notify destination")),
            };
        }

        Ok(via)
    }
}

#[derive(Clone, Debug, Default, Deserialize)]
pub struct Encryption {
    indicator: Option<EncryptionIndicator>,
    indicator_location: Option<EncryptionIndicatorLocation>,
}

impl Encryption {
    fn merge(profile: Self, global: Self) -> Self {
        Encryption {
            indicator: profile.indicator.or(global.indicator),
            indicator_location: profile.indicator_location.or(global.indicator_location),
        }
    }

    pub fn values(self) -> EncryptionValues {
        EncryptionValues {
            indicator: self.indicator.unwrap_or_default(),
            indicator_location: self.indicator_location.unwrap_or(DEFAULT_ENC_INDICATOR_LOC),
        }
    }
}

#[derive(Clone, Debug)]
pub struct EncryptionValues {
    pub indicator: EncryptionIndicator,
    pub indicator_location: EncryptionIndicatorLocation,
}

impl EncryptionValues {
    pub fn get_indicator(
        &self,
        location: EncryptionIndicatorLocation,
        state: EncryptionState,
    ) -> Option<Span<'static>> {
        if !self.indicator_location.contains(location) {
            return None;
        }

        let indicator = match (self.indicator, state) {
            (EncryptionIndicator::Disabled, _) |
            (EncryptionIndicator::OnlyUnencrypted, EncryptionState::Encrypted) |
            (EncryptionIndicator::OnlyEncrypted, EncryptionState::NotEncrypted) => {
                // User doesn't want to see anything:
                return None;
            },
            (
                EncryptionIndicator::Enabled | EncryptionIndicator::OnlyEncrypted,
                EncryptionState::Encrypted,
            ) => {
                // Green lock:
                Span::styled("\u{1F512}\u{FE0E} ", Style::new().fg(Color::LightGreen))
            },
            (
                EncryptionIndicator::Enabled | EncryptionIndicator::OnlyUnencrypted,
                EncryptionState::NotEncrypted,
            ) => {
                // Red unlocked lock:
                Span::styled("\u{1F513}\u{FE0E} ", Style::new().fg(Color::Red))
            },

            (_, EncryptionState::Unknown) => {
                // Yellow question mark:
                Span::styled("? ", Style::new().fg(Color::Yellow))
            },
        };

        Some(indicator)
    }
}

#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub enum ProxyUrl {
    Disabled,
    Endpoint(Url),
    #[default]
    System,
}

pub struct ProxyUrlVisitor;

impl Visitor<'_> for ProxyUrlVisitor {
    type Value = ProxyUrl;

    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        formatter.write_str("a valid proxy URL (e.g. \"socks5://localhost:9050\")")
    }

    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
    where
        E: SerdeError,
    {
        if value.is_empty() {
            return Ok(ProxyUrl::Disabled);
        }

        match Url::from_str(value) {
            Ok(uri) => Ok(ProxyUrl::Endpoint(uri)),
            Err(e) => Err(E::custom(format!("could not parse {value:?}: {e}"))),
        }
    }
}

#[derive(Clone, Debug, Default, Deserialize)]
pub struct Proxy {
    /// How and where to proxy the client's requests to the homeserver.
    url: Option<ProxyUrl>,

    /// An optional value to include in the `Proxy-Authorization` header.
    #[serde(default, deserialize_with = "deserialize_from_str_opt")]
    auth: Option<HeaderValue>,

    /// Optional headers to include in requests sent to the proxy.
    #[serde(default, with = "http_serde::header_map")]
    headers: HeaderMap,
}

impl Proxy {
    pub fn values(self) -> ProxyValues {
        ProxyValues {
            url: self.url.unwrap_or_default(),
            auth: self.auth,
            headers: self.headers,
        }
    }
}

#[derive(Clone, Debug, Default)]
pub struct ProxyValues {
    pub url: ProxyUrl,
    pub auth: Option<HeaderValue>,
    pub headers: HeaderMap,
}

#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
pub struct Mouse {
    #[serde(default)]
    pub enabled: bool,
}

#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
pub struct Notifications {
    #[serde(default)]
    pub enabled: bool,
    #[serde(default)]
    pub via: NotifyVia,
    #[serde(default = "default_true")]
    pub show_message: bool,
    #[serde(default)]
    pub sound_hint: Option<String>,
}

#[derive(Clone)]
pub struct ImagePreviewValues {
    pub lazy_load: bool,
    pub size: ImagePreviewSize,
    pub protocol: Option<ImagePreviewProtocolValues>,
}

#[derive(Clone, Debug, Default, Deserialize)]
pub struct ImagePreview {
    pub lazy_load: Option<bool>,
    pub size: Option<ImagePreviewSize>,
    pub protocol: Option<ImagePreviewProtocolValues>,
}

impl ImagePreview {
    fn values(self) -> ImagePreviewValues {
        ImagePreviewValues {
            lazy_load: self.lazy_load.unwrap_or(true),
            size: self.size.unwrap_or_default(),
            protocol: self.protocol,
        }
    }
}

#[derive(Clone, Copy, Deserialize, Debug)]
pub struct ImagePreviewSize {
    pub width: usize,
    pub height: usize,
}

impl Default for ImagePreviewSize {
    fn default() -> Self {
        ImagePreviewSize { width: 66, height: 10 }
    }
}

#[derive(Clone, Debug, Deserialize)]
pub struct ImagePreviewProtocolValues {
    pub r#type: Option<ProtocolType>,
    pub font_size: Option<(u16, u16)>,
}

#[derive(Clone)]
pub struct SortValues {
    pub chats: Vec<SortColumn<SortFieldRoom>>,
    pub dms: Vec<SortColumn<SortFieldRoom>>,
    pub rooms: Vec<SortColumn<SortFieldRoom>>,
    pub spaces: Vec<SortColumn<SortFieldRoom>>,
    pub members: Vec<SortColumn<SortFieldUser>>,
}

#[derive(Clone, Debug, Default, Deserialize)]
pub struct SortOverrides {
    pub chats: Option<Vec<SortColumn<SortFieldRoom>>>,
    pub dms: Option<Vec<SortColumn<SortFieldRoom>>>,
    pub rooms: Option<Vec<SortColumn<SortFieldRoom>>>,
    pub spaces: Option<Vec<SortColumn<SortFieldRoom>>>,
    pub members: Option<Vec<SortColumn<SortFieldUser>>>,
}

impl SortOverrides {
    fn merge(profile: Self, global: Self) -> Self {
        Self {
            chats: profile.chats.or(global.chats),
            dms: profile.dms.or(global.dms),
            rooms: profile.rooms.or(global.rooms),
            spaces: profile.spaces.or(global.spaces),
            members: profile.members.or(global.members),
        }
    }

    pub fn values(self) -> SortValues {
        let rooms = self.rooms.unwrap_or_else(|| Vec::from(DEFAULT_ROOM_SORT));
        let chats = self.chats.unwrap_or_else(|| rooms.clone());
        let dms = self.dms.unwrap_or_else(|| rooms.clone());
        let spaces = self.spaces.unwrap_or_else(|| rooms.clone());
        let members = self.members.unwrap_or_else(|| Vec::from(DEFAULT_MEMBERS_SORT));

        SortValues { rooms, members, chats, dms, spaces }
    }
}

#[derive(Clone, Debug, Default, Deserialize)]
pub struct Terminal {
    pub cursor_shape: Option<CursorShape>,
    pub enable_extended_keys: Option<bool>,
    pub enable_title: Option<bool>,
}

impl Terminal {
    fn merge(profile: Self, global: Self) -> Self {
        Self {
            cursor_shape: profile.cursor_shape.or(global.cursor_shape),
            enable_extended_keys: profile.enable_extended_keys.or(global.enable_extended_keys),
            enable_title: profile.enable_title.or(global.enable_title),
        }
    }

    pub fn values(self) -> TerminalValues {
        TerminalValues {
            cursor_shape: self.cursor_shape.unwrap_or_default(),
            enable_extended_keys: self.enable_extended_keys,
            enable_title: self.enable_title.unwrap_or(DEFAULT_ENABLE_TITLE),
        }
    }
}

#[derive(Clone, Debug)]
pub struct TerminalValues {
    pub cursor_shape: CursorShape,
    pub enable_extended_keys: Option<bool>,
    pub enable_title: bool,
}

/// The configuration settings to run with, after merging the
/// per-profile overrides on top of the global settings.
#[derive(Clone)]
pub struct TunableValues {
    pub encryption: EncryptionValues,
    pub default_markup: MarkupFormat,
    pub log_level: String,
    pub max_log_files: usize,
    pub message_shortcode_display: bool,
    pub normal_after_send: bool,
    pub proxy: ProxyValues,
    pub reaction_display: bool,
    pub reaction_shortcode_display: bool,
    pub read_receipt_send: bool,
    pub read_receipt_trigger: ReadReceiptTrigger,
    pub read_receipt_display: bool,
    pub request_timeout: u64,
    pub sort: SortValues,
    pub state_event_display: bool,
    pub typing_notice_send: bool,
    pub typing_notice_display: bool,
    pub users: UserOverrides,
    pub username_display: UserDisplayStyle,
    pub message_user_color: bool,
    pub default_room: Option<String>,
    pub open_command: Option<Vec<String>>,
    pub mouse: Mouse,
    pub notifications: Notifications,
    pub terminal: TerminalValues,
    pub image_preview: Option<ImagePreviewValues>,
    pub user_gutter_width: usize,
    pub external_edit_file_suffix: String,
    pub tabstop: usize,
    pub members_split: Option<SplitDirection>,
    pub default_split: SplitDirection,
    pub ssl_verify: bool,
}

#[derive(Clone, Debug, Default, Deserialize)]
pub struct Tunables {
    /// Subsection for overriding encryption-related settings.
    #[serde(default)]
    pub encryption: Encryption,

    /// Subsection for configuring an HTTP(S) proxy.
    pub proxy: Option<Proxy>,

    /// Subsection for overriding sort orders in UI lists.
    #[serde(default)]
    pub sort: SortOverrides,

    /// Subsection for overriding terminal settings.
    #[serde(default)]
    pub terminal: Terminal,

    /// Subsection for overriding how specific Matrix users are rendered.
    pub users: Option<UserOverrides>,

    pub default_markup: Option<MarkupFormat>,
    pub log_level: Option<String>,
    pub max_log_files: Option<usize>,
    pub message_shortcode_display: Option<bool>,
    pub normal_after_send: Option<bool>,
    pub reaction_display: Option<bool>,
    pub reaction_shortcode_display: Option<bool>,
    pub read_receipt_send: Option<bool>,
    pub read_receipt_trigger: Option<ReadReceiptTrigger>,
    pub read_receipt_display: Option<bool>,
    pub request_timeout: Option<u64>,
    pub state_event_display: Option<bool>,
    pub typing_notice_send: Option<bool>,
    pub typing_notice_display: Option<bool>,
    pub username_display: Option<UserDisplayStyle>,
    pub message_user_color: Option<bool>,
    pub default_room: Option<String>,
    pub open_command: Option<Vec<String>>,
    pub mouse: Option<Mouse>,
    pub notifications: Option<Notifications>,
    pub image_preview: Option<ImagePreview>,
    pub user_gutter_width: Option<usize>,
    pub external_edit_file_suffix: Option<String>,
    pub tabstop: Option<usize>,
    pub members_split: Option<SplitDirection>,
    pub default_split: Option<SplitDirection>,
    pub ssl_verify: Option<bool>,
}

impl Tunables {
    fn merge(self, other: Self) -> Self {
        Tunables {
            encryption: Encryption::merge(self.encryption, other.encryption),
            sort: SortOverrides::merge(self.sort, other.sort),
            terminal: Terminal::merge(self.terminal, other.terminal),
            users: merge_maps(self.users, other.users),

            // Proxy configuration sub-field do *not* get merged, so that a
            // per-profile override won't inherit auth or headers from the
            // global settings.
            proxy: self.proxy.or(other.proxy),

            default_markup: self.default_markup.or(other.default_markup),
            log_level: self.log_level.or(other.log_level),
            max_log_files: self.max_log_files.or(other.max_log_files),
            message_shortcode_display: self
                .message_shortcode_display
                .or(other.message_shortcode_display),
            normal_after_send: self.normal_after_send.or(other.normal_after_send),
            reaction_display: self.reaction_display.or(other.reaction_display),
            reaction_shortcode_display: self
                .reaction_shortcode_display
                .or(other.reaction_shortcode_display),
            read_receipt_send: self.read_receipt_send.or(other.read_receipt_send),
            read_receipt_trigger: self.read_receipt_trigger.or(other.read_receipt_trigger),
            read_receipt_display: self.read_receipt_display.or(other.read_receipt_display),
            request_timeout: self.request_timeout.or(other.request_timeout),
            state_event_display: self.state_event_display.or(other.state_event_display),
            typing_notice_send: self.typing_notice_send.or(other.typing_notice_send),
            typing_notice_display: self.typing_notice_display.or(other.typing_notice_display),
            username_display: self.username_display.or(other.username_display),
            message_user_color: self.message_user_color.or(other.message_user_color),
            default_room: self.default_room.or(other.default_room),
            open_command: self.open_command.or(other.open_command),
            mouse: self.mouse.or(other.mouse),
            notifications: self.notifications.or(other.notifications),
            image_preview: self.image_preview.or(other.image_preview),
            user_gutter_width: self.user_gutter_width.or(other.user_gutter_width),
            external_edit_file_suffix: self
                .external_edit_file_suffix
                .or(other.external_edit_file_suffix),
            tabstop: self.tabstop.or(other.tabstop),
            members_split: self.members_split.or(other.members_split),
            default_split: self.default_split.or(other.default_split),
            ssl_verify: self.ssl_verify.or(other.ssl_verify),
        }
    }

    fn values(self) -> TunableValues {
        TunableValues {
            encryption: self.encryption.values(),
            proxy: self.proxy.unwrap_or_default().values(),
            sort: self.sort.values(),
            terminal: self.terminal.values(),
            users: self.users.unwrap_or_default(),

            default_markup: self.default_markup.unwrap_or_default(),
            log_level: self.log_level.unwrap_or_else(|| DEFAULT_LOG_LEVEL.to_owned()),
            max_log_files: self.max_log_files.unwrap_or(7),
            message_shortcode_display: self.message_shortcode_display.unwrap_or(false),
            normal_after_send: self.normal_after_send.unwrap_or(false),
            reaction_display: self.reaction_display.unwrap_or(true),
            reaction_shortcode_display: self.reaction_shortcode_display.unwrap_or(false),
            read_receipt_send: self.read_receipt_send.unwrap_or(true),
            read_receipt_trigger: self.read_receipt_trigger.unwrap_or_default(),
            read_receipt_display: self.read_receipt_display.unwrap_or(true),
            request_timeout: self.request_timeout.unwrap_or(DEFAULT_REQ_TIMEOUT),
            state_event_display: self.state_event_display.unwrap_or(true),
            typing_notice_send: self.typing_notice_send.unwrap_or(true),
            typing_notice_display: self.typing_notice_display.unwrap_or(true),
            username_display: self.username_display.unwrap_or_default(),
            message_user_color: self.message_user_color.unwrap_or(false),
            default_room: self.default_room,
            open_command: self.open_command,
            mouse: self.mouse.unwrap_or_default(),
            notifications: self.notifications.unwrap_or_default(),
            image_preview: self.image_preview.map(ImagePreview::values),
            user_gutter_width: self.user_gutter_width.unwrap_or(30),
            external_edit_file_suffix: self
                .external_edit_file_suffix
                .unwrap_or_else(|| ".md".to_string()),
            tabstop: self.tabstop.unwrap_or(4),
            members_split: self.members_split,
            default_split: self.default_split.unwrap_or_default(),
            ssl_verify: self.ssl_verify.unwrap_or(true),
        }
    }
}

#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq)]
#[serde(rename_all = "kebab-case")]
#[repr(u8)]
pub enum CursorShape {
    #[default]
    Default,
    Block,
    Line,
    Underline,
}

impl From<CursorShape> for modalkit::crossterm::cursor::SetCursorStyle {
    fn from(shape: CursorShape) -> Self {
        match shape {
            CursorShape::Default => Self::DefaultUserShape,
            CursorShape::Block => Self::SteadyBlock,
            CursorShape::Line => Self::SteadyBar,
            CursorShape::Underline => Self::SteadyUnderScore,
        }
    }
}

#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq)]
#[serde(rename_all = "kebab-case")]
#[repr(u8)]
pub enum MarkupFormat {
    Html,
    #[default]
    Markdown,
    Plaintext,
}

#[derive(Clone)]
pub struct DirectoryValues {
    pub cache: PathBuf,
    pub data: PathBuf,
    pub logs: PathBuf,
    pub downloads: Option<PathBuf>,
}

impl DirectoryValues {
    fn create_dir_all(&self) -> std::io::Result<()> {
        use std::fs::create_dir_all;

        let Self { cache, data, logs, downloads } = self;

        create_dir_all(cache)?;
        create_dir_all(data)?;
        create_dir_all(logs)?;

        if let Some(downloads) = downloads {
            create_dir_all(downloads)?;
        }

        Ok(())
    }
}

#[derive(Clone, Default, Deserialize)]
pub struct Directories {
    pub cache: Option<String>,
    pub data: Option<String>,
    pub logs: Option<String>,
    pub downloads: Option<String>,
}

impl Directories {
    fn merge(self, other: Self) -> Self {
        Directories {
            cache: self.cache.or(other.cache),
            data: self.data.or(other.data),
            logs: self.logs.or(other.logs),
            downloads: self.downloads.or(other.downloads),
        }
    }

    fn values(self) -> DirectoryValues {
        let cache = self
            .cache
            .map(|dir| {
                let dir = shellexpand::full(&dir)
                    .expect("unable to expand shell variables in dirs.cache");
                Path::new(dir.as_ref()).to_owned()
            })
            .or_else(|| {
                let mut dir = dirs::cache_dir()?;
                dir.push("iamb");
                dir.into()
            })
            .expect("no dirs.cache value configured!");

        let data = self
            .data
            .map(|dir| {
                let dir = shellexpand::full(&dir)
                    .expect("unable to expand shell variables in dirs.cache");
                Path::new(dir.as_ref()).to_owned()
            })
            .or_else(|| {
                let mut dir = dirs::data_dir()?;
                dir.push("iamb");
                dir.into()
            })
            .expect("no dirs.data value configured!");

        let logs = self
            .logs
            .map(|dir| {
                let dir = shellexpand::full(&dir)
                    .expect("unable to expand shell variables in dirs.cache");
                Path::new(dir.as_ref()).to_owned()
            })
            .unwrap_or_else(|| {
                let mut dir = cache.clone();
                dir.push("logs");
                dir
            });

        let downloads = self
            .downloads
            .map(|dir| {
                let dir = shellexpand::full(&dir)
                    .expect("unable to expand shell variables in dirs.cache");
                Path::new(dir.as_ref()).to_owned()
            })
            .or_else(dirs::download_dir);

        DirectoryValues { cache, data, logs, downloads }
    }
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
#[serde(untagged)]
pub enum WindowPath {
    AliasId(OwnedRoomAliasId),
    RoomId(OwnedRoomId),
    UserId(OwnedUserId),
    Window(IambId),
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
#[serde(untagged, deny_unknown_fields)]
pub enum WindowLayout {
    Window { window: WindowPath },
    Split { split: Vec<WindowLayout> },
}

#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
#[serde(rename_all = "lowercase", tag = "style")]
pub enum Layout {
    /// Restore the layout from the previous session.
    #[default]
    Restore,

    /// Open a single window using the `default_room` value.
    New,

    /// Open the window layouts described under `tabs`.
    Config { tabs: Vec<WindowLayout> },
}

#[derive(Clone, Deserialize)]
pub struct ProfileConfig {
    pub user_id: OwnedUserId,
    pub password_file: Option<PathBuf>,
    pub url: Option<Url>,
    pub settings: Option<Tunables>,
    pub dirs: Option<Directories>,
    pub layout: Option<Layout>,
    pub macros: Option<Macros>,
}

#[derive(Clone, Deserialize)]
pub struct IambConfig {
    pub profiles: BTreeMap<String, ProfileConfig>,
    pub default_profile: Option<String>,
    pub settings: Option<Tunables>,
    pub dirs: Option<Directories>,
    pub layout: Option<Layout>,
    pub macros: Option<Macros>,
}

impl IambConfig {
    pub fn load_toml(path: &Path) -> Result<Self, ConfigError> {
        let s = std::fs::read_to_string(path)?;
        let config = toml::from_str(&s)?;

        Ok(config)
    }

    pub fn load_json(path: &Path) -> Result<Self, ConfigError> {
        let s = std::fs::read_to_string(path)?;
        let config = serde_json::from_str(&s)?;

        Ok(config)
    }
}

#[derive(Clone)]
pub struct ApplicationSettings {
    pub layout_json: PathBuf,
    pub session_json: PathBuf,
    pub session_json_old: PathBuf,
    pub sled_dir: PathBuf,
    pub sqlite_dir: PathBuf,
    pub profile_name: String,
    pub profile: ProfileConfig,
    pub tunables: TunableValues,
    pub dirs: DirectoryValues,
    pub layout: Layout,
    pub macros: Macros,
}

impl ApplicationSettings {
    fn get_xdg_config_home() -> Option<PathBuf> {
        env::var("XDG_CONFIG_HOME").ok().map(PathBuf::from)
    }

    pub fn load(cli: Iamb) -> Result<Self, Box<dyn std::error::Error>> {
        let mut config_dir = cli
            .config_directory
            .or_else(Self::get_xdg_config_home)
            .or_else(dirs::config_dir)
            .unwrap_or_else(|| {
                usage!(
                    "No user configuration directory found;\
                    please specify one via -C.\n\n
                    For more information try '--help'"
                );
            });

        config_dir.push("iamb");
        let config_json = config_dir.join("config.json");
        let config_toml = config_dir.join("config.toml");

        let config = if config_toml.is_file() {
            IambConfig::load_toml(config_toml.as_path())?
        } else if config_json.is_file() {
            IambConfig::load_json(config_json.as_path())?
        } else {
            usage!(
                "Please create a configuration file at {}\n\n\
                For more information try '--help'",
                config_toml.display(),
            );
        };

        let IambConfig {
            mut profiles,
            default_profile,
            dirs,
            settings: global,
            layout,
            macros,
        } = config;

        validate_profile_names(&profiles);

        let (profile_name, mut profile) = if let Some(profile) = cli.profile.or(default_profile) {
            profiles.remove_entry(&profile).unwrap_or_else(|| {
                usage!(
                    "No configured profile with the name {:?} in {}",
                    profile,
                    config_json.display()
                );
            })
        } else if profiles.len() == 1 {
            profiles.into_iter().next().unwrap()
        } else {
            loop {
                println!("\nNo profile specified. Available profiles:");
                profiles.keys().enumerate().for_each(|(i, name)| println!("{i}: {name}"));

                print!("Select a number or 'q' to quit: ");
                let _ = std::io::stdout().flush();

                let mut input = String::new();
                let _ = std::io::stdin().read_line(&mut input);

                if input.trim() == "q" {
                    usage!(
                        "No profile specified. \
                        Please use -P or add \"default_profile\" to your configuration.\n\n\
                        For more information try '--help'",
                    );
                }
                if let Ok(i) = input.trim().parse::<usize>() &&
                    i < profiles.len()
                {
                    break profiles.into_iter().nth(i).unwrap();
                }
                println!("\nInvalid index.");
            }
        };

        let macros = merge_maps(profile.macros.take(), macros).unwrap_or_default();
        let layout = profile.layout.take().or(layout).unwrap_or_default();

        let tunables = global.unwrap_or_default();
        let tunables = profile.settings.take().unwrap_or_default().merge(tunables);
        let tunables = tunables.values();

        let dirs = dirs.unwrap_or_default();
        let dirs = profile.dirs.take().unwrap_or_default().merge(dirs);
        let dirs = dirs.values();

        // Create directories
        dirs.create_dir_all()?;

        // Set up paths that live inside the profile's data directory.
        let mut profile_dir = config_dir.clone();
        profile_dir.push("profiles");
        profile_dir.push(profile_name.as_str());

        let mut profile_data_dir = dirs.data.clone();
        profile_data_dir.push("profiles");
        profile_data_dir.push(profile_name.as_str());

        let mut sled_dir = profile_dir.clone();
        sled_dir.push("matrix");

        let mut sqlite_dir = profile_data_dir.clone();
        sqlite_dir.push("sqlite");

        let mut session_json = profile_data_dir.clone();
        session_json.push("session.json");

        let mut session_json_old = profile_dir;
        session_json_old.push("session.json");

        // Set up paths that live inside the profile's cache directory.
        let mut cache_dir = dirs.cache.clone();
        cache_dir.push("profiles");
        cache_dir.push(profile_name.as_str());

        let mut layout_json = cache_dir.clone();
        layout_json.push("layout.json");

        let settings = ApplicationSettings {
            sled_dir,
            layout_json,
            session_json,
            session_json_old,
            sqlite_dir,
            profile_name,
            profile,
            tunables,
            dirs,
            layout,
            macros,
        };

        Ok(settings)
    }

    pub fn read_session(&self, path: impl AsRef<Path>) -> Result<Session, IambError> {
        let file = File::open(path)?;
        let reader = BufReader::new(file);
        let session = serde_json::from_reader(reader).map_err(IambError::from)?;
        Ok(session)
    }

    pub fn write_session(&self, session: MatrixSession) -> Result<(), IambError> {
        let file = File::create(self.session_json.as_path())?;
        let writer = BufWriter::new(file);
        let session = Session::from(session);
        serde_json::to_writer(writer, &session).map_err(IambError::from)?;
        Ok(())
    }

    pub fn get_user_char_span(&self, user_id: &UserId) -> Span<'_> {
        let (color, c) = self
            .tunables
            .users
            .get(user_id)
            .map(|user| {
                (
                    user.color.as_ref().map(|c| c.0),
                    user.name.as_ref().and_then(|s| s.chars().next()),
                )
            })
            .unwrap_or_default();

        let color = color.unwrap_or_else(|| user_color(user_id.as_str()));
        let style = user_style_from_color(color);

        let c = c.unwrap_or_else(|| user_id.localpart().chars().next().unwrap_or(' '));

        Span::styled(String::from(c), style)
    }

    pub fn get_user_overrides(
        &self,
        user_id: &UserId,
    ) -> (Option<Color>, Option<Cow<'static, str>>) {
        self.tunables
            .users
            .get(user_id)
            .map(|user| (user.color.as_ref().map(|c| c.0), user.name.clone().map(Cow::Owned)))
            .unwrap_or_default()
    }

    pub fn get_user_color(&self, user_id: &UserId) -> Color {
        self.tunables
            .users
            .get(user_id)
            .and_then(|user| user.color.as_ref().map(|c| c.0))
            .unwrap_or_else(|| user_color(user_id.as_str()))
    }

    pub fn get_user_style(&self, user_id: &UserId) -> Style {
        user_style_from_color(self.get_user_color(user_id))
    }

    pub fn get_user_span<'a>(&self, user_id: &'a UserId, info: &'a RoomInfo) -> Span<'a> {
        let (color, name) = self.get_user_overrides(user_id);

        let color = color.unwrap_or_else(|| user_color(user_id.as_str()));
        let style = user_style_from_color(color);
        let name = match (name, &self.tunables.username_display) {
            (Some(name), _) => name,
            (None, UserDisplayStyle::Username) => Cow::Borrowed(user_id.as_str()),
            (None, UserDisplayStyle::LocalPart) => Cow::Borrowed(user_id.localpart()),
            (None, UserDisplayStyle::DisplayName) => {
                if let Some(name) = info.display_names.get(user_id) {
                    name
                } else {
                    Cow::Borrowed(user_id.as_str())
                }
            },
        };

        Span::styled(name, style)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use matrix_sdk::ruma::user_id;
    use std::convert::TryFrom;

    #[test]
    fn test_profile_name_invalid() {
        assert_eq!(validate_profile_name(""), false);
        assert_eq!(validate_profile_name(" "), false);
        assert_eq!(validate_profile_name("a b"), false);
        assert_eq!(validate_profile_name("foo^bar"), false);
        assert_eq!(validate_profile_name("FOO/BAR"), false);
        assert_eq!(validate_profile_name("-b-c"), false);
        assert_eq!(validate_profile_name("-B-c"), false);
        assert_eq!(validate_profile_name(".b-c"), false);
        assert_eq!(validate_profile_name(".B-c"), false);
    }

    #[test]
    fn test_profile_name_valid() {
        assert_eq!(validate_profile_name("foo"), true);
        assert_eq!(validate_profile_name("FOO"), true);
        assert_eq!(validate_profile_name("a-b-c"), true);
        assert_eq!(validate_profile_name("a-B-c"), true);
        assert_eq!(validate_profile_name("a.b-c"), true);
        assert_eq!(validate_profile_name("a.B-c"), true);
    }

    #[test]
    fn test_merge_users() {
        let a = None;
        let b = vec![(user_id!("@a:b.c").to_owned(), UserDisplayTunables {
            color: Some(UserColor(Color::Red)),
            name: Some("Hello".into()),
        })]
        .into_iter()
        .collect::<HashMap<_, _>>();
        let c = vec![(user_id!("@a:b.c").to_owned(), UserDisplayTunables {
            color: Some(UserColor(Color::Green)),
            name: Some("World".into()),
        })]
        .into_iter()
        .collect::<HashMap<_, _>>();

        let res = merge_maps(a.clone(), a.clone());
        assert_eq!(res, None);

        let res = merge_maps(a.clone(), Some(b.clone()));
        assert_eq!(res, Some(b.clone()));

        let res = merge_maps(Some(b.clone()), a.clone());
        assert_eq!(res, Some(b.clone()));

        let res = merge_maps(Some(b.clone()), Some(b.clone()));
        assert_eq!(res, Some(b.clone()));

        let res = merge_maps(Some(b.clone()), Some(c.clone()));
        assert_eq!(res, Some(b.clone()));

        let res = merge_maps(Some(c.clone()), Some(b.clone()));
        assert_eq!(res, Some(c.clone()));
    }

    #[test]
    fn test_parse_tunables() {
        let res: Tunables = serde_json::from_str("{}").unwrap();
        assert_eq!(res.typing_notice_send, None);
        assert_eq!(res.typing_notice_display, None);
        assert_eq!(res.users, None);

        let res: Tunables = serde_json::from_str("{\"typing_notice_send\": true}").unwrap();
        assert_eq!(res.typing_notice_send, Some(true));
        assert_eq!(res.typing_notice_display, None);
        assert_eq!(res.users, None);

        let res: Tunables = serde_json::from_str("{\"typing_notice_send\": false}").unwrap();
        assert_eq!(res.typing_notice_send, Some(false));
        assert_eq!(res.typing_notice_display, None);
        assert_eq!(res.users, None);

        let res: Tunables = serde_json::from_str("{\"users\": {}}").unwrap();
        assert_eq!(res.typing_notice_send, None);
        assert_eq!(res.typing_notice_display, None);
        assert_eq!(res.users, Some(HashMap::new()));

        let res: Tunables = serde_json::from_str(
            "{\"users\": {\"@a:b.c\": {\"color\": \"black\", \"name\": \"Tim\"}}}",
        )
        .unwrap();
        assert_eq!(res.typing_notice_send, None);
        assert_eq!(res.typing_notice_display, None);
        let users = vec![(user_id!("@a:b.c").to_owned(), UserDisplayTunables {
            color: Some(UserColor(Color::Black)),
            name: Some("Tim".into()),
        })];
        assert_eq!(res.users, Some(users.into_iter().collect()));
    }

    #[test]
    fn test_parse_tunables_username_display() {
        let res: Tunables = serde_json::from_str("{\"username_display\": \"username\"}").unwrap();
        assert_eq!(res.username_display, Some(UserDisplayStyle::Username));

        let res: Tunables = serde_json::from_str("{\"username_display\": \"localpart\"}").unwrap();
        assert_eq!(res.username_display, Some(UserDisplayStyle::LocalPart));

        let res: Tunables =
            serde_json::from_str("{\"username_display\": \"displayname\"}").unwrap();
        assert_eq!(res.username_display, Some(UserDisplayStyle::DisplayName));
    }

    #[test]
    fn test_parse_tunables_sort() {
        let res: Tunables = serde_json::from_str(
            r#"{"sort": {"members": ["server","~localpart"],"spaces":["~favorite", "alias"]}}"#,
        )
        .unwrap();
        assert_eq!(
            res.sort.members,
            Some(vec![
                SortColumn(SortFieldUser::Server, SortOrder::Ascending),
                SortColumn(SortFieldUser::LocalPart, SortOrder::Descending),
            ])
        );
        assert_eq!(
            res.sort.spaces,
            Some(vec![
                SortColumn(SortFieldRoom::Favorite, SortOrder::Descending),
                SortColumn(SortFieldRoom::Alias, SortOrder::Ascending),
            ])
        );
        assert_eq!(res.sort.rooms, None);
        assert_eq!(res.sort.dms, None);

        // Check that we get the right default "rooms" and "dms" values.
        let res = res.values();
        assert_eq!(res.sort.members, vec![
            SortColumn(SortFieldUser::Server, SortOrder::Ascending),
            SortColumn(SortFieldUser::LocalPart, SortOrder::Descending),
        ]);
        assert_eq!(res.sort.spaces, vec![
            SortColumn(SortFieldRoom::Favorite, SortOrder::Descending),
            SortColumn(SortFieldRoom::Alias, SortOrder::Ascending),
        ]);
        assert_eq!(res.sort.rooms, Vec::from(DEFAULT_ROOM_SORT));
        assert_eq!(res.sort.dms, Vec::from(DEFAULT_ROOM_SORT));
    }

    #[test]
    fn test_parse_tunables_proxy_invalid() {
        let res =
            serde_json::from_str::<Tunables>(r#"{"proxy": {"url": "localhost"}}"#).unwrap_err();

        // Should result in a validation error:
        assert_eq!(res.classify(), serde_json::error::Category::Data);
    }

    #[test]
    fn test_parse_tunables_proxy_empty() {
        let res: Tunables = serde_json::from_str(r#"{"proxy": {"url": ""}}"#).unwrap();
        let proxy = res.proxy.unwrap();
        assert_eq!(proxy.url.unwrap(), ProxyUrl::Disabled);
    }

    #[test]
    fn test_parse_tunables_proxy_socks5() {
        let res: Tunables =
            serde_json::from_str(r#"{"proxy": {"url": "socks5://localhost:1080"}}"#).unwrap();
        let proxy = res.proxy.unwrap();
        let ProxyUrl::Endpoint(url) = proxy.url.unwrap() else {
            panic!("should parse ProxyUrl::Endpoint")
        };

        assert_eq!(url.scheme(), "socks5");
        assert_eq!(url.host_str().unwrap(), "localhost");
        assert_eq!(url.port().unwrap(), 1080);
        assert_eq!(url.authority(), "localhost:1080");
    }

    #[test]
    fn test_parse_tunables_proxy_https() {
        let res: Tunables = serde_json::from_str(
            r#"{"proxy": {"url": "https://localhost:8080","auth": "Bearer abcd1234","headers":{"User-Agent": "iamb"}}}"#
        ).unwrap();
        let proxy = res.proxy.unwrap();
        let ProxyUrl::Endpoint(url) = proxy.url.unwrap() else {
            panic!("should parse ProxyUrl::Endpoint")
        };

        // Verify URL fields:
        assert_eq!(url.scheme(), "https");
        assert_eq!(url.host_str().unwrap(), "localhost");
        assert_eq!(url.port().unwrap(), 8080);
        assert_eq!(url.authority(), "localhost:8080");

        // Verify our `Proxy-Authorization` value:
        assert_eq!(proxy.auth.unwrap(), "Bearer abcd1234");

        // Verify our custom header is present:
        assert_eq!(proxy.headers.len(), 1);
        assert_eq!(proxy.headers.get("user-agent").unwrap(), "iamb");
    }

    #[test]
    fn test_parse_tunables_proxy_merge() {
        let global: Tunables = serde_json::from_str(
            r#"{"proxy": {"url": "https://localhost:8080","auth": "Bearer abcd1234","headers":{"User-Agent": "iamb"}}}"#
        ).unwrap();
        let profile: Tunables =
            serde_json::from_str(r#"{"proxy": {"url": "socks5://localhost:1080"}}"#).unwrap();

        // The configuration merge should select the entirety of the profile proxy config,
        // and not merge subfields, to ensure that things like `auth` and `headers` are
        // not ever sent to a `url` they were meant for.
        let merged = profile.merge(global).values();
        let ProxyUrl::Endpoint(url) = merged.proxy.url else {
            panic!("should parse ProxyUrl::Endpoint")
        };
        assert_eq!(url.scheme(), "socks5");
        assert_eq!(url.authority(), "localhost:1080");
        assert_eq!(merged.proxy.auth, None);
        assert_eq!(merged.proxy.headers.is_empty(), true);
    }

    #[test]
    fn test_parse_layout() {
        let user = WindowPath::UserId(user_id!("@user:example.com").to_owned());
        let alias = WindowPath::AliasId(OwnedRoomAliasId::try_from("#room:example.com").unwrap());
        let room = WindowPath::RoomId(OwnedRoomId::try_from("!room:example.com").unwrap());
        let dms = WindowPath::Window(IambId::DirectList);
        let welcome = WindowPath::Window(IambId::Welcome);

        let res: Layout = serde_json::from_str("{\"style\": \"restore\"}").unwrap();
        assert_eq!(res, Layout::Restore);

        let res: Layout = serde_json::from_str("{\"style\": \"new\"}").unwrap();
        assert_eq!(res, Layout::New);

        let res: Layout = serde_json::from_str(
            "{\"style\": \"config\", \"tabs\": [{\"window\":\"@user:example.com\"}]}",
        )
        .unwrap();
        assert_eq!(res, Layout::Config {
            tabs: vec![WindowLayout::Window { window: user.clone() }]
        });

        let res: Layout = serde_json::from_str(
            "{\
            \"style\": \"config\",\
            \"tabs\": [\
                {\"split\":[\
                    {\"window\":\"@user:example.com\"},\
                    {\"window\":\"#room:example.com\"}\
                ]},\
                {\"split\":[\
                    {\"window\":\"!room:example.com\"},\
                    {\"split\":[\
                        {\"window\":\"iamb://dms\"},\
                        {\"window\":\"iamb://welcome\"}\
                    ]}\
                ]}\
            ]}",
        )
        .unwrap();
        let split1 = WindowLayout::Split {
            split: vec![
                WindowLayout::Window { window: user.clone() },
                WindowLayout::Window { window: alias },
            ],
        };
        let split2 = WindowLayout::Split {
            split: vec![WindowLayout::Window { window: dms }, WindowLayout::Window {
                window: welcome,
            }],
        };
        let split3 = WindowLayout::Split {
            split: vec![WindowLayout::Window { window: room }, split2],
        };
        let tabs = vec![split1, split3];
        assert_eq!(res, Layout::Config { tabs });
    }

    #[test]
    fn test_parse_macros() {
        let res: Macros = serde_json::from_str("{\"i|c\":{\"jj\":\"<Esc>\"}}").unwrap();
        assert_eq!(res.len(), 1);

        let modes = VimModes(vec![VimMode::Insert, VimMode::Command]);
        let mapped = res.get(&modes).unwrap();
        assert_eq!(mapped.len(), 1);

        let j = "j".parse::<TerminalKey>().unwrap();
        let esc = "<Esc>".parse::<TerminalKey>().unwrap();

        let jj = Keys(vec![j, j], "jj".into());
        let run = mapped.get(&jj).unwrap();
        let exp = Keys(vec![esc], "<Esc>".into());
        assert_eq!(run, &exp);
    }

    #[test]
    fn test_parse_notify_via() {
        assert_eq!(NotifyVia { bell: false, desktop: true }, NotifyVia::default());
        assert_eq!(
            NotifyVia { bell: false, desktop: true },
            serde_json::from_str(r#""desktop""#).unwrap()
        );
        assert_eq!(
            NotifyVia { bell: true, desktop: false },
            serde_json::from_str(r#""bell""#).unwrap()
        );
        assert_eq!(
            NotifyVia { bell: true, desktop: true },
            serde_json::from_str(r#""bell|desktop""#).unwrap()
        );
        assert_eq!(
            NotifyVia { bell: true, desktop: true },
            serde_json::from_str(r#""desktop|bell""#).unwrap()
        );
        assert!(serde_json::from_str::<NotifyVia>(r#""other""#).is_err());
        assert!(serde_json::from_str::<NotifyVia>(r#""""#).is_err());
    }

    #[test]
    fn test_parse_cursor_shape() {
        assert_eq!(CursorShape::Default, CursorShape::default());
        assert_eq!(CursorShape::Default, serde_json::from_str(r#""default""#).unwrap());
        assert_eq!(CursorShape::Block, serde_json::from_str(r#""block""#).unwrap());
        assert_eq!(CursorShape::Line, serde_json::from_str(r#""line""#).unwrap());
        assert_eq!(CursorShape::Underline, serde_json::from_str(r#""underline""#).unwrap());
        assert!(serde_json::from_str::<CursorShape>(r#""beam""#).is_err());
    }

    #[test]
    fn test_load_example_config_toml() {
        let path = PathBuf::from("config.example.toml");
        let config = IambConfig::load_toml(&path).expect("can load example_config.toml");

        let IambConfig {
            profiles,
            default_profile,
            settings,
            dirs,
            layout,
            macros,
        } = &config;

        // There should be an example object for each top-level field.
        assert!(!profiles.is_empty());
        assert!(default_profile.is_some());
        assert!(settings.is_some());
        assert!(dirs.is_some());
        assert!(layout.is_some());
        assert!(macros.is_some());
    }

    #[test]
    fn test_encryption_indicator_enabled() {
        use EncryptionState::*;

        let enc = EncryptionValues {
            indicator: EncryptionIndicator::Enabled,
            indicator_location: EncryptionIndicatorLocation::TITLE,
        };

        // Always shows in the title:
        assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Encrypted).is_some());
        assert!(
            enc.get_indicator(EncryptionIndicatorLocation::TITLE, NotEncrypted)
                .is_some()
        );
        assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Unknown).is_some());

        // Doesn't show in the prompt:
        assert!(enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Encrypted).is_none());
        assert!(
            enc.get_indicator(EncryptionIndicatorLocation::PROMPT, NotEncrypted)
                .is_none()
        );
        assert!(enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Unknown).is_none());
    }

    #[test]
    fn test_encryption_indicator_disabled() {
        use EncryptionState::*;

        let enc = EncryptionValues {
            indicator: EncryptionIndicator::Disabled,
            indicator_location: EncryptionIndicatorLocation::TITLE,
        };

        // Never shows in the title or the prompt:
        assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Encrypted).is_none());
        assert!(
            enc.get_indicator(EncryptionIndicatorLocation::TITLE, NotEncrypted)
                .is_none()
        );
        assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Unknown).is_none());
        assert!(enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Encrypted).is_none());
        assert!(
            enc.get_indicator(EncryptionIndicatorLocation::PROMPT, NotEncrypted)
                .is_none()
        );
        assert!(enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Unknown).is_none());
    }

    #[test]
    fn test_encryption_indicator_only_encrypted() {
        use EncryptionState::*;

        let enc = EncryptionValues {
            indicator: EncryptionIndicator::OnlyEncrypted,
            indicator_location: EncryptionIndicatorLocation::PROMPT,
        };

        // Shows in the prompt when encrypted or unknown:
        assert!(enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Encrypted).is_some());
        assert!(enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Unknown).is_some());

        // But is hidden when unencrypted:
        assert!(
            enc.get_indicator(EncryptionIndicatorLocation::PROMPT, NotEncrypted)
                .is_none()
        );

        // Doesn't show in the title:
        assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Encrypted).is_none());
        assert!(
            enc.get_indicator(EncryptionIndicatorLocation::TITLE, NotEncrypted)
                .is_none()
        );
        assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Unknown).is_none());
    }
    #[test]
    fn test_encryption_indicator_only_unencrypted() {
        use EncryptionState::*;

        let enc = EncryptionValues {
            indicator: EncryptionIndicator::OnlyUnencrypted,
            indicator_location: EncryptionIndicatorLocation::all(),
        };

        // Shows in both the prompt and title when unencrypted or unknown:
        assert!(
            enc.get_indicator(EncryptionIndicatorLocation::TITLE, NotEncrypted)
                .is_some()
        );
        assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Unknown).is_some());
        assert!(
            enc.get_indicator(EncryptionIndicatorLocation::PROMPT, NotEncrypted)
                .is_some()
        );
        assert!(enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Unknown).is_some());

        // But is hidden when encrypted:
        assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Encrypted).is_none());
        assert!(enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Encrypted).is_none());
    }
}