file_desktop 0.1.0

Parse, inspect, and build XDG .desktop files in Rust
Documentation
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
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
// {── Module ──────────────────────────────────────────────────────────────
//! Desktop Entry keys, values, and specification versions.
//!
//! This module provides types for working with the
//! [Desktop Entry specification](https://specifications.freedesktop.org/desktop-entry-spec/latest/).
//! It includes:
//!
//! - [`Version`] — Desktop Entry specification version identifiers from 1.0 to 1.5
//! - [`DesktopFileType`](crate::desktop::DesktopFileType) — The three standard Desktop Entry file types:
//!   `Application`, `Link`, and `Directory`
//! - [`EntryKeys`] — A type-safe enum of standardized Desktop Entry keys
//! - [`EscapedString`] and [`EscapedStrings`] — Validated `string` values and
//!   semicolon-separated lists of `string` values
//! - [`LocaleString`] and [`LocaleStrings`] — Validated `localestring` values and
//!   semicolon-separated lists of `localestring` values
//! - [`IconString`] — A validated `iconstring` value
//! - [`Bool`] — A validated boolean value
//! - [`Numeric`] — A validated numeric value
//! - Version-aware key filtering to determine which standardized keys are
//!   available in a given Desktop Entry specification version
//!
//! The value wrapper types validate their contents according to the
//! Desktop Entry specification and provide parsing and formatting support.
//!
//! # Examples
//!
//! Parse a Desktop Entry specification version:
//!
//! ```rust
//! use file_desktop::key::Version;
//!
//! let version: Version = "1.5".parse().unwrap();
//!
//! assert_eq!(version, Version::Ver1_5);
//! assert_eq!(version.version(), "1.5");
//! ```
//!
//! Parse a standardized Desktop Entry key:
//!
//! ```rust
//! use file_desktop::key::EntryKeys;
//!
//! let key: EntryKeys = "Name".parse().unwrap();
//!
//! assert_eq!(key, EntryKeys::Name);
//! ```
//!
//! Parse and validate a Desktop Entry string value:
//!
//! ```rust
//! use file_desktop::key::EscapedString;
//!
//! let value: EscapedString = r"Basic\nEditor".parse().unwrap();
//!
//! assert_eq!(value.as_ref(), r"Basic\nEditor");
//! ```
//!
//! Parse a semicolon-separated list value:
//!
//! ```rust
//! use file_desktop::key::EscapedStrings;
//!
//! let values: EscapedStrings = r"Editor;Basic\;Editor;".parse().unwrap();
//!
//! assert_eq!(values.len(), 2);
//! assert_eq!(values[0].as_ref(), "Editor");
//! assert_eq!(values[1].as_ref(), r"Basic;Editor");
//! ```

use std::borrow::Cow;
use std::fmt;
use std::str::FromStr;

use crate::entry::Entry;
use crate::error::{
    MutationValueError, ParseEntryError, ParseEntryValueError, ParseKeyError, ValueError,
};

// }{── Const ──────────────────────────────────────────────────────────────

/// Keys introduced after spec v1.0, ordered by introduction version.
///
/// `VersionKeys::new` slices a suffix of this array to obtain the exclusion list
/// for each target version.  The ordering is a hard invariant — do not reorder.
///
/// - indices 0–2: added in v1.1 (`DBusActivatable`, `Actions`, `Keywords`)
/// - index 3: added in v1.2 (`Implements`)
/// - index 4: added in v1.4 (`PrefersNonDefaultGPU`)
/// - index 5: added in v1.5 (`SingleMainWindow`)
pub(crate) const VERSION_EXCLUDES: [&str; 6] = [
    EntryKeys::DBusActivatable.key(),
    EntryKeys::Actions.key(),
    EntryKeys::Keywords.key(),
    EntryKeys::Implements.key(),
    EntryKeys::PrefersNonDefaultGPU.key(),
    EntryKeys::SingleMainWindow.key(),
];

pub(crate) const APPLICATION: &str = "Application";
pub(crate) const DIRECTORY: &str = "Directory";
pub(crate) const LINK: &str = "Link";

// }{── EntryKeys ──────────────────────────────────────────────────────────────

/// Enumeration of all 25 standardized Desktop Entry key names.
///
/// Each variant maps 1-to-1 to a key in the XDG Desktop Entry Specification via
/// `key()`.  The declaration order matches `KEYS` — keep them in sync.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum EntryKeys {
    /// `Type`: Defines the type of desktop entry (Application, Link, or Directory)
    Type,
    /// `Version`: Version of the Desktop Entry Specification this file conforms to
    Version,
    /// `Name`: Display name of the application, link, or directory (required)
    Name,
    /// `GenericName`: Generic description (e.g., "Web Browser" for Firefox)
    GenericName,
    /// `NoDisplay`: If true, the entry should not be displayed in menus
    NoDisplay,
    /// `Comment`: Tooltip or longer description of the entry
    Comment,
    /// `Icon`: Name or path to the icon for this entry
    Icon,
    /// `Hidden`: If true, this desktop file is marked as deleted/hidden
    Hidden,
    /// `OnlyShowIn`: Semicolon-separated list of desktop environments where entry should be shown (all if absent)
    OnlyShowIn,
    /// `NotShowIn`: Semicolon-separated list of desktop environments where entry should not be shown
    NotShowIn,
    /// `DBusActivatable`: If true, the application can be activated via D-Bus (since 1.1)
    DBusActivatable,
    /// `TryExec`: Path to an executable used to determine if the program is installed
    TryExec,
    /// `Exec`: Command line to execute the program
    Exec,
    /// `Path`: Working directory for the program execution
    Path,
    /// `Terminal`: If true, the program runs in a terminal window
    Terminal,
    /// `Actions`: Semicolon-separated list of action names (since 1.1)
    Actions,
    /// `MimeType`: Semicolon-separated list of MIME types supported by the application
    MimeType,
    /// `Categories`: Semicolon-separated list of menu categories
    Categories,
    /// `Implements`: Semicolon-separated list of interfaces the application implements (since 1.2)
    Implements,
    /// `Keywords`: Semicolon-separated list of keywords for searching this entry (since 1.1)
    Keywords,
    /// `StartupNotify`: If true, provides startup/launch notification feedback
    StartupNotify,
    /// `StartupWMClass`: String used for window manager startup notification
    StartupWMClass,
    /// `URL`: URL to access when activated (for Link type entries)
    URL,
    /// `PrefersNonDefaultGPU`: If true, hints that the application prefers discrete GPU (since 1.4)
    PrefersNonDefaultGPU,
    /// `SingleMainWindow`: If true, the application uses a single main window (since 1.5)
    SingleMainWindow,
}

impl EntryKeys {
    /// All 25 standardized Desktop Entry key name strings, in declaration order.
    ///
    /// Must stay in sync with the variant order of `EntryKeys` and with
    /// `VERSION_EXCLUDES` indices.
    pub(crate) const KEYS: &[&'static str] = &[
        EntryKeys::Type.key(),
        EntryKeys::Version.key(),
        EntryKeys::Name.key(),
        EntryKeys::GenericName.key(),
        EntryKeys::NoDisplay.key(),
        EntryKeys::Comment.key(),
        EntryKeys::Icon.key(),
        EntryKeys::Hidden.key(),
        EntryKeys::OnlyShowIn.key(),
        EntryKeys::NotShowIn.key(),
        EntryKeys::DBusActivatable.key(),
        EntryKeys::TryExec.key(),
        EntryKeys::Exec.key(),
        EntryKeys::Path.key(),
        EntryKeys::Terminal.key(),
        EntryKeys::Actions.key(),
        EntryKeys::MimeType.key(),
        EntryKeys::Categories.key(),
        EntryKeys::Implements.key(),
        EntryKeys::Keywords.key(),
        EntryKeys::StartupNotify.key(),
        EntryKeys::StartupWMClass.key(),
        EntryKeys::URL.key(),
        EntryKeys::PrefersNonDefaultGPU.key(),
        EntryKeys::SingleMainWindow.key(),
    ];

    /// Returns an iterator over all standardized Desktop Entry key names.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use file_desktop::key::EntryKeys;
    ///
    /// assert!(EntryKeys::all_keys().any(|key| key == "Name"));
    /// ```
    #[inline]
    #[must_use]
    pub fn all_keys() -> AllKeys {
        AllKeys(Self::KEYS.iter())
    }

    /// Returns whether this key is required for every desktop entry type.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use file_desktop::key::EntryKeys;
    ///
    /// assert!(EntryKeys::Name.is_required());
    /// assert!(!EntryKeys::URL.is_required());
    /// ```
    #[inline]
    #[must_use]
    pub const fn is_required(self) -> bool {
        matches!(self, Self::Type | Self::Name)
    }

    /// Returns whether this key is required for the specified desktop entry type.
    ///
    /// `Type` and `Name` are required for every entry type. `URL` is additionally
    /// required for link entries.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use file_desktop::key::{DesktopType, EntryKeys};
    ///
    /// assert!(EntryKeys::URL.is_required_for(DesktopType::Link));
    /// assert!(!EntryKeys::URL.is_required_for(DesktopType::Application));
    /// assert!(EntryKeys::Name.is_required_for(DesktopType::Application));
    /// ```
    #[inline]
    #[must_use]
    pub const fn is_required_for(self, desktop_type: DesktopType) -> bool {
        self.is_required() || matches!((self, desktop_type), (Self::URL, DesktopType::Link))
    }

    /// Returns the key's exact string spelling as used in `.desktop` files.
    #[inline]
    #[must_use]
    pub const fn key(self) -> &'static str {
        match self {
            Self::Type => "Type",
            Self::Version => "Version",
            Self::Name => "Name",
            Self::GenericName => "GenericName",
            Self::NoDisplay => "NoDisplay",
            Self::Comment => "Comment",
            Self::Icon => "Icon",
            Self::Hidden => "Hidden",
            Self::OnlyShowIn => "OnlyShowIn",
            Self::NotShowIn => "NotShowIn",
            Self::DBusActivatable => "DBusActivatable",
            Self::TryExec => "TryExec",
            Self::Exec => "Exec",
            Self::Path => "Path",
            Self::Terminal => "Terminal",
            Self::Actions => "Actions",
            Self::MimeType => "MimeType",
            Self::Categories => "Categories",
            Self::Implements => "Implements",
            Self::Keywords => "Keywords",
            Self::StartupNotify => "StartupNotify",
            Self::StartupWMClass => "StartupWMClass",
            Self::URL => "URL",
            Self::PrefersNonDefaultGPU => "PrefersNonDefaultGPU",
            Self::SingleMainWindow => "SingleMainWindow",
        }
    }

    /// Returns the Desktop Entry Specification version in which this key was
    /// introduced, or `None` when it was present in version 1.0.
    #[inline]
    #[must_use]
    pub const fn version_introduced(self) -> Option<Version> {
        match self {
            Self::DBusActivatable | Self::Actions | Self::Keywords => Some(Version::Ver1_1),
            Self::Implements => Some(Version::Ver1_2),
            Self::PrefersNonDefaultGPU => Some(Version::Ver1_4),
            Self::SingleMainWindow => Some(Version::Ver1_5),
            _ => None,
        }
    }

    /// Returns this key when it supports a locale suffix.
    ///
    /// The localizable standard keys are `Name`, `GenericName`, `Comment`,
    /// `Icon`, and `Keywords`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use file_desktop::key::EntryKeys;
    ///
    /// assert_eq!(EntryKeys::Name.localizable_key(), Some(EntryKeys::Name));
    /// assert_eq!(EntryKeys::Exec.localizable_key(), None);
    /// ```
    #[must_use]
    pub fn localizable_key(self) -> Option<EntryKeys> {
        Some(match self {
            Self::Name | Self::GenericName | Self::Comment | Self::Icon | Self::Keywords => self,
            _ => return None,
        })
    }

    /// Parses a standard key name that supports a locale suffix.
    ///
    /// # Arguments
    ///
    /// * `s` - The base key name without a locale suffix.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use file_desktop::key::EntryKeys;
    ///
    /// assert_eq!(EntryKeys::parse_localizable_key("Keywords"), Some(EntryKeys::Keywords));
    /// assert_eq!(EntryKeys::parse_localizable_key("Exec"), None);
    /// ```
    #[must_use]
    pub fn parse_localizable_key(s: &str) -> Option<EntryKeys> {
        Some(match s {
            "Name" => Self::Name,
            "GenericName" => Self::GenericName,
            "Comment" => Self::Comment,
            "Icon" => Self::Icon,
            "Keywords" => Self::Keywords,
            _ => return None,
        })
    }
}

impl AsRef<str> for EntryKeys {
    fn as_ref(&self) -> &str {
        self.key()
    }
}

/// Formats the entry key as its string representation.
///
/// Outputs the exact key name as defined in the Desktop Entry Specification.
impl fmt::Display for EntryKeys {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.key().fmt(f)
    }
}

/// Converts an [`EntryKeys`] variant to its string representation.
impl From<EntryKeys> for &str {
    #[inline]
    fn from(entry_key: EntryKeys) -> &'static str {
        entry_key.key()
    }
}

/// Converts an [`EntryKeys`] variant to a borrowed `Cow<'static, str>`.
///
/// The resulting `Cow` always contains a borrowed string slice, never an owned value.
impl From<EntryKeys> for Cow<'static, str> {
    #[inline]
    fn from(entry_key: EntryKeys) -> Self {
        entry_key.key().into()
    }
}

/// Converts a string to an [`EntryKeys`] variant.
///
/// Performs case-sensitive matching against all standardized Desktop Entry keys.
/// Note that `"URL"` (all uppercase) is the correct form for the URL key.
///
/// Returns [`ParseKeyError`] if the string doesn't match any known key name.
impl FromStr for EntryKeys {
    type Err = ParseKeyError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            val if val == EntryKeys::Type.key() => Ok(Self::Type),
            val if val == EntryKeys::Version.key() => Ok(Self::Version),
            val if val == EntryKeys::Name.key() => Ok(Self::Name),
            val if val == EntryKeys::GenericName.key() => Ok(Self::GenericName),
            val if val == EntryKeys::NoDisplay.key() => Ok(Self::NoDisplay),
            val if val == EntryKeys::Comment.key() => Ok(Self::Comment),
            val if val == EntryKeys::Icon.key() => Ok(Self::Icon),
            val if val == EntryKeys::Hidden.key() => Ok(Self::Hidden),
            val if val == EntryKeys::OnlyShowIn.key() => Ok(Self::OnlyShowIn),
            val if val == EntryKeys::NotShowIn.key() => Ok(Self::NotShowIn),
            val if val == EntryKeys::DBusActivatable.key() => Ok(Self::DBusActivatable),
            val if val == EntryKeys::TryExec.key() => Ok(Self::TryExec),
            val if val == EntryKeys::Exec.key() => Ok(Self::Exec),
            val if val == EntryKeys::Path.key() => Ok(Self::Path),
            val if val == EntryKeys::Terminal.key() => Ok(Self::Terminal),
            val if val == EntryKeys::Actions.key() => Ok(Self::Actions),
            val if val == EntryKeys::MimeType.key() => Ok(Self::MimeType),
            val if val == EntryKeys::Categories.key() => Ok(Self::Categories),
            val if val == EntryKeys::Implements.key() => Ok(Self::Implements),
            val if val == EntryKeys::Keywords.key() => Ok(Self::Keywords),
            val if val == EntryKeys::StartupNotify.key() => Ok(Self::StartupNotify),
            val if val == EntryKeys::StartupWMClass.key() => Ok(Self::StartupWMClass),
            val if val == EntryKeys::URL.key() => Ok(Self::URL),
            val if val == EntryKeys::PrefersNonDefaultGPU.key() => Ok(Self::PrefersNonDefaultGPU),
            val if val == EntryKeys::SingleMainWindow.key() => Ok(Self::SingleMainWindow),
            _ => Err(ParseKeyError::NonStandardKey),
        }
    }
}

// }{── AllKeys ──────────────────────────────────────────────────────────────

/// Iterator over all 25 standardized Desktop Entry key name strings.
///
/// Produced by [`EntryKeys::all_keys`]; wraps a slice iterator over `KEYS`.
#[derive(Debug, Clone)]
pub struct AllKeys(std::slice::Iter<'static, &'static str>);

/// Yields the next desktop entry key string from the iterator.
///
/// The iterator yields each key defined by the enum exactly once, then returns `None`.
impl Iterator for AllKeys {
    type Item = &'static str;

    fn next(&mut self) -> Option<Self::Item> {
        self.0.next().map(|value| &**value)
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.0.size_hint()
    }
}

impl DoubleEndedIterator for AllKeys {
    fn next_back(&mut self) -> Option<Self::Item> {
        self.0.next_back().map(|value| &**value)
    }
}

impl ExactSizeIterator for AllKeys {}
impl std::iter::FusedIterator for AllKeys {}

// }{── DesktopType ──────────────────────────────────────────────────────────────

/// The resource class of a desktop entry, carried by [`Entry::Type`].
///
/// Corresponds to the three standardized `Type=` values defined by the
/// [XDG Desktop Entry Specification](https://specifications.freedesktop.org/desktop-entry-spec/latest/).
///
/// # Examples
///
/// ```rust
/// use file_desktop::key::DesktopType;
///
/// assert_eq!(DesktopType::Application.to_string(), "Application");
/// assert_eq!(DesktopType::Link.to_string(), "Link");
/// assert_eq!(DesktopType::Directory.to_string(), "Directory");
/// ```
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum DesktopType {
    /// A runnable application entry.
    #[default]
    Application,
    /// A URL / web-link entry.
    Link,
    /// A directory entry.
    Directory,
}

impl DesktopType {
    /// Returns the Desktop Entry `Type` value as a string slice.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use file_desktop::key::DesktopType;
    ///
    /// assert_eq!(DesktopType::Application.as_str(), "Application");
    /// ```
    #[inline]
    #[must_use]
    pub fn as_str(&self) -> &str {
        match self {
            Self::Application => APPLICATION,
            Self::Link => LINK,
            Self::Directory => DIRECTORY,
        }
    }
}

impl AsRef<str> for DesktopType {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl fmt::Display for DesktopType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl From<DesktopType> for &str {
    #[inline]
    fn from(value: DesktopType) -> Self {
        match value {
            DesktopType::Application => APPLICATION,
            DesktopType::Link => LINK,
            DesktopType::Directory => DIRECTORY,
        }
    }
}

impl FromStr for DesktopType {
    type Err = ParseEntryValueError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::try_from(s)
    }
}

impl TryFrom<&str> for DesktopType {
    type Error = ParseEntryValueError;

    fn try_from(s: &str) -> Result<Self, Self::Error> {
        match s {
            APPLICATION => Ok(Self::Application),
            LINK => Ok(Self::Link),
            DIRECTORY => Ok(Self::Directory),
            _ => Err(ParseEntryValueError::ParseDesktopType),
        }
    }
}

impl TryFrom<String> for DesktopType {
    type Error = ParseEntryValueError;

    fn try_from(s: String) -> Result<Self, Self::Error> {
        DesktopType::try_from(s.as_str())
    }
}

impl<'a> TryFrom<&'a Entry> for &'a DesktopType {
    type Error = ValueError;

    fn try_from(entry: &'a Entry) -> Result<Self, Self::Error> {
        match entry {
            Entry::Type(value) => Ok(value),
            entry => Err(ValueError(entry.value_type().to_string())),
        }
    }
}

// }{── Version ──────────────────────────────────────────────────────────────

/// Desktop Entry Specification version identifier.
///
/// Represents the version of the [Desktop Entry Specification](https://specifications.freedesktop.org/desktop-entry-spec/latest/)
/// that a desktop file conforms to. Different versions support different sets of keys.
///
/// # Version Ordering
///
/// Versions are ordered chronologically, allowing for comparisons:
/// `Ver1_0 < Ver1_1 < Ver1_2 < Ver1_3 < Ver1_4 < Ver1_5`
///
/// # Key Changes by Version
///
/// | Version | New Keys | Total Keys |
/// |---------|----------|------------|
/// | 1.0 | (initial) | 19 |
/// | 1.1 | `DBusActivatable`, `Actions`, `Keywords` | 22 |
/// | 1.2 | `Implements` | 23 |
/// | 1.3 | (no changes) | 23 |
/// | 1.4 | `PrefersNonDefaultGPU` | 24 |
/// | 1.5 | `SingleMainWindow` | 25 |
///
/// # Examples
///
/// Create default version:
///
/// ```
/// use file_desktop::key::Version;
///
/// let default_version = Version::latest();
/// assert_eq!(default_version, Version::Ver1_5);
/// ```
///
/// Parse from string:
///
/// ```rust
/// use file_desktop::key::Version;
/// use std::str::FromStr;
///
/// let version = Version::from_str("1.4").unwrap();
/// assert_eq!(version.version(), "1.4");
/// ```
///
/// Compare versions:
///
/// ```
/// use file_desktop::key::Version;
///
/// assert!(Version::Ver1_0 < Version::Ver1_5);
/// assert!(Version::Ver1_2 <= Version::Ver1_2);
/// assert!(Version::Ver1_4 > Version::Ver1_1);
/// ```
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum Version {
    /// Desktop Entry Specification version 1.0 (19 keys)
    Ver1_0,
    /// Desktop Entry Specification version 1.1 (22 keys: adds `DBusActivatable`, `Actions`, `Keywords`)
    Ver1_1,
    /// Desktop Entry Specification version 1.2 (23 keys: adds `Implements`)
    Ver1_2,
    /// Desktop Entry Specification version 1.3 (23 keys: no changes from 1.2)
    Ver1_3,
    /// Desktop Entry Specification version 1.4 (24 keys: adds `PrefersNonDefaultGPU`)
    Ver1_4,
    /// Desktop Entry Specification version 1.5 (25 keys: adds `SingleMainWindow`, current)
    #[default]
    Ver1_5,
}

impl Version {
    /// Returns the most recent Desktop Entry Specification version supported by this library.
    ///
    /// Applications should use this version by default when creating or processing desktop
    /// entries, unless they specifically need compatibility with older specification versions.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use file_desktop::key::Version;
    ///
    /// let latest = Version::latest();
    ///
    /// assert_eq!(latest, Version::Ver1_5);
    /// ```
    #[must_use]
    pub const fn latest() -> Self {
        Self::Ver1_5
    }

    /// Returns the version number as a string slice.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use file_desktop::key::Version;
    ///
    /// assert_eq!(Version::Ver1_0.version(), "1.0");
    /// assert_eq!(Version::Ver1_5.version(), "1.5");
    /// ```
    #[inline]
    #[must_use]
    pub const fn version(&self) -> &'static str {
        match self {
            Self::Ver1_0 => "1.0",
            Self::Ver1_1 => "1.1",
            Self::Ver1_2 => "1.2",
            Self::Ver1_3 => "1.3",
            Self::Ver1_4 => "1.4",
            Self::Ver1_5 => "1.5",
        }
    }

    /// Returns `true` if `s` exactly matches one of the six supported
    /// version strings (`"1.0"` through `"1.5"`).
    ///
    /// # Arguments
    ///
    /// * `s` - The version string to validate.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use file_desktop::key::Version;
    ///
    /// assert!(Version::is_valid_version("1.5"));
    /// assert!(!Version::is_valid_version("1.6"));
    /// ```
    #[inline]
    #[must_use]
    pub fn is_valid_version(s: &str) -> bool {
        s.parse::<Version>().is_ok()
    }
}

impl AsRef<str> for Version {
    fn as_ref(&self) -> &str {
        self.version()
    }
}

/// Formats the specification version as its version string.
///
/// Outputs the version in the format `X.Y` (e.g., `"1.5"`).
///
/// # Examples
///
/// ```rust
/// use file_desktop::key::Version;
///
/// assert_eq!(format!("{}", Version::Ver1_0), "1.0");
/// assert_eq!(format!("{}", Version::Ver1_5), "1.5");
/// ```
impl fmt::Display for Version {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.version().fmt(f)
    }
}

impl From<Version> for f64 {
    fn from(value: Version) -> f64 {
        match value {
            Version::Ver1_0 => 1.0,
            Version::Ver1_1 => 1.1,
            Version::Ver1_2 => 1.2,
            Version::Ver1_3 => 1.3,
            Version::Ver1_4 => 1.4,
            Version::Ver1_5 => 1.5,
        }
    }
}

impl From<Version> for &'static str {
    fn from(value: Version) -> &'static str {
        value.version()
    }
}

/// Converts a string to a [`Version`] variant.
///
/// Performs case-sensitive matching against the registered Desktop Entry Specification versions
/// (`1.0`, `1.1`, `1.2`, `1.3`, `1.4`, `1.5`). All other strings are rejected.
///
/// # Errors
///
/// Returns [`ParseEntryValueError::ParseVersion`] if the string does not exactly
/// match one of the six supported version strings.
///
/// # Examples
///
/// ```rust
/// use file_desktop::key::Version;
/// use std::str::FromStr;
///
/// assert_eq!(Version::from_str("1.0"), Ok(Version::Ver1_0));
/// assert_eq!(Version::from_str("1.5"), Ok(Version::Ver1_5));
/// assert!(Version::from_str("1.6").is_err());
/// assert!(Version::from_str("2.0").is_err());
/// assert!(Version::from_str("1").is_err());
/// ```
impl FromStr for Version {
    type Err = ParseEntryValueError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::try_from(s)
    }
}

impl TryFrom<&str> for Version {
    type Error = ParseEntryValueError;

    fn try_from(s: &str) -> Result<Self, Self::Error> {
        match s {
            val if val == Self::Ver1_0.version() => Ok(Self::Ver1_0),
            val if val == Self::Ver1_1.version() => Ok(Self::Ver1_1),
            val if val == Self::Ver1_2.version() => Ok(Self::Ver1_2),
            val if val == Self::Ver1_3.version() => Ok(Self::Ver1_3),
            val if val == Self::Ver1_4.version() => Ok(Self::Ver1_4),
            val if val == Self::Ver1_5.version() => Ok(Self::Ver1_5),
            _ => Err(ParseEntryValueError::ParseVersion),
        }
    }
}

impl TryFrom<String> for Version {
    type Error = ParseEntryValueError;

    fn try_from(s: String) -> Result<Self, Self::Error> {
        Version::try_from(s.as_str())
    }
}

impl<'a> TryFrom<&'a Entry> for &'a Version {
    type Error = ValueError;

    fn try_from(entry: &'a Entry) -> Result<Self, Self::Error> {
        match entry {
            Entry::Version(value) => Ok(value),
            entry => Err(ValueError(entry.value_type().to_string())),
        }
    }
}

impl<'a> TryFrom<&'a mut Entry> for &'a mut Version {
    type Error = MutationValueError;

    fn try_from(entry: &'a mut Entry) -> Result<Self, Self::Error> {
        match entry {
            Entry::Version(value) => Ok(value),
            entry => Err(MutationValueError(entry.value_type().to_string())),
        }
    }
}

// }{── Numeric ──────────────────────────────────────────────────────────────────

/// A validated floating-point value for numeric Desktop Entry fields.
///
/// `Numeric` is provided for extension keys and future spec additions that carry
/// floating-point values.  It encapsulates parsing and validation so that raw strings
/// are not used for numeric fields.
///
/// # Examples
///
/// ```rust
/// use file_desktop::key::Numeric;
/// use std::str::FromStr;
///
/// let n = Numeric::new(42.0);
/// assert_eq!(n.value(), 42.0);
/// assert_eq!(n.to_string(), "42");
///
/// let parsed = Numeric::try_from("100").unwrap();
/// assert_eq!(parsed.value(), 100.0);
///
/// assert!(Numeric::from_str("not-a-number").is_err());
/// ```
#[derive(Default, Debug, Copy, Clone, PartialEq, PartialOrd)]
pub struct Numeric(f64);

impl Numeric {
    /// Creates a new `Numeric` value.
    ///
    /// # Arguments
    ///
    /// * `value` - The floating-point value to wrap.
    #[inline]
    #[must_use]
    pub fn new(value: f64) -> Self {
        Self(value)
    }

    /// Returns the wrapped floating-point value.
    #[inline]
    #[must_use]
    pub fn value(self) -> f64 {
        self.0
    }
}

impl fmt::Display for Numeric {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl From<f64> for Numeric {
    #[inline]
    fn from(value: f64) -> Self {
        Self(value)
    }
}

impl From<Numeric> for f64 {
    #[inline]
    fn from(value: Numeric) -> Self {
        value.0
    }
}

impl FromStr for Numeric {
    type Err = ParseEntryValueError;

    #[inline]
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::try_from(s)
    }
}

impl TryFrom<&str> for Numeric {
    type Error = ParseEntryValueError;

    #[inline]
    fn try_from(s: &str) -> Result<Self, Self::Error> {
        s.parse::<f64>()
            .map(Self)
            .map_err(|_| ParseEntryValueError::ParseNumeric)
    }
}

impl TryFrom<String> for Numeric {
    type Error = ParseEntryValueError;

    #[inline]
    fn try_from(s: String) -> Result<Self, Self::Error> {
        Self::try_from(s.as_str())
    }
}

// }{── Bool ──────────────────────────────────────────────────────────────────

/// A `boolean`-typed Desktop Entry value: exactly `"true"` or `"false"`.
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Bool(bool);

impl Bool {
    /// Creates a new `Bool` value.
    ///
    /// # Arguments
    ///
    /// * `value` - The Boolean value to wrap.
    #[inline]
    #[must_use]
    pub fn new(value: bool) -> Self {
        Self(value)
    }

    /// Returns the wrapped Boolean value.
    #[inline]
    #[must_use]
    pub fn value(self) -> bool {
        self.0
    }
}

impl fmt::Display for Bool {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl From<bool> for Bool {
    #[inline]
    fn from(value: bool) -> Self {
        Self(value)
    }
}

impl From<Bool> for bool {
    #[inline]
    fn from(value: Bool) -> Self {
        value.0
    }
}

impl FromStr for Bool {
    type Err = ParseEntryValueError;

    #[inline]
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::try_from(s)
    }
}

impl TryFrom<&str> for Bool {
    type Error = ParseEntryValueError;

    #[inline]
    fn try_from(s: &str) -> Result<Self, Self::Error> {
        s.parse::<bool>()
            .map(Self)
            .map_err(|_| ParseEntryValueError::ParseBool)
    }
}

impl TryFrom<String> for Bool {
    type Error = ParseEntryValueError;

    #[inline]
    fn try_from(s: String) -> Result<Self, Self::Error> {
        Self::try_from(s.as_str())
    }
}

impl<'a> TryFrom<&'a Entry> for &'a Bool {
    type Error = ValueError;

    fn try_from(entry: &'a Entry) -> Result<Self, Self::Error> {
        match entry {
            Entry::NoDisplay(value)
            | Entry::Hidden(value)
            | Entry::Terminal(value)
            | Entry::DBusActivatable(value)
            | Entry::StartupNotify(value)
            | Entry::PrefersNonDefaultGPU(value)
            | Entry::SingleMainWindow(value) => Ok(value),
            entry => Err(ValueError(entry.value_type().to_string())),
        }
    }
}

impl<'a> TryFrom<&'a mut Entry> for &'a mut Bool {
    type Error = MutationValueError;

    fn try_from(entry: &'a mut Entry) -> Result<Self, Self::Error> {
        match entry {
            Entry::NoDisplay(value)
            | Entry::Hidden(value)
            | Entry::Terminal(value)
            | Entry::DBusActivatable(value)
            | Entry::StartupNotify(value)
            | Entry::PrefersNonDefaultGPU(value)
            | Entry::SingleMainWindow(value) => Ok(value),
            entry => Err(MutationValueError(entry.value_type().to_string())),
        }
    }
}

// }{── IconString ───────────────────────────────────────────────────────────────

/// An `iconstring`-typed value for the `Icon=` field: an icon theme name or
/// an absolute filesystem path.
///
/// Per the [XDG value types](https://specifications.freedesktop.org/desktop-entry/1.5/value-types.html),
/// `iconstring` is UTF-8 (like [`LocaleString`]), not ASCII-restricted like
/// [`EscapedString`] — only raw control characters and unsupported escape
/// sequences are rejected.
///
/// # Examples
///
/// ```rust
/// use file_desktop::key::IconString;
///
/// let path = IconString::try_from("/usr/share/icons/firefox.png").unwrap();
/// assert!(path.is_path());
/// assert!(!path.is_name());
/// ```
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct IconString(String);

impl IconString {
    /// Returns the icon value as a string slice.
    #[inline]
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Returns `true` if the value is an absolute filesystem path (starts with `/`).
    #[inline]
    #[must_use]
    pub fn is_path(&self) -> bool {
        self.0.starts_with('/')
    }

    /// Returns `true` if the value is an icon theme name rather than a path.
    #[inline]
    #[must_use]
    pub fn is_name(&self) -> bool {
        !self.is_path()
    }

    /// Consumes the wrapper and returns the inner `String`.
    #[inline]
    #[must_use]
    pub fn into_string(self) -> String {
        self.0
    }
}

impl AsRef<str> for IconString {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for IconString {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl std::ops::Deref for IconString {
    type Target = str;

    fn deref(&self) -> &str {
        &self.0
    }
}

impl From<IconString> for String {
    fn from(value: IconString) -> Self {
        value.0
    }
}

impl std::str::FromStr for IconString {
    type Err = ParseEntryValueError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::try_from(s)
    }
}

impl TryFrom<&str> for IconString {
    type Error = ParseEntryValueError;

    #[inline]
    fn try_from(s: &str) -> Result<Self, Self::Error> {
        validate_string(
            s,
            validate_no_control,
            ParseEntryValueError::ParseIconString,
        )?;
        Ok(Self(s.to_owned()))
    }
}

impl TryFrom<String> for IconString {
    type Error = ParseEntryValueError;

    fn try_from(s: String) -> Result<Self, Self::Error> {
        validate_string(
            &s,
            validate_no_control,
            ParseEntryValueError::ParseIconString,
        )?;
        Ok(Self(s))
    }
}

impl<'a> TryFrom<&'a Entry> for &'a IconString {
    type Error = ValueError;

    fn try_from(entry: &'a Entry) -> Result<Self, Self::Error> {
        match entry {
            Entry::Icon(value) => Ok(value),
            entry => Err(ValueError(entry.value_type().to_string())),
        }
    }
}

impl<'a> TryFrom<&'a mut Entry> for &'a mut IconString {
    type Error = MutationValueError;

    fn try_from(entry: &'a mut Entry) -> Result<Self, Self::Error> {
        match entry {
            Entry::Icon(value) => Ok(value),
            entry => Err(MutationValueError(entry.value_type().to_string())),
        }
    }
}

// }{── EscapedString ───────────────────────────────────────────────────────────────

/// A `string`-typed Desktop Entry value: printable ASCII only, per the
/// [XDG value types](https://specifications.freedesktop.org/desktop-entry/1.5/value-types.html).
///
/// Backs keys such as `Exec=`, `TryExec=`, `Path=`, `StartupWMClass=`, and
/// `URL=`. Unlike [`LocaleString`]/[`IconString`], this type rejects any
/// non-ASCII byte, not just control characters — `string` values are ASCII
/// by spec, while `localestring`/`iconstring` are UTF-8.
///
/// The stored text is the raw, still-escaped form (backslash sequences are
/// validated but not decoded into their literal characters).
///
/// # Examples
///
/// ```rust
/// use file_desktop::key::EscapedString;
///
/// let s = EscapedString::try_from("/usr/bin/myapp \\snoconfig").unwrap();
/// assert_eq!(s.as_str(), "/usr/bin/myapp \\snoconfig");
///
/// assert!(EscapedString::try_from("café").is_err()); // non-ASCII
/// assert!(EscapedString::try_from("bad \\q escape").is_err()); // unknown escape
/// ```
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct EscapedString(String);

impl EscapedString {
    /// Returns the value as a string slice.
    #[inline]
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Consumes the wrapper and returns the inner `String`.
    #[inline]
    #[must_use]
    pub fn into_string(self) -> String {
        self.0
    }
}

impl AsRef<str> for EscapedString {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for EscapedString {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl std::ops::Deref for EscapedString {
    type Target = str;

    fn deref(&self) -> &str {
        &self.0
    }
}

impl From<EscapedString> for String {
    fn from(value: EscapedString) -> Self {
        value.0
    }
}

impl std::str::FromStr for EscapedString {
    type Err = ParseEntryValueError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::try_from(s)
    }
}

impl TryFrom<&str> for EscapedString {
    type Error = ParseEntryValueError;

    #[inline]
    fn try_from(s: &str) -> Result<Self, Self::Error> {
        validate_string(
            s,
            validate_ascii_no_control,
            ParseEntryValueError::ParseEscapedString,
        )?;
        Ok(Self(s.to_owned()))
    }
}

impl TryFrom<String> for EscapedString {
    type Error = ParseEntryValueError;

    fn try_from(s: String) -> Result<Self, Self::Error> {
        validate_string(
            &s,
            validate_ascii_no_control,
            ParseEntryValueError::ParseEscapedString,
        )?;
        Ok(Self(s))
    }
}

impl<'a> TryFrom<&'a Entry> for &'a EscapedString {
    type Error = ValueError;

    fn try_from(entry: &'a Entry) -> Result<Self, Self::Error> {
        match entry {
            Entry::Exec(value)
            | Entry::TryExec(value)
            | Entry::Path(value)
            | Entry::StartupWMClass(value)
            | Entry::URL(value) => Ok(value),
            entry => Err(ValueError(entry.value_type().to_string())),
        }
    }
}

impl<'a> TryFrom<&'a mut Entry> for &'a mut EscapedString {
    type Error = MutationValueError;

    fn try_from(entry: &'a mut Entry) -> Result<Self, Self::Error> {
        match entry {
            Entry::Exec(value)
            | Entry::TryExec(value)
            | Entry::Path(value)
            | Entry::StartupWMClass(value)
            | Entry::URL(value) => Ok(value),
            entry => Err(MutationValueError(entry.value_type().to_string())),
        }
    }
}

// }{── LocaleString ─────────────────────────────────────────────────────────────

/// A `localestring`-typed value used by localized and display-text entries.
///
/// Per the [XDG value types](https://specifications.freedesktop.org/desktop-entry/1.5/value-types.html),
/// `localestring` is UTF-8, unlike the ASCII-restricted [`EscapedString`] —
/// only raw control characters and unsupported escape sequences are
/// rejected. It is carried by the [`Entry::Localized`] variant as the
/// translated content.
///
/// # Examples
///
/// ```rust
/// use file_desktop::key::LocaleString;
///
/// let s = LocaleString::try_from("Mein Browser").unwrap();
/// assert_eq!(s.as_str(), "Mein Browser");
/// assert_eq!(s.to_string(), "Mein Browser");
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Default, Hash)]
pub struct LocaleString(String);

impl LocaleString {
    /// Returns the string value as a slice.
    #[inline]
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Consumes the wrapper and returns the inner `String`.
    #[inline]
    #[must_use]
    pub fn into_string(self) -> String {
        self.0
    }
}

impl AsRef<str> for LocaleString {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for LocaleString {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl std::ops::Deref for LocaleString {
    type Target = str;

    fn deref(&self) -> &str {
        &self.0
    }
}

impl From<LocaleString> for String {
    fn from(value: LocaleString) -> Self {
        value.0
    }
}

impl std::str::FromStr for LocaleString {
    type Err = ParseEntryValueError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::try_from(s)
    }
}

impl TryFrom<&str> for LocaleString {
    type Error = ParseEntryValueError;

    #[inline]
    fn try_from(s: &str) -> Result<Self, Self::Error> {
        validate_string(
            s,
            validate_no_control,
            ParseEntryValueError::ParseLocaleString,
        )?;
        Ok(Self(s.to_owned()))
    }
}

impl TryFrom<String> for LocaleString {
    type Error = ParseEntryValueError;

    fn try_from(s: String) -> Result<Self, Self::Error> {
        validate_string(
            &s,
            validate_no_control,
            ParseEntryValueError::ParseLocaleString,
        )?;
        Ok(Self(s))
    }
}

impl<'a> TryFrom<&'a Entry> for &'a LocaleString {
    type Error = ValueError;

    fn try_from(entry: &'a Entry) -> Result<Self, Self::Error> {
        let error = ValueError(entry.value_type().to_string());

        match entry {
            Entry::Name(value) | Entry::GenericName(value) | Entry::Comment(value) => Ok(value),

            Entry::Localized(localized) => match &localized.value {
                LocalizedValue::Localized(value) => Ok(value),
                LocalizedValue::LocalizedKeywords(_) => Err(error),
            },

            _ => Err(error),
        }
    }
}

impl<'a> TryFrom<&'a mut Entry> for &'a mut LocaleString {
    type Error = MutationValueError;

    fn try_from(entry: &'a mut Entry) -> Result<Self, Self::Error> {
        let error = MutationValueError(entry.value_type().to_string());

        match entry {
            Entry::Name(value) | Entry::GenericName(value) | Entry::Comment(value) => Ok(value),

            Entry::Localized(localized) => match &mut localized.value {
                LocalizedValue::Localized(value) => Ok(value),
                LocalizedValue::LocalizedKeywords(_) => Err(error),
            },

            _ => Err(error),
        }
    }
}

// }{── EscapedStrings ──────────────────────────────────────────────────────────────────

/// A semicolon-delimited list of [`EscapedString`] values.
///
/// Backs list-typed `string(s)` keys such as `Actions=`, `MimeType=`,
/// `Categories=`, and `Implements=`.
#[derive(Debug, Clone, PartialEq, Eq, Default, Hash)]
pub struct EscapedStrings(Vec<EscapedString>);

impl EscapedStrings {
    /// Creates a new `EscapedStrings` from a list of already-valid
    /// [`EscapedString`] values.
    ///
    /// No further validation is needed here: each element was already
    /// validated when it was constructed as an `EscapedString`.
    #[inline]
    #[must_use]
    pub fn new(list: Vec<EscapedString>) -> Self {
        Self(list)
    }

    /// Returns the list as a slice of `EscapedString` values.
    #[inline]
    #[must_use]
    pub fn as_slice(&self) -> &[EscapedString] {
        &self.0
    }

    /// Appends an `EscapedString` to the end of the list.
    #[inline]
    pub fn push(&mut self, item: EscapedString) {
        self.0.push(item);
    }

    /// Returns an iterator over the list's `EscapedString` values.
    pub fn iter(&self) -> std::slice::Iter<'_, EscapedString> {
        <&Self as IntoIterator>::into_iter(self)
    }
}

impl AsRef<[EscapedString]> for EscapedStrings {
    fn as_ref(&self) -> &[EscapedString] {
        &self.0
    }
}

impl fmt::Display for EscapedStrings {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for value in &self.0 {
            for c in value.chars() {
                if c == ';' {
                    f.write_str("\\")?;
                }

                write!(f, "{c}")?;
            }

            f.write_str(";")?;
        }

        Ok(())
    }
}

impl std::ops::Deref for EscapedStrings {
    type Target = [EscapedString];

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl From<Vec<EscapedString>> for EscapedStrings {
    fn from(value: Vec<EscapedString>) -> Self {
        Self(value)
    }
}

impl FromIterator<EscapedString> for EscapedStrings {
    fn from_iter<I>(iter: I) -> Self
    where
        I: IntoIterator<Item = EscapedString>,
    {
        Self(iter.into_iter().collect())
    }
}

impl FromStr for EscapedStrings {
    type Err = ParseEntryValueError;

    fn from_str(strings: &str) -> Result<Self, Self::Err> {
        Self::try_from(strings)
    }
}

impl TryFrom<&str> for EscapedStrings {
    type Error = ParseEntryValueError;

    fn try_from(list: &str) -> Result<Self, Self::Error> {
        Ok(Self(split_semicolon_list::<EscapedString>(
            list,
            ParseEntryValueError::ParseEscapedStrings,
        )?))
    }
}
impl TryFrom<String> for EscapedStrings {
    type Error = ParseEntryValueError;

    #[inline]
    fn try_from(value: String) -> Result<Self, Self::Error> {
        Self::try_from(value.as_str())
    }
}

impl<'a> TryFrom<&'a Entry> for &'a EscapedStrings {
    type Error = ValueError;

    fn try_from(entry: &'a Entry) -> Result<Self, Self::Error> {
        match entry {
            Entry::OnlyShowIn(value)
            | Entry::NotShowIn(value)
            | Entry::Actions(value)
            | Entry::Categories(value)
            | Entry::MimeType(value)
            | Entry::Implements(value) => Ok(value),
            entry => Err(ValueError(entry.value_type().to_string())),
        }
    }
}

impl<'a> TryFrom<&'a mut Entry> for &'a mut EscapedStrings {
    type Error = MutationValueError;

    fn try_from(entry: &'a mut Entry) -> Result<Self, Self::Error> {
        match entry {
            Entry::OnlyShowIn(value)
            | Entry::NotShowIn(value)
            | Entry::Categories(value)
            | Entry::MimeType(value)
            | Entry::Implements(value) => Ok(value),
            entry => Err(MutationValueError(entry.value_type().to_string())),
        }
    }
}

impl<'a> Extend<&'a EscapedString> for EscapedStrings {
    fn extend<I>(&mut self, iter: I)
    where
        I: IntoIterator<Item = &'a EscapedString>,
    {
        self.0.extend(iter.into_iter().cloned());
    }
}

impl Extend<EscapedString> for EscapedStrings {
    fn extend<I>(&mut self, iter: I)
    where
        I: IntoIterator<Item = EscapedString>,
    {
        self.0.extend(iter);
    }
}

impl IntoIterator for EscapedStrings {
    type Item = EscapedString;
    type IntoIter = std::vec::IntoIter<EscapedString>;
    fn into_iter(self) -> Self::IntoIter {
        self.0.into_iter()
    }
}

impl<'a> IntoIterator for &'a EscapedStrings {
    type Item = &'a EscapedString;
    type IntoIter = std::slice::Iter<'a, EscapedString>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.iter()
    }
}

impl std::ops::Index<usize> for EscapedStrings {
    type Output = EscapedString;

    fn index(&self, index: usize) -> &Self::Output {
        &self.0[index]
    }
}

impl std::ops::IndexMut<usize> for EscapedStrings {
    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
        &mut self.0[index]
    }
}

// }{── LocaleStrings ──────────────────────────────────────────────────────────────────

/// A semicolon-delimited list of [`LocaleString`] values.
///
/// Backs list-typed `localestring(s)` keys such as `Keywords=`.
#[derive(Debug, Clone, PartialEq, Eq, Default, Hash)]
pub struct LocaleStrings(Vec<LocaleString>);

impl LocaleStrings {
    /// Creates a new `LocaleStrings` from a list of already-valid
    /// [`LocaleString`] values.
    ///
    /// No further validation is needed here: each element was already
    /// validated when it was constructed as a `LocaleString`.
    #[inline]
    #[must_use]
    pub fn new(list: Vec<LocaleString>) -> Self {
        Self(list)
    }

    /// Returns the list as a slice of `LocaleString` values.
    #[inline]
    #[must_use]
    pub fn as_slice(&self) -> &[LocaleString] {
        &self.0
    }

    /// Appends a `LocaleString` to the end of the list.
    #[inline]
    pub fn push(&mut self, item: LocaleString) {
        self.0.push(item);
    }

    /// Returns an iterator over the list's `LocaleString` values.
    pub fn iter(&self) -> std::slice::Iter<'_, LocaleString> {
        <&Self as IntoIterator>::into_iter(self)
    }
}

impl AsRef<[LocaleString]> for LocaleStrings {
    fn as_ref(&self) -> &[LocaleString] {
        &self.0
    }
}

impl fmt::Display for LocaleStrings {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for value in &self.0 {
            for c in value.chars() {
                if c == ';' {
                    f.write_str("\\")?;
                }

                write!(f, "{c}")?;
            }

            f.write_str(";")?;
        }

        Ok(())
    }
}

impl std::ops::Deref for LocaleStrings {
    type Target = [LocaleString];

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl FromIterator<LocaleString> for LocaleStrings {
    fn from_iter<I>(iter: I) -> Self
    where
        I: IntoIterator<Item = LocaleString>,
    {
        Self(iter.into_iter().collect())
    }
}

impl From<Vec<LocaleString>> for LocaleStrings {
    fn from(value: Vec<LocaleString>) -> Self {
        Self(value)
    }
}

impl FromStr for LocaleStrings {
    type Err = ParseEntryValueError;

    fn from_str(strings: &str) -> Result<Self, Self::Err> {
        Self::try_from(strings)
    }
}

impl TryFrom<&str> for LocaleStrings {
    type Error = ParseEntryValueError;

    fn try_from(list: &str) -> Result<Self, Self::Error> {
        Ok(Self(split_semicolon_list::<LocaleString>(
            list,
            ParseEntryValueError::ParseLocaleStrings,
        )?))
    }
}

impl TryFrom<String> for LocaleStrings {
    type Error = ParseEntryValueError;

    #[inline]
    fn try_from(value: String) -> Result<Self, Self::Error> {
        Self::try_from(value.as_str())
    }
}

impl<'a> TryFrom<&'a Entry> for &'a LocaleStrings {
    type Error = ValueError;

    fn try_from(entry: &'a Entry) -> Result<Self, Self::Error> {
        let error = ValueError(entry.value_type().to_string());

        match entry {
            Entry::Keywords(value) => Ok(value),
            Entry::Localized(localized) => match &localized.value {
                LocalizedValue::LocalizedKeywords(value) => Ok(value),
                LocalizedValue::Localized(_) => Err(error),
            },
            _ => Err(error),
        }
    }
}

impl<'a> TryFrom<&'a mut Entry> for &'a mut LocaleStrings {
    type Error = MutationValueError;

    fn try_from(entry: &'a mut Entry) -> Result<Self, Self::Error> {
        let error = MutationValueError(entry.value_type().to_string());

        match entry {
            Entry::Keywords(value) => Ok(value),
            Entry::Localized(localized) => match &mut localized.value {
                LocalizedValue::LocalizedKeywords(value) => Ok(value),
                LocalizedValue::Localized(_) => Err(error),
            },
            _ => Err(error),
        }
    }
}

impl Extend<LocaleString> for LocaleStrings {
    fn extend<I>(&mut self, iter: I)
    where
        I: IntoIterator<Item = LocaleString>,
    {
        self.0.extend(iter);
    }
}

impl<'a> Extend<&'a LocaleString> for LocaleStrings {
    fn extend<I>(&mut self, iter: I)
    where
        I: IntoIterator<Item = &'a LocaleString>,
    {
        self.0.extend(iter.into_iter().cloned());
    }
}

impl<'a> IntoIterator for &'a LocaleStrings {
    type Item = &'a LocaleString;
    type IntoIter = std::slice::Iter<'a, LocaleString>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.iter()
    }
}

impl IntoIterator for LocaleStrings {
    type Item = LocaleString;
    type IntoIter = std::vec::IntoIter<LocaleString>;
    fn into_iter(self) -> Self::IntoIter {
        self.0.into_iter()
    }
}

impl std::ops::Index<usize> for LocaleStrings {
    type Output = LocaleString;

    fn index(&self, index: usize) -> &Self::Output {
        &self.0[index]
    }
}

impl std::ops::IndexMut<usize> for LocaleStrings {
    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
        &mut self.0[index]
    }
}

// }{── LocalizedValue ─────────────────────────────────────────────────────────

/// The value carried by an `Entry::Localized` entry.
///
/// `Keywords` is the only localizable standard key that holds a
/// semicolon-delimited list; the other four localizable keys (`Name`,
/// `GenericName`, `Comment`, `Icon`) each hold a single localized string.
///
/// # Examples
///
/// ```rust
/// use file_desktop::key::LocalizedValue;
///
/// let value = LocalizedValue::Localized("Feuerfuchs".parse().unwrap());
/// assert_eq!(value.to_string(), "Feuerfuchs");
///
/// let keywords = LocalizedValue::LocalizedKeywords("Browser;Web".parse().unwrap());
/// assert_eq!(keywords.to_string(), "Browser;Web;");
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum LocalizedValue {
    /// A single localized string; backs `Name`, `GenericName`, `Comment`, and `Icon`.
    Localized(LocaleString),
    /// A semicolon-delimited list of localized strings; backs `Keywords`.
    LocalizedKeywords(LocaleStrings),
}

impl fmt::Display for LocalizedValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Localized(value) => write!(f, "{value}"),
            Self::LocalizedKeywords(value) => write!(f, "{value}"),
        }
    }
}

// }{── ExtensionValue ─────────────────────────────────────────────────────────

/// The value of an `X-` extension key, as carried by [`ExtensionEntry`].
///
/// Like [`LocaleString`]/[`IconString`], this is UTF-8 (not ASCII-restricted
/// like [`EscapedString`]) — only raw control characters are rejected.
///
/// # Examples
///
/// ```rust
/// use file_desktop::key::ExtensionValue;
///
/// let value = ExtensionValue::try_from("enabled").unwrap();
/// assert_eq!(value.as_str(), "enabled");
///
/// assert!(ExtensionValue::try_from("bad\nvalue").is_err()); // raw newline
/// assert!(ExtensionValue::try_from("Hello\tWorld".replace('\t', " ")).is_ok());
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Default, Hash)]
pub struct ExtensionValue(String);

impl ExtensionValue {
    /// Returns the string value as a slice.
    #[inline]
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Consumes the wrapper and returns the inner `String`.
    #[inline]
    #[must_use]
    pub fn into_string(self) -> String {
        self.0
    }
}

impl AsRef<str> for ExtensionValue {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl std::ops::Deref for ExtensionValue {
    type Target = str;

    fn deref(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for ExtensionValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl From<ExtensionValue> for String {
    fn from(value: ExtensionValue) -> Self {
        value.0
    }
}

impl std::str::FromStr for ExtensionValue {
    type Err = ParseEntryValueError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        Self::try_from(value.to_owned())
    }
}

impl TryFrom<&str> for ExtensionValue {
    type Error = ParseEntryValueError;

    #[inline]
    fn try_from(value: &str) -> Result<Self, Self::Error> {
        Self::try_from(value.to_owned())
    }
}

impl TryFrom<String> for ExtensionValue {
    type Error = ParseEntryValueError;

    fn try_from(value: String) -> Result<Self, Self::Error> {
        if value.chars().any(char::is_control) {
            return Err(ParseEntryValueError::ParseExtensionString);
        }

        Ok(Self(value))
    }
}

impl<'a> TryFrom<&'a Entry> for &'a ExtensionValue {
    type Error = ValueError;

    fn try_from(entry: &'a Entry) -> Result<Self, Self::Error> {
        match entry {
            Entry::Extension(extension) => Ok(&extension.value),
            entry => Err(ValueError(entry.value_type().to_string())),
        }
    }
}

impl<'a> TryFrom<&'a mut Entry> for &'a mut ExtensionValue {
    type Error = MutationValueError;

    fn try_from(entry: &'a mut Entry) -> Result<Self, Self::Error> {
        match entry {
            Entry::Extension(extension) => Ok(&mut extension.value),
            entry => Err(MutationValueError(entry.value_type().to_string())),
        }
    }
}

// }{── LocalizedEntry ─────────────────────────────────────────────────────────

/// Represents a localized standard Desktop Entry key and its value.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LocalizedEntry {
    key: EntryKeys,
    locale: Locale,
    pub(crate) value: LocalizedValue,
}

impl LocalizedEntry {
    /// Creates a localized entry after validating key/value compatibility.
    ///
    /// # Errors
    ///
    /// Returns an error if `key` is not localizable, if `locale` is invalid,
    /// or if `value` is incompatible with `key`.
    pub fn try_new(
        key: EntryKeys,
        locale: Locale,
        value: LocalizedValue,
    ) -> Result<Self, ParseEntryError> {
        if key.localizable_key().is_none() {
            return Err(ParseEntryError::ParseKey(ParseKeyError::NotLocalizable));
        }

        match (key, &value) {
            (EntryKeys::Keywords, LocalizedValue::LocalizedKeywords(_))
            | (
                EntryKeys::Name | EntryKeys::GenericName | EntryKeys::Comment | EntryKeys::Icon,
                LocalizedValue::Localized(_),
            ) => {}
            (EntryKeys::Keywords, _) => {
                return Err(ParseEntryError::ParseValue(
                    ParseEntryValueError::ParseLocaleStrings,
                ));
            }
            _ => {
                return Err(ParseEntryError::ParseValue(
                    ParseEntryValueError::ParseLocaleString,
                ));
            }
        }

        Ok(Self { key, locale, value })
    }

    /// Returns the base standard key.
    #[inline]
    #[must_use]
    pub fn key(&self) -> EntryKeys {
        self.key
    }

    /// Returns the locale suffix.
    #[inline]
    #[must_use]
    pub fn locale(&self) -> &Locale {
        &self.locale
    }

    /// Returns the localized value.
    #[inline]
    #[must_use]
    pub fn value(&self) -> &LocalizedValue {
        &self.value
    }
}

impl TryFrom<(&str, &str)> for LocalizedEntry {
    type Error = ParseEntryError;

    fn try_from((key, value): (&str, &str)) -> Result<Self, Self::Error> {
        let (base_key, locale) = split_localized_key(key)?;

        let value = match base_key {
            EntryKeys::Keywords => LocalizedValue::LocalizedKeywords(
                value.parse().map_err(ParseEntryError::ParseValue)?,
            ),
            _ => LocalizedValue::Localized(value.parse().map_err(ParseEntryError::ParseValue)?),
        };

        LocalizedEntry::try_new(base_key, locale.parse()?, value)
    }
}

// }{── ExtensionEntry ─────────────────────────────────────────────────────────

/// Represents a non-standard Desktop Entry extension key and value.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExtensionEntry {
    key: String,
    pub(crate) value: ExtensionValue,
}

impl ExtensionEntry {
    /// Returns the full extension key.
    #[inline]
    #[must_use]
    pub fn key(&self) -> &str {
        &self.key
    }

    /// Returns the extension value.
    #[inline]
    #[must_use]
    pub fn value(&self) -> &str {
        &self.value
    }
}

impl TryFrom<(&str, &str)> for ExtensionEntry {
    type Error = ParseEntryError;

    fn try_from((key, value): (&str, &str)) -> Result<Self, Self::Error> {
        if !is_valid_extension_key(key) {
            return Err(ParseEntryError::ParseKey(
                ParseKeyError::InvalidExtensionKey,
            ));
        }

        Ok(Self {
            key: key.to_owned(),
            value: ExtensionValue::try_from(value)?,
        })
    }
}

// }{── Locale ─────────────────────────────────────────────────────────
//
/// A validated locale suffix used in localized key names.
///
/// The accepted syntax is `lang[_COUNTRY][.ENCODING][@MODIFIER]`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Locale(String);

impl Locale {
    /// Creates a locale suffix after syntax validation.
    ///
    /// Accepted syntax is `lang[_COUNTRY][.ENCODING][@MODIFIER]`.
    ///
    /// # Errors
    ///
    /// Returns `ParseKeyError::InvalidLocale` when `locale` does not follow
    /// the accepted syntax.
    #[inline]
    pub fn try_new(locale: impl AsRef<str>) -> Result<Self, ParseKeyError> {
        locale.as_ref().parse()
    }

    /// Returns the locale suffix as a string slice.
    #[inline]
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl FromStr for Locale {
    type Err = ParseKeyError;

    fn from_str(locale: &str) -> Result<Self, Self::Err> {
        if !is_valid_locale_suffix(locale) {
            return Err(ParseKeyError::InvalidLocale);
        }

        Ok(Self(locale.to_owned()))
    }
}

impl AsRef<str> for Locale {
    #[inline]
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl fmt::Display for Locale {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

// }{── Helper ─────────────────────────────────────────────────────────────────

fn validate_string(
    s: &str,
    validate_characters: fn(&str, ParseEntryValueError) -> Result<(), ParseEntryValueError>,
    error: ParseEntryValueError,
) -> Result<(), ParseEntryValueError> {
    validate_characters(s, error)?;
    validate_escape_sequences_string(s, error)
}

/// Validates that `s` is printable ASCII: every character must be ASCII and
/// not an ASCII control character. Used for `string`-typed values
/// ([`EscapedString`]), which the spec restricts to ASCII.
fn validate_ascii_no_control(
    s: &str,
    error: ParseEntryValueError,
) -> Result<(), ParseEntryValueError> {
    if s.chars().all(|c| c.is_ascii() && !c.is_ascii_control()) {
        Ok(())
    } else {
        Err(error)
    }
}

/// Validates that `s` has no raw Unicode control character. Used for
/// `localestring`/`iconstring`-typed values ([`LocaleString`],
/// [`IconString`]), which the spec allows to be UTF-8 but still forbids
/// raw control characters in.
fn validate_no_control(s: &str, error: ParseEntryValueError) -> Result<(), ParseEntryValueError> {
    if s.chars().any(char::is_control) {
        Err(error)
    } else {
        Ok(())
    }
}

fn validate_escape_sequences_string(
    s: &str,
    error: ParseEntryValueError,
) -> Result<(), ParseEntryValueError> {
    let mut chars = s.chars();

    while let Some(c) = chars.next() {
        if c != '\\' {
            continue;
        }

        match chars.next() {
            Some('s' | 'n' | 't' | 'r' | '\\') => {}
            _ => return Err(error),
        }
    }

    Ok(())
}

/// Splits a semicolon-delimited Desktop Entry value into validated items.
///
/// Escaped semicolons (`\;`) remain within their item. An empty input returns
/// an empty vector; a trailing unescaped semicolon does not add an empty item.
///
/// # Arguments
///
/// * `s` - The semicolon-delimited text to split.
/// * `error` - The error to return when splitting or validating an item fails.
///
/// # Errors
///
/// Returns `error` for a trailing backslash. Returns the conversion error from
/// `T::try_from` when an item is invalid.
///
/// # Examples
///
/// ```rust
/// use file_desktop::error::ParseEntryValueError;
/// use file_desktop::key::{split_semicolon_list, EscapedString};
///
/// let values = split_semicolon_list::<EscapedString>(
///     r"Open;New\;Window;",
///     ParseEntryValueError::ParseEscapedStrings,
/// )
/// .unwrap();
///
/// assert_eq!(values[1].as_str(), r"New;Window");
/// ```
pub fn split_semicolon_list<T>(
    s: &str,
    error: ParseEntryValueError,
) -> Result<Vec<T>, ParseEntryValueError>
where
    T: TryFrom<String, Error = ParseEntryValueError>,
{
    if s.is_empty() {
        return Ok(Vec::new());
    }

    let mut values = Vec::new();
    let mut current = String::new();
    let mut chars = s.chars();

    while let Some(c) = chars.next() {
        match c {
            '\\' => match chars.next() {
                Some(c) => {
                    if c != ';' {
                        current.push('\\');
                    }

                    current.push(c);
                }
                None => return Err(error),
            },

            ';' => {
                values.push(T::try_from(std::mem::take(&mut current))?);
            }

            _ => current.push(c),
        }
    }

    if !current.is_empty() {
        values.push(T::try_from(current)?);
    }

    Ok(values)
}

fn is_valid_key_token(value: &str) -> bool {
    !value.is_empty()
        && value
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-')
}

/// Validates an extension key name of form `X-...`.
///
/// Extension keys must start with `X-`, and the remaining portion must follow
/// key-name token rules used by Desktop Entry keys.
pub(crate) fn is_valid_extension_key(key: &str) -> bool {
    let Some(token) = key.strip_prefix("X-") else {
        return false;
    };

    if !is_valid_key_token(token) {
        return false;
    }

    !token.ends_with('-')
}

fn is_valid_locale_component(locale: &str, start: usize, end: usize, dot_ok: bool) -> bool {
    if start == end {
        return false;
    }

    locale[start..end]
        .bytes()
        .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-' || (!dot_ok && byte == b'_'))
}

/// Validates locale suffix syntax: `lang[_COUNTRY][.ENCODING][@MODIFIER]`.
pub(crate) fn is_valid_locale_suffix(locale: &str) -> bool {
    if locale.is_empty() {
        return false;
    }

    let bytes = locale.as_bytes();
    let len = bytes.len();
    let mut idx = 0usize;

    while idx < len && bytes[idx].is_ascii_alphabetic() {
        idx += 1;
    }

    if idx == 0 {
        return false;
    }

    if idx < len && bytes[idx] == b'_' {
        let start = idx + 1;
        idx = start;
        while idx < len
            && bytes[idx] != b'.'
            && bytes[idx] != b'@'
            && bytes[idx] != b'_'
            && bytes[idx] != b']'
        {
            idx += 1;
        }

        if !is_valid_locale_component(locale, start, idx, false) {
            return false;
        }
    }

    if idx < len && bytes[idx] == b'.' {
        let start = idx + 1;
        idx = start;
        while idx < len && bytes[idx] != b'@' && bytes[idx] != b'.' {
            idx += 1;
        }

        if !is_valid_locale_component(locale, start, idx, true) {
            return false;
        }
    }

    if idx < len && bytes[idx] == b'@' {
        let start = idx + 1;
        idx = len;

        if !is_valid_locale_component(locale, start, len, true) {
            return false;
        }
    }

    idx == len
}

/// Splits a bracketed, locale-suffixed key name into its base key and locale.
pub(crate) fn split_localized_key(key: &str) -> Result<(EntryKeys, &str), ParseKeyError> {
    let open = key.find('[').ok_or(ParseKeyError::InvalidLocale)?;

    let close = key.rfind(']').ok_or(ParseKeyError::InvalidLocale)?;

    if !key.ends_with(']') || close <= open {
        return Err(ParseKeyError::InvalidLocale);
    }

    let base =
        EntryKeys::parse_localizable_key(&key[..open]).ok_or(ParseKeyError::NotLocalizable)?;

    let locale = &key[open + 1..close];

    if !is_valid_locale_suffix(locale) {
        return Err(ParseKeyError::InvalidLocale);
    }

    Ok((base, locale))
}

// }{── Tests ──────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    mod escaped {
        use super::*;
        mod string {
            use super::*;

            #[test]
            fn construct_wrapper_type_ok() {
                assert!(EscapedString::try_from("Firefox\\n browser").is_ok());
                assert_eq!(
                    EscapedString::try_from("Firefox\\s").unwrap(),
                    EscapedString("Firefox\\s".to_string())
                );
                assert_eq!(
                    EscapedString::try_from("Firefox\\n").unwrap(),
                    EscapedString("Firefox\\n".to_string())
                );
                assert_eq!(
                    EscapedString::try_from("Firefox\\t").unwrap(),
                    EscapedString("Firefox\\t".to_string())
                );
                assert_eq!(
                    EscapedString::try_from("Firefox\\r").unwrap(),
                    EscapedString("Firefox\\r".to_string())
                );
                assert_eq!(
                    EscapedString::try_from("Firefox\\\\").unwrap(),
                    EscapedString("Firefox\\\\".to_string())
                );
            }

            #[test]
            fn construct_wrapper_type_err() {
                assert!(EscapedString::try_from("Müller").is_err());
                assert!(EscapedString::try_from("Firefox\\").is_err());
                assert!(EscapedString::try_from("A\\q").is_err());
            }
        }
        mod strings {
            use super::*;

            #[test]
            fn construct_wrapper_type_ok() {
                let original = r"Edit\;value;Clone;Copy;";
                let parsed = EscapedStrings::try_from(original).unwrap();
                assert_eq!(parsed.to_string(), original);

                let parsed = EscapedStrings::try_from(r"Edit\;Test;Copy;Clone");

                assert_eq!(
                    parsed,
                    EscapedStrings::try_from(parsed.clone().unwrap().to_string())
                );

                assert_eq!(
                    EscapedStrings::try_from(r"Edit\;Test;Copy;Clone;"),
                    Ok(EscapedStrings(vec![
                        EscapedString(r"Edit;Test".to_string()),
                        EscapedString("Copy".to_string()),
                        EscapedString("Clone".to_string())
                    ])),
                );

                assert_eq!(
                    EscapedStrings::try_from(
                        "application/x-cambalache-project;application/x-gtk-builder;application/x-glade;",
                    ),
                    Ok(EscapedStrings(vec![
                        EscapedString("application/x-cambalache-project".to_string()),
                        EscapedString("application/x-gtk-builder".to_string()),
                        EscapedString("application/x-glade".to_string())
                    ])),
                );
            }
        }
        mod helper {
            use super::*;

            fn split_semicolon_list_escaped(
                value: &str,
            ) -> Result<Vec<EscapedString>, ParseEntryValueError> {
                split_semicolon_list::<EscapedString>(
                    value,
                    ParseEntryValueError::ParseEscapedStrings,
                )
            }

            #[test]
            fn split_semicolon_list_ok() {
                assert_eq!(split_semicolon_list_escaped(""), Ok(vec![]));

                assert_eq!(
                    split_semicolon_list_escaped("Edit\\;value;Clone;Copy"),
                    Ok(vec![
                        EscapedString("Edit;value".to_string()),
                        EscapedString("Clone".to_string()),
                        EscapedString("Copy".to_string())
                    ]),
                );

                assert_eq!(
                    split_semicolon_list_escaped("GTK;Utility;"),
                    Ok(vec![
                        EscapedString("GTK".to_string()),
                        EscapedString("Utility".to_string())
                    ]),
                );

                assert_eq!(
                    split_semicolon_list_escaped("\\;;Copy"),
                    Ok(vec![
                        EscapedString(";".to_string()),
                        EscapedString("Copy".to_string())
                    ]),
                );

                assert_eq!(
                    split_semicolon_list_escaped("\\;;"),
                    Ok(vec![EscapedString(";".to_string())]),
                );

                assert_eq!(
                    split_semicolon_list_escaped("\\;"),
                    Ok(vec![EscapedString(";".to_string())]),
                );

                assert_eq!(
                    split_semicolon_list_escaped(";"),
                    Ok(vec![EscapedString("".to_string())]),
                );

                assert_eq!(
                    split_semicolon_list_escaped(";;"),
                    Ok(vec![
                        EscapedString("".to_string()),
                        EscapedString("".to_string())
                    ]),
                );

                assert_eq!(
                    split_semicolon_list_escaped("A\\;B\\;C;D"),
                    Ok(vec![
                        EscapedString("A;B;C".into()),
                        EscapedString("D".into()),
                    ]),
                );

                assert_eq!(
                    split_semicolon_list_escaped("A;;B"),
                    Ok(vec![
                        EscapedString("A".into()),
                        EscapedString("".into()),
                        EscapedString("B".into()),
                    ]),
                );

                assert_eq!(
                    split_semicolon_list_escaped(";A"),
                    Ok(vec![EscapedString("".into()), EscapedString("A".into()),]),
                );
            }

            #[test]
            fn split_semicolon_list_err() {
                assert!(split_semicolon_list_escaped("Café").is_err());

                assert!(split_semicolon_list_escaped("Edit\\q").is_err());

                assert!(split_semicolon_list_escaped("Edit\\").is_err());

                assert!(split_semicolon_list_escaped("Edit\\x;Copy").is_err());

                assert!(split_semicolon_list_escaped("Café").is_err());
            }
        }
    }

    mod locale {
        use super::*;
        mod string {}

        mod strings {
            use super::*;

            #[test]
            fn construct_wrapper_type() {
                assert!(LocaleString::try_from("Café").is_ok());
                assert_eq!(
                    LocaleString::try_from("Café"),
                    Ok(LocaleString("Café".to_string()))
                );
            }
        }

        mod helper {
            use super::*;

            fn split_semicolon_list_locale(
                value: &str,
            ) -> Result<Vec<LocaleString>, ParseEntryValueError> {
                split_semicolon_list::<LocaleString>(
                    value,
                    ParseEntryValueError::ParseLocaleStrings,
                )
            }

            #[test]
            fn split_semicolon_list_ok() {
                assert_eq!(
                    split_semicolon_list_locale("Café"),
                    Ok(vec![LocaleString("Café".to_string())]),
                );

                let list = split_semicolon_list_locale("Café").unwrap();
                assert_eq!(list.len(), 1);
                assert_eq!(list[0].to_string(), "Café");

                let result = split_semicolon_list_locale("Müller\\;Spiele;Unterhaltung;");
                assert!(result.is_ok());
                let vec = result.unwrap();
                assert_eq!(vec.len(), 2);
                assert_eq!(vec[0].as_str(), "Müller;Spiele");
                assert_eq!(vec[1].as_str(), "Unterhaltung");
            }
        }
    }

    mod key {
        use super::*;

        // ──────────────────────────────────────────────────────────
        // Private API tests: ParseKeyError has a pub(crate) inner field,
        // so only in-crate tests can construct and compare against it.
        // All public API behavior is tested in tests/unit_tests_key.rs.
        // ──────────────────────────────────────────────────────────

        // Verifies that from_str("") returns a ParseKeyError containing the original empty string.
        #[test]
        fn from_str_empty_string_returns_parse_key_error_with_original() {
            assert_eq!(EntryKeys::from_str(""), Err(ParseKeyError::NonStandardKey));
        }

        // Verifies that from_str for an unknown key returns a ParseKeyError containing the original string.
        #[test]
        fn from_str_unknown_key_returns_parse_key_error_with_original() {
            let result = EntryKeys::from_str("UnknownKey");
            assert_eq!(result, Err(ParseKeyError::NonStandardKey));
        }

        #[test]
        fn split_localized() {
            assert_eq!(split_localized_key("Name[de]"), Ok((EntryKeys::Name, "de")));
            assert_eq!(
                split_localized_key("Name"),
                Err(ParseKeyError::InvalidLocale)
            );
            assert_eq!(
                split_localized_key("Exec[de]"),
                Err(ParseKeyError::NotLocalizable)
            ); // Exec isn't localizable
        }

        #[test]
        fn extension_key_validation_accepts_valid_examples() {
            assert!(is_valid_extension_key("X-Test"));
            assert!(is_valid_extension_key("X-GNOME-FullName"));
            assert!(is_valid_extension_key("X-KDE-Submenu"));
            assert!(is_valid_extension_key("X-MyCompany-Feature"));
        }

        #[test]
        fn extension_key_validation_rejects_invalid_examples() {
            assert!(!is_valid_extension_key("X-"));
            assert!(!is_valid_extension_key("X-foo bar"));
            assert!(!is_valid_extension_key("X-!!!"));
            assert!(is_valid_extension_key("X-abc"));
        }

        #[test]
        fn locale_suffix_validation_accepts_valid_examples() {
            assert!(is_valid_locale_suffix("de"));
            assert!(is_valid_locale_suffix("de_DE"));
            assert!(is_valid_locale_suffix("de_DE.UTF-8"));
            assert!(is_valid_locale_suffix("de_DE@euro"));
            assert!(is_valid_locale_suffix("de_DE.UTF-8@euro"));
        }

        #[test]
        fn locale_suffix_validation_rejects_invalid_examples() {
            assert!(!is_valid_locale_suffix(""));
            assert!(!is_valid_locale_suffix("!!!"));
            assert!(!is_valid_locale_suffix("de DE"));
            assert!(!is_valid_locale_suffix("de][bad"));
            assert!(!is_valid_locale_suffix("de@"));
            assert!(!is_valid_locale_suffix("_DE"));
            assert!(!is_valid_locale_suffix("de."));
            assert!(!is_valid_locale_suffix("de.UTF-8.UTF-16"));
        }

        #[test]
        fn split_localized_key_accepts_valid_localized_examples() {
            assert_eq!(
                split_localized_key("Name[de_DE.UTF-8@euro]"),
                Ok((EntryKeys::Name, "de_DE.UTF-8@euro"))
            );
            assert_eq!(
                split_localized_key("Comment[de_DE]"),
                Ok((EntryKeys::Comment, "de_DE"))
            );
        }

        #[test]
        fn split_localized_key_rejects_invalid_localized_examples() {
            assert_eq!(
                split_localized_key("Name[]"),
                Err(ParseKeyError::InvalidLocale)
            );
            assert_eq!(
                split_localized_key("Name[!!!]"),
                Err(ParseKeyError::InvalidLocale)
            );
            assert_eq!(
                split_localized_key("Name[de DE]"),
                Err(ParseKeyError::InvalidLocale)
            );
            assert_eq!(
                split_localized_key("Name[de][bad]"),
                Err(ParseKeyError::InvalidLocale)
            );
            assert_eq!(
                split_localized_key("Name[de@]"),
                Err(ParseKeyError::InvalidLocale)
            );
            assert_eq!(
                split_localized_key("Name[_DE]"),
                Err(ParseKeyError::InvalidLocale)
            );
            assert_eq!(
                split_localized_key("Name[de.]"),
                Err(ParseKeyError::InvalidLocale)
            );
            assert_eq!(
                split_localized_key("Name[de.UTF-8.UTF-16]"),
                Err(ParseKeyError::InvalidLocale)
            );
        }

        #[test]
        fn locale_suffix_validation_rejects_duplicate_or_misordered_sections() {
            assert!(!is_valid_locale_suffix("de__DE"));
            assert!(!is_valid_locale_suffix("de@euro.UTF-8"));
            assert!(!is_valid_locale_suffix("de.UTF-8_DE"));
            assert!(!is_valid_locale_suffix("de_DE@euro@x"));
            assert!(!is_valid_locale_suffix("de..UTF-8"));
        }
    }

    mod version {
        use super::*;
        use std::collections::HashSet;

        // ──────────────────────────────────────────────────────────
        // VERSION_EXCLUDES constant
        // ──────────────────────────────────────────────────────────

        // Verifies that VERSION_EXCLUDES contains the six keys added after v1.0.
        #[test]
        fn test_version_excludes_contains_expected_keys() {
            assert_eq!(VERSION_EXCLUDES.len(), 6);
            assert!(VERSION_EXCLUDES.contains(&"DBusActivatable"));
            assert!(VERSION_EXCLUDES.contains(&"Actions"));
            assert!(VERSION_EXCLUDES.contains(&"Keywords"));
            assert!(VERSION_EXCLUDES.contains(&"Implements"));
            assert!(VERSION_EXCLUDES.contains(&"PrefersNonDefaultGPU"));
            assert!(VERSION_EXCLUDES.contains(&"SingleMainWindow"));
        }

        // Verifies that VERSION_EXCLUDES does not contain any base v1.0 keys.
        #[test]
        fn test_version_excludes_does_not_contain_v1_0_keys() {
            let base_keys = [
                "Type",
                "Version",
                "Name",
                "GenericName",
                "NoDisplay",
                "Comment",
                "Icon",
                "Hidden",
                "OnlyShowIn",
                "NotShowIn",
                "TryExec",
                "Exec",
                "Path",
                "Terminal",
                "MimeType",
                "Categories",
                "StartupNotify",
                "StartupWMClass",
                "URL",
            ];
            for k in &base_keys {
                assert!(
                    !VERSION_EXCLUDES.contains(k),
                    "{k} should not be in VERSION_EXCLUDES"
                );
            }
        }

        // Verifies that Display output matches the key string for all 25 variants.
        #[test]
        fn test_entry_keys_display_all() {
            for key_str in EntryKeys::KEYS {
                let variant = EntryKeys::from_str(key_str).unwrap();
                assert_eq!(format!("{variant}"), *key_str);
            }
        }

        // ──────────────────────────────────────────────────────────
        // EntryKeys: FromStr round-trip with key()
        // ──────────────────────────────────────────────────────────

        // Verifies that from_str(key.key()) == Ok(key) for every variant,
        // ensuring the key() → from_str round-trip is lossless.
        #[test]
        fn test_entry_keys_from_str_roundtrip() {
            for key_str in EntryKeys::KEYS {
                let parsed = EntryKeys::from_str(key_str).unwrap();
                assert_eq!(parsed.key(), *key_str);
            }
        }

        // ──────────────────────────────────────────────────────────
        // EntryKeys: key() method
        // ──────────────────────────────────────────────────────────

        // Verifies that key() matches the corresponding KEYS constant element for every variant.
        #[test]
        fn test_entry_keys_key_matches_keys_constant() {
            let variants: [(EntryKeys, usize); 25] = [
                (EntryKeys::Type, 0),
                (EntryKeys::Version, 1),
                (EntryKeys::Name, 2),
                (EntryKeys::GenericName, 3),
                (EntryKeys::NoDisplay, 4),
                (EntryKeys::Comment, 5),
                (EntryKeys::Icon, 6),
                (EntryKeys::Hidden, 7),
                (EntryKeys::OnlyShowIn, 8),
                (EntryKeys::NotShowIn, 9),
                (EntryKeys::DBusActivatable, 10),
                (EntryKeys::TryExec, 11),
                (EntryKeys::Exec, 12),
                (EntryKeys::Path, 13),
                (EntryKeys::Terminal, 14),
                (EntryKeys::Actions, 15),
                (EntryKeys::MimeType, 16),
                (EntryKeys::Categories, 17),
                (EntryKeys::Implements, 18),
                (EntryKeys::Keywords, 19),
                (EntryKeys::StartupNotify, 20),
                (EntryKeys::StartupWMClass, 21),
                (EntryKeys::URL, 22),
                (EntryKeys::PrefersNonDefaultGPU, 23),
                (EntryKeys::SingleMainWindow, 24),
            ];
            for (variant, idx) in variants {
                assert_eq!(variant.key(), EntryKeys::KEYS[idx]);
            }
        }

        // ──────────────────────────────────────────────────────────
        // EntryKeys::KEYS constant
        // ──────────────────────────────────────────────────────────

        // Verifies that KEYS contains exactly 25 elements.
        #[test]
        fn test_entry_keys_constant_has_25_elements() {
            assert_eq!(EntryKeys::KEYS.len(), 25);
        }

        // Verifies that KEYS contains exactly 25 unique entries.
        #[test]
        fn test_entry_keys_uniqueness_in_keys_constant() {
            let set: HashSet<&str> = EntryKeys::KEYS.iter().copied().collect();
            assert_eq!(set.len(), EntryKeys::KEYS.len());
        }

        // Verifies that the first and last entries of KEYS match the expected boundary keys.
        #[test]
        fn test_entry_keys_constant_first_and_last() {
            assert_eq!(EntryKeys::KEYS[0], "Type");
            assert_eq!(EntryKeys::KEYS[24], "SingleMainWindow");
        }

        // ──────────────────────────────────────────────────────────
        // AllKeys ExactSizeIterator
        // ──────────────────────────────────────────────────────────

        // Verifies that the all_keys().len() iterator length is exactly 25 elements.
        #[test]
        fn test_entry_keys_iter_len() {
            let entry_keys = EntryKeys::all_keys();
            assert_eq!(entry_keys.len(), 25);
        }

        // Verifies that the all_keys().len() iterator length is 24 elements.
        #[test]
        fn test_entry_keys_iter_next_len() {
            let mut entry_keys = EntryKeys::all_keys();
            let _ = entry_keys.next();

            assert_eq!(entry_keys.len(), 24);
        }

        // ──────────────────────────────────────────────────────────
        // AllKeys DoubleEndedIterator
        // ──────────────────────────────────────────────────────────

        // Verifies that collecting the all_keys().rev() iterator equals the KEYS rev constant.
        #[test]
        fn test_entry_keys_test_iter_rev_collect() {
            assert_eq!(
                EntryKeys::all_keys().rev().collect::<Vec<_>>(),
                EntryKeys::KEYS.iter().cloned().rev().collect::<Vec<_>>()
            );
        }

        // ──────────────────────────────────────────────────────────
        // AllKeys iterator
        // ──────────────────────────────────────────────────────────

        // Verifies that collecting the all_keys() iterator equals the KEYS constant.
        #[test]
        fn test_entry_keys_test_iter_collect() {
            assert_eq!(EntryKeys::all_keys().collect::<Vec<_>>(), EntryKeys::KEYS);
        }
    }
}

// }────────────────────────────────────────────────────────────────────────────