paneru 0.5.2

A sliding, tiling window manager for MacOS.
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
use arc_swap::{ArcSwap, Guard};
use bevy::ecs::resource::Resource;
use objc2_core_foundation::{CFData, CFString};
use regex::Regex;
use serde::{Deserialize, Deserializer, de};
use std::{
    collections::HashMap,
    env,
    ffi::c_void,
    fs::{OpenOptions, create_dir_all, read_to_string},
    io::{ErrorKind, Write},
    path::{Path, PathBuf},
    ptr::NonNull,
    sync::{Arc, LazyLock},
    time::Duration,
};
use stdext::function_name;
use tracing::{error, info, warn};

use self::decorations::{
    BorderRadiusOption, DescriptorStyle, IndicatorFormat, IndicatorStyle, MenubarOrientation,
};
use self::swipe::SwipeGestureDirection;

#[cfg(test)]
use crate::commands::{MoveFocus, Operation, ResizeDirection};
use crate::{
    commands::Command,
    manager::ProcessApi,
    platform::{Modifiers, OSStatus, macos_major_version},
};
use crate::{
    errors::{Error, Result},
    util::MacResult,
};
use crate::{platform::CFStringRef, util::AXUIWrapper};

pub mod decorations;
pub mod padding;
pub mod snippet;
pub mod swipe;

/// A `LazyLock` that determines the path to the application's configuration file.
/// It checks the `PANERU_CONFIG` environment variable first, then standard XDG locations and user home directory.
/// If no configuration file is found, a minimal one is created in the user's
/// XDG configuration directory so a fresh app installation can start with the
/// built-in defaults.
/// The TOML configuration file, if there is one to use. `None` when an
/// `init.lua` exists, since a script disables the TOML entirely (see
/// [`Config::defaults`]).
pub static CONFIGURATION_FILE: LazyLock<Option<PathBuf>> = LazyLock::new(|| {
    #[cfg(feature = "lua")]
    if let Some(script) = discover_lua_file() {
        info!(
            "{}: {} is in charge; the TOML configuration is ignored",
            function_name!(),
            script.display()
        );
        return None;
    }
    if let Some(path) = discover_configuration_file() {
        return Some(path);
    }
    Some(create_default_configuration_file().unwrap_or_else(|error| {
        panic!(
            "{}: Unable to create default configuration: {error}",
            function_name!()
        )
    }))
});

const DEFAULT_CONFIGURATION: &str = "# Paneru configuration\n\n[options]\n\n[bindings]\n";

fn default_configuration_file() -> std::io::Result<PathBuf> {
    let config_home = env::var_os("XDG_CONFIG_HOME")
        .map(PathBuf::from)
        .or_else(|| env::var_os("HOME").map(|home| PathBuf::from(home).join(".config")))
        .ok_or_else(|| {
            std::io::Error::new(
                ErrorKind::NotFound,
                "neither XDG_CONFIG_HOME nor HOME is set",
            )
        })?;

    Ok(config_home.join("paneru").join("paneru.toml"))
}

fn create_default_configuration_file() -> std::io::Result<PathBuf> {
    let path = default_configuration_file()?;
    if create_configuration_file_at(&path)? {
        info!("Created default configuration at {}", path.display());
    }
    Ok(path)
}

fn create_configuration_file_at(path: &Path) -> std::io::Result<bool> {
    let parent = path.parent().ok_or_else(|| {
        std::io::Error::new(ErrorKind::InvalidInput, "configuration path has no parent")
    })?;
    create_dir_all(parent)?;

    match OpenOptions::new().write(true).create_new(true).open(path) {
        Ok(mut file) => {
            file.write_all(DEFAULT_CONFIGURATION.as_bytes())?;
            Ok(true)
        }
        Err(error) if error.kind() == ErrorKind::AlreadyExists => Ok(false),
        Err(error) => Err(error),
    }
}

/// Finds the first existing configuration file from supported locations.
/// Unlike [`CONFIGURATION_FILE`], this does not panic when no file is found.
pub fn discover_configuration_file() -> Option<PathBuf> {
    if let Ok(path_str) = env::var("PANERU_CONFIG") {
        let path = PathBuf::from(path_str);
        if path.exists() {
            return Some(path);
        }
        warn!(
            "{}: $PANERU_CONFIG is set to {}, but the file does not exist. Falling back to default locations.",
            function_name!(),
            path.display()
        );
    }

    let standard_paths = [
        env::var("HOME")
            .ok()
            .map(|h| PathBuf::from(h).join(".paneru")),
        env::var("HOME")
            .ok()
            .map(|h| PathBuf::from(h).join(".paneru.toml")),
    ];

    let xdg_dirs = xdg::BaseDirectories::with_prefix("paneru");
    let xdg_config_paths = xdg_dirs.find_config_files("paneru.toml");

    standard_paths
        .into_iter()
        .flatten()
        .chain(xdg_config_paths)
        .find(|path| path.exists())
}

/// The default Lua init script, written on first launch when no script exists so the
/// file watcher always has a concrete path to observe for hot reloading.
#[cfg(feature = "lua")]
const DEFAULT_LUA_SCRIPT: &str = "\
-- Paneru Lua configuration (hot-reloaded on save).
--
-- Hook into window-manager events:
--   paneru.on(\"window_focused\", function(e) paneru.log(\"focused \" .. e.window_id) end)
--
-- Bind keys to commands (chord syntax matches [bindings]):
--   paneru.bind(\"alt - b\", \"window balance\")
--
-- ...or to a function. Handlers are given the whole layout as a value they can
-- transform; nothing moves until you return one, so computing a layout and
-- discarding it costs nothing. See CONFIGURATION.md.
--   paneru.bind(\"alt - j\", function(ws)
--     return ws:focus(ws:east(ws:focused()))
--   end)
";

/// Returns the default location for the Lua init script (`<config>/paneru/init.lua`).
#[cfg(feature = "lua")]
fn default_lua_file() -> std::io::Result<PathBuf> {
    let config_home = env::var_os("XDG_CONFIG_HOME")
        .map(PathBuf::from)
        .or_else(|| env::var_os("HOME").map(|home| PathBuf::from(home).join(".config")))
        .ok_or_else(|| {
            std::io::Error::new(
                ErrorKind::NotFound,
                "neither XDG_CONFIG_HOME nor HOME is set",
            )
        })?;

    Ok(config_home.join("paneru").join("init.lua"))
}

/// Finds the first existing Lua init script from supported locations, mirroring
/// [`discover_configuration_file`]. Honors `$PANERU_LUA` first.
#[cfg(feature = "lua")]
pub fn discover_lua_file() -> Option<PathBuf> {
    if let Ok(path_str) = env::var("PANERU_LUA") {
        let path = PathBuf::from(path_str);
        if path.exists() {
            return Some(path);
        }
        warn!(
            "{}: $PANERU_LUA is set to {}, but the file does not exist. Falling back to default locations.",
            function_name!(),
            path.display()
        );
    }

    let standard_paths = [env::var("HOME")
        .ok()
        .map(|h| PathBuf::from(h).join(".paneru.lua"))];

    let xdg_dirs = xdg::BaseDirectories::with_prefix("paneru");
    let xdg_paths = xdg_dirs.find_config_files("init.lua");

    standard_paths
        .into_iter()
        .flatten()
        .chain(xdg_paths)
        .find(|path| path.exists())
}

/// Returns the path to the Lua init script, creating a default one at the XDG
/// location if none exists.
///
/// Returns `Ok(None)` instead if a `paneru.toml` already exists: planting a
/// script beside an existing TOML would silently override it (see
/// [`CONFIGURATION_FILE`]).
#[cfg(feature = "lua")]
pub fn ensure_lua_file() -> std::io::Result<Option<PathBuf>> {
    if let Some(path) = discover_lua_file() {
        return Ok(Some(path));
    }
    if let Some(toml) = discover_configuration_file() {
        info!(
            "{}: {} is the active configuration; not creating a default init.lua",
            function_name!(),
            toml.display()
        );
        return Ok(None);
    }
    let path = default_lua_file()?;
    if create_lua_file_at(&path)? {
        info!("Created default Lua script at {}", path.display());
    }
    Ok(Some(path))
}

#[cfg(feature = "lua")]
fn create_lua_file_at(path: &Path) -> std::io::Result<bool> {
    let parent = path.parent().ok_or_else(|| {
        std::io::Error::new(ErrorKind::InvalidInput, "Lua script path has no parent")
    })?;
    create_dir_all(parent)?;

    match OpenOptions::new().write(true).create_new(true).open(path) {
        Ok(mut file) => {
            file.write_all(DEFAULT_LUA_SCRIPT.as_bytes())?;
            Ok(true)
        }
        Err(error) if error.kind() == ErrorKind::AlreadyExists => Ok(false),
        Err(error) => Err(error),
    }
}

/// Returns the list of deprecated top-level `[options]` keys present in a TOML config.
pub fn deprecated_options_in_input(input: &str) -> Result<Vec<String>> {
    const DEPRECATED_KEYS: [&str; 16] = [
        "padding_top",
        "padding_bottom",
        "padding_left",
        "padding_right",
        "dim_inactive_windows",
        "dim_inactive_color",
        "border_active_window",
        "border_color",
        "border_opacity",
        "border_width",
        "border_radius",
        "swipe_gesture_fingers",
        "swipe_gesture_direction",
        "continuous_swipe",
        "swipe_sensitivity",
        "swipe_deceleration",
    ];

    let value: toml::Value = toml::from_str(input)?;
    let Some(options) = value.get("options").and_then(toml::Value::as_table) else {
        return Ok(Vec::new());
    };

    Ok(DEPRECATED_KEYS
        .into_iter()
        .filter(|key| options.contains_key(*key))
        .map(str::to_string)
        .collect())
}

/// Returns deprecated top-level `[options]` keys present in the config file.
pub fn deprecated_options_in_file(path: &Path) -> Result<Vec<String>> {
    let input = read_to_string(path)?;
    deprecated_options_in_input(&input)
}

/// Parses a command argument vector into a [`Command`] (e.g. `["window",
/// "focus", "east"]`), mapping the shared vocabulary crate's parse error into
/// this crate's configuration error.
pub fn parse_command(argv: &[&str]) -> Result<Command> {
    crate::types::commands::parse_command(argv)
        .map_err(|err| Error::InvalidConfig(format!("{}: {err}", function_name!())))
}

/// `Config` manages the application's configuration, including options, keybindings, and window-specific parameters.
/// It provides methods for loading, reloading, and querying configuration settings.
#[derive(Clone, Debug, Resource)]
pub struct Config {
    inner: Arc<ArcSwap<InnerConfig>>,
}

impl Config {
    /// Creates a new `Config` instance by loading the configuration from the specified path.
    ///
    /// # Arguments
    ///
    /// * `path` - A reference to the path of the configuration file.
    ///
    /// # Returns
    ///
    /// `Ok(Self)` if the configuration is loaded successfully, otherwise `Err(Error)` with an error message.
    pub fn new(path: &Path) -> Result<Self> {
        let input = read_to_string(path)?;
        Ok(Config {
            inner: Arc::new(ArcSwap::from_pointee(InnerConfig::new(&input)?)),
        })
    }

    /// The configuration with every option left at its default, used when
    /// there is no TOML file (e.g. a Lua-only setup; see [`CONFIGURATION_FILE`]).
    /// Parses the same text the generated stub would contain.
    pub fn defaults() -> Result<Self> {
        Ok(Config {
            inner: Arc::new(ArcSwap::from_pointee(InnerConfig::new(
                DEFAULT_CONFIGURATION,
            )?)),
        })
    }

    /// Loads `path` if there is one, otherwise falls back to the defaults.
    pub fn load(path: Option<&Path>) -> Result<Self> {
        match path {
            Some(path) => Self::new(path),
            None => Self::defaults(),
        }
    }

    /// Reloads the configuration from the specified path, updating the internal options and keybindings.
    ///
    /// # Arguments
    ///
    /// * `path` - A reference to the path of the new configuration file.
    ///
    /// # Returns
    ///
    /// `Ok(())` if the configuration is reloaded successfully, otherwise `Err(Error)` with an error message.
    pub fn reload_config(&mut self, path: &Path) -> Result<()> {
        let input = read_to_string(path)?;
        let new = InnerConfig::new(&input)?;
        self.inner.store(Arc::new(new));
        Ok(())
    }

    /// Atomically adopts another config's inner data via a lock-free
    /// `ArcSwap::store`, so every shared handle to this `Config` observes the
    /// new settings. Used by the Lua hot-reload path.
    #[cfg(feature = "lua")]
    pub(crate) fn replace_inner_from(&self, other: &Config) {
        self.inner.store(other.inner.load_full());
    }

    /// Returns a read guard to the inner `InnerConfig` for read-only access.
    ///
    /// # Returns
    ///
    /// A `Guard<Arc<InnerConfig>>` allowing read access to `InnerConfig`.
    fn inner(&self) -> Guard<Arc<InnerConfig>> {
        self.inner.load()
    }

    /// Returns a clone of the `MainOptions` from the current configuration.
    ///
    /// # Returns
    ///
    /// A `MainOptions` struct containing the main configuration options.
    pub fn options(&self) -> MainOptions {
        self.inner().options.clone()
    }

    // Exponential ease-out decay rate (per second) consumed by the animation
    // systems as `t = 1 - e^(-rate*dt)`. Higher values feel snappier; very large
    // values collapse to an instant snap.
    // Suggested range: 8..20 for a fluid feel. Unset = instant (no animation),
    pub fn animation_speed(&self) -> f64 {
        self.options()
            .animation_speed
            // If unset, set it to something high, so the move happens immediately,
            // effectively disabling animation.
            .unwrap_or(1_000_000.0)
            .max(0.0)
    }

    /// Finds a keybinding matching the given `keycode` and `modifier` mask.
    ///
    /// # Arguments
    ///
    /// * `keycode` - The raw key code of the keybinding to find.
    /// * `mask` - The modifier mask (e.g., `Alt`, `Shift`, `Cmd`, `Ctrl`) of the keybinding.
    ///
    /// # Returns
    ///
    /// `Some(Command)` if a matching keybinding is found, otherwise `None`.
    pub fn find_keybind(&self, keycode: u8, mask: Modifiers) -> Option<Command> {
        let config = self.inner();
        config
            .bindings
            .values()
            .flat_map(|binds| binds.all())
            .find_map(|bind| {
                (bind.code == keycode && bind.modifiers.matches(mask))
                    .then_some(bind.command.clone())
            })
    }

    /// Finds window properties for a given `title` and `bundle_id`.
    /// It iterates through configured window parameters and returns all matching rules.
    /// A rule matches when its bundle ID (if any) and title regex match.
    ///
    /// # Arguments
    ///
    /// * `title` - The title of the window to match.
    /// * `bundle_id` - The bundle identifier of the application owning the window.
    ///
    /// # Returns
    ///
    /// A `Vec<WindowParams>` containing all matching window rules.
    pub fn find_window_properties(&self, title: &str, bundle_id: &str) -> Vec<WindowParams> {
        self.inner()
            .windows
            .as_ref()
            .map(|windows| {
                windows
                    .values()
                    .filter(|params| {
                        let bundle_match =
                            params.bundle_id.as_ref().map(|id| id.as_str() == bundle_id);
                        bundle_match.is_none_or(|m| m) && params.title.is_match(title)
                    })
                    .cloned()
                    .collect::<Vec<_>>()
            })
            .unwrap_or_default()
    }

    /// Returns `true` if any window rule for the given bundle ID requests that the
    /// process be forcibly managed even when macOS reports it as unobservable.
    pub fn should_force_manage_process(&self, process: &dyn ProcessApi) -> bool {
        self.inner().windows.as_ref().is_some_and(|windows| {
            let Some(bundle_id) = process
                .application()
                .as_ref()
                .and_then(|app| app.bundleIdentifier())
                .map(|id| id.to_string())
            else {
                return false;
            };
            windows.values().any(|params| {
                params
                    .bundle_id
                    .as_ref()
                    .is_some_and(|id| id.as_str() == bundle_id)
                    && params.manage.is_some_and(|manage| manage)
            })
        })
    }

    pub fn sliver_height(&self) -> f64 {
        self.options().sliver_height.unwrap_or(1.0).clamp(0.1, 1.0)
    }

    pub fn sliver_width(&self) -> i32 {
        i32::from(self.options().sliver_width.unwrap_or(5)).max(1)
    }

    pub fn edge_padding(&self) -> (i32, i32, i32, i32) {
        let config = self.inner();
        let o = &config.options;
        let p = config.padding.as_ref();
        (
            i32::from(p.and_then(|p| p.top).or(o.padding_top).unwrap_or(0)),
            i32::from(p.and_then(|p| p.right).or(o.padding_right).unwrap_or(0)),
            i32::from(p.and_then(|p| p.bottom).or(o.padding_bottom).unwrap_or(0)),
            i32::from(p.and_then(|p| p.left).or(o.padding_left).unwrap_or(0)),
        )
    }

    pub fn preset_column_widths(&self) -> Vec<f64> {
        self.options().preset_column_widths
    }

    pub fn preset_stack_heights(&self) -> Vec<f64> {
        self.options().preset_stack_heights
    }

    pub fn swipe_gesture_direction(&self) -> SwipeGestureDirection {
        let config = self.inner();
        config
            .swipe
            .as_ref()
            .and_then(|swipe| swipe.gesture.as_ref())
            .and_then(|gesture| gesture.direction.clone())
            .clone()
            .or(config.options.swipe_gesture_direction.clone())
            .unwrap_or(SwipeGestureDirection::Natural)
    }

    pub fn swipe_gesture_fingers(&self) -> Option<usize> {
        let config = self.inner();
        config
            .swipe
            .as_ref()
            .and_then(|swipe| swipe.gesture.as_ref())
            .and_then(|gesture| gesture.fingers_count)
            .or(config.options.swipe_gesture_fingers)
    }

    pub fn swipe_vertical(&self) -> bool {
        let config = self.inner();
        config
            .swipe
            .as_ref()
            .and_then(|swipe| swipe.gesture.as_ref())
            .and_then(|gesture| gesture.vertical)
            // Enabled by default
            .is_none_or(|vertical| vertical)
    }

    pub fn has_dim_inactive_color(&self) -> bool {
        let config = self.inner();
        config
            .decorations
            .as_ref()
            .and_then(|decorations| decorations.inactive.as_ref())
            .and_then(|inactive| inactive.dim.as_ref())
            .and_then(|dim| dim.color.as_ref())
            .is_some()
            || config.options.dim_inactive_color.is_some()
    }

    pub fn dim_inactive_opacity(&self) -> f32 {
        let config = self.inner();
        let color = config
            .decorations
            .as_ref()
            .and_then(|decorations| decorations.inactive.as_ref())
            .and_then(|inactive| inactive.dim.as_ref())
            .and_then(|dim| dim.color.as_ref())
            .or(config.options.dim_inactive_color.as_ref());
        if color.is_none() {
            return 0.0;
        }
        config
            .decorations
            .as_ref()
            .and_then(|decorations| decorations.inactive.as_ref())
            .and_then(|inactive| inactive.dim.as_ref())
            .and_then(|dim| dim.opacity)
            .or(config.options.dim_inactive_windows)
            .unwrap_or(0.0)
            .clamp(0.0, 1.0)
    }

    pub fn dim_inactive_color(&self) -> (f64, f64, f64) {
        let config = self.inner();
        config
            .decorations
            .as_ref()
            .and_then(|decorations| decorations.inactive.as_ref())
            .and_then(|inactive| inactive.dim.as_ref())
            .and_then(|dim| dim.color.as_deref())
            .or(config.options.dim_inactive_color.as_deref())
            .map_or((0.0, 0.0, 0.0), parse_hex_color)
    }

    pub fn border_active_window(&self) -> bool {
        let config = self.inner();
        config
            .decorations
            .as_ref()
            .and_then(|decorations| decorations.active.as_ref())
            .and_then(|active| active.border.as_ref())
            .and_then(|border| border.enabled)
            .or(config.options.border_active_window)
            .unwrap_or(false)
    }

    pub fn border_color(&self) -> (f64, f64, f64) {
        let config = self.inner();
        config
            .decorations
            .as_ref()
            .and_then(|decorations| decorations.active.as_ref())
            .and_then(|active| active.border.as_ref())
            .and_then(|border| border.color.as_deref())
            .or(config.options.border_color.as_deref())
            .map_or((1.0, 1.0, 1.0), parse_hex_color)
    }

    pub fn border_opacity(&self) -> f64 {
        let config = self.inner();
        config
            .decorations
            .as_ref()
            .and_then(|decorations| decorations.active.as_ref())
            .and_then(|active| active.border.as_ref())
            .and_then(|border| border.opacity)
            .or(config.options.border_opacity)
            .unwrap_or(1.0)
            .clamp(0.0, 1.0)
    }

    pub fn border_width(&self) -> f64 {
        let config = self.inner();
        config
            .decorations
            .as_ref()
            .and_then(|decorations| decorations.active.as_ref())
            .and_then(|active| active.border.as_ref())
            .and_then(|border| border.width)
            .or(config.options.border_width)
            .unwrap_or(2.0)
            .max(0.0)
    }

    pub fn border_radius(&self) -> BorderRadiusOption {
        let config = self.inner();
        match config
            .decorations
            .as_ref()
            .and_then(|decorations| decorations.active.as_ref())
            .and_then(|active| active.border.as_ref())
            .and_then(|border| border.radius.clone())
            .or(config.options.border_radius.clone())
            .unwrap_or(BorderRadiusOption::Auto)
        {
            BorderRadiusOption::Auto if macos_major_version() == 26 => BorderRadiusOption::Auto,
            BorderRadiusOption::Value(value) => BorderRadiusOption::Value(value.max(0.0)),
            BorderRadiusOption::Auto => BorderRadiusOption::Value(10.0),
        }
    }

    pub fn menubar_height(&self) -> Option<i32> {
        self.options().menubar_height.map(i32::from)
    }

    pub fn swipe_sensitivity(&self) -> f64 {
        let config = self.inner();
        config
            .swipe
            .as_ref()
            .and_then(|swipe| swipe.sensitivity)
            .or(config.options.swipe_sensitivity)
            .unwrap_or(0.35)
            .clamp(0.1, 2.0)
    }

    pub fn continuous_swipe(&self) -> bool {
        let config = self.inner();
        config
            .swipe
            .as_ref()
            .and_then(|swipe| swipe.continuous)
            .or(config.options.continuous_swipe)
            // Default: true (enabled).
            .unwrap_or(true)
    }

    pub fn swipe_deceleration(&self) -> f64 {
        let config = self.inner();
        config
            .swipe
            .as_ref()
            .and_then(|swipe| swipe.deceleration)
            .or(config.options.swipe_deceleration)
            .unwrap_or(4.0)
            .clamp(1.0, 10.0)
    }

    pub fn mouse_resize_modifier(&self) -> Option<Modifiers> {
        self.options().mouse_resize_modifier
    }

    pub fn restore_enabled(&self) -> bool {
        self.inner()
            .restore
            .as_ref()
            .and_then(|restore| restore.enabled)
            .unwrap_or(true)
    }

    pub fn restore_startup_grace(&self) -> Duration {
        Duration::from_millis(
            self.inner()
                .restore
                .as_ref()
                .and_then(|restore| restore.startup_grace_ms)
                .unwrap_or(2000),
        )
    }

    pub fn restore_missing_windows(&self) -> MissingWindowBehavior {
        self.inner()
            .restore
            .as_ref()
            .and_then(|restore| restore.missing_windows)
            .unwrap_or(MissingWindowBehavior::Ignore)
    }

    pub fn swipe_scroll_modifier(&self) -> Modifiers {
        let config = self.inner();
        config
            .swipe
            .as_ref()
            .and_then(|swipe| swipe.scroll.as_ref())
            .and_then(|scroll| scroll.modifier)
            .unwrap_or(Modifiers::ALT)
    }

    pub fn swipe_scroll_vertical_modifier(&self) -> Option<Modifiers> {
        let config = self.inner();
        config
            .swipe
            .as_ref()
            .and_then(|swipe| swipe.scroll.as_ref())
            .and_then(|scroll| scroll.vertical_modifier)
    }

    pub fn swipe_scroll_window_step(&self) -> bool {
        self.inner()
            .swipe
            .as_ref()
            .and_then(|swipe| swipe.scroll.as_ref())
            .and_then(|scroll| scroll.window_step)
            .unwrap_or(false)
    }

    pub fn window_dim_ratio(&self, is_dark: bool) -> Option<f32> {
        let config = self.inner();
        if config
            .decorations
            .as_ref()
            .and_then(|decorations| decorations.inactive.as_ref())
            .and_then(|inactive| inactive.dim.as_ref())
            .and_then(|dim| dim.color.as_ref())
            .is_some()
            || config.options.dim_inactive_color.is_some()
        {
            // This is not our dimming - it's the color one.
            return None;
        }

        let dim = config
            .decorations
            .as_ref()
            .and_then(|decorations| decorations.inactive.as_ref())
            .and_then(|inactive| inactive.dim.as_ref());

        if is_dark {
            dim.and_then(|d| d.opacity_night)
                .or(dim.and_then(|d| d.opacity))
                .or(config.options.dim_inactive_windows)
        } else {
            dim.and_then(|d| d.opacity)
                .or(config.options.dim_inactive_windows)
        }
    }

    /// Returns the allowed hidden fraction of a window before a focus change
    /// forces it into view. 0.0 = always bring into view (eager),
    /// 1.0 = never move unless fully invisible (lazy). Default: 0.0.
    pub fn window_hidden_ratio(&self) -> f64 {
        self.options()
            .window_hidden_ratio
            .unwrap_or(0.0)
            .clamp(0.0, 1.0)
    }

    pub fn window_resize_cycle(&self) -> bool {
        self.options().window_resize_cycle.unwrap_or(true)
    }

    pub fn auto_center(&self) -> bool {
        self.options().auto_center.is_some_and(|center| center)
    }

    pub fn horizontal_mouse_warp(&self) -> Option<i16> {
        self.options().horizontal_mouse_warp
    }

    /// Returns `true` if focus should follow the mouse based on the current configuration.
    /// If the configuration option is not set, it defaults to `true`.
    pub fn focus_follows_mouse(&self) -> bool {
        // Default is enabled.
        self.options().focus_follows_mouse.is_none_or(|ffm| ffm)
    }

    /// Returns `true` if the mouse cursor should follow the focused window based on the current configuration.
    /// If the configuration option is not set, it defaults to `true`.
    pub fn mouse_follows_focus(&self) -> bool {
        // Default is enabled.
        self.options().mouse_follows_focus.is_none_or(|mff| mff)
    }

    pub fn horizontal_mouse_warp_offset(&self) -> i32 {
        self.options().horizontal_mouse_warp_offset.unwrap_or(0)
    }

    pub fn reap_empty_workspaces(&self) -> bool {
        // Default is disabled..
        self.options()
            .reap_empty_workspaces
            .is_some_and(|reap| reap)
    }

    pub fn native_tabs_enabled(&self) -> bool {
        // Default is enabled.
        !self
            .options()
            .disable_native_tabs
            .is_some_and(|disabled| disabled)
    }

    pub fn workspace_menu_status(&self) -> bool {
        self.inner()
            .decorations
            .as_ref()
            .and_then(|decorations| decorations.workspace_menu_status)
            .is_none_or(|enabled| enabled)
    }

    pub fn workspace_popup_status(&self) -> bool {
        self.inner()
            .decorations
            .as_ref()
            .and_then(|decorations| decorations.workspace_popup_status)
            .is_none_or(|enabled| enabled)
    }

    pub fn virtual_workspace_animations(&self) -> bool {
        // Default is disabled
        self.options()
            .virtual_workspace_animations
            .is_some_and(|enabled| enabled)
    }

    /// Number of virtual workspaces to pre-create on each physical space at
    /// startup. Default: 1 (just the physical space itself, no extra virtual
    /// workspaces).
    pub fn default_workspaces(&self) -> u32 {
        self.inner().default_workspaces.unwrap_or(1).max(1)
    }

    pub fn insert_windows_mid_strip(&self) -> bool {
        // Default is disabled: appending to the end of the strip is the
        // expected behaviour, especially when moving several windows.
        self.options()
            .insert_windows_mid_strip
            .is_some_and(|enabled| enabled)
    }

    pub fn create_workspace_automatically(&self) -> bool {
        self.options()
            .create_virtual_workspace_automatically
            .is_some_and(|enabled| enabled)
    }
    pub fn menubar_orientation(&self) -> MenubarOrientation {
        self.inner()
            .decorations
            .as_ref()
            .and_then(|decorations| decorations.menu.as_ref())
            .and_then(|menubar| menubar.orientation)
            .unwrap_or(MenubarOrientation::Default)
    }
    pub fn menubar_gradient(&self) -> Vec<(f64, f64, f64)> {
        self.inner()
            .decorations
            .as_ref()
            .and_then(|decorations| decorations.menu.as_ref())
            .and_then(|menubar| menubar.colors.as_ref())
            .into_iter()
            .flatten()
            .map(|hex_string| resolve_menubar_color(hex_string))
            .collect()
    }
    /// True when at least one menubar colour is an explicit hex stop rather than
    /// the empty-string system-appearance sentinel.
    pub fn menubar_has_external_gradient(&self) -> bool {
        self.menubar_gradient()
            .iter()
            .any(|(red, _, _)| !red.is_nan())
    }
    pub fn menubar_gradient_angle(&self) -> f64 {
        self.inner()
            .decorations
            .as_ref()
            .and_then(|decorations| decorations.menu.as_ref())
            .and_then(|menubar| menubar.angle)
            .unwrap_or(90.0)
    }
    pub fn menubar_descriptor_style(&self) -> DescriptorStyle {
        self.inner()
            .decorations
            .as_ref()
            .and_then(|decorations| decorations.menu.as_ref())
            .and_then(|menubar| menubar.descriptor.as_ref())
            .and_then(|descriptor_options| descriptor_options.style)
            .unwrap_or(DescriptorStyle::Symbol)
    }
    pub fn menubar_descriptor_text(&self) -> String {
        self.inner()
            .decorations
            .as_ref()
            .and_then(|decorations| decorations.menu.as_ref())
            .and_then(|menubar| menubar.descriptor.as_ref())
            .and_then(|descriptor_options| descriptor_options.text.clone())
            .unwrap_or(String::from("VW"))
    }
    pub fn menubar_descriptor_symbol(&self) -> String {
        self.inner()
            .decorations
            .as_ref()
            .and_then(|decorations| decorations.menu.as_ref())
            .and_then(|menubar| menubar.descriptor.as_ref())
            .and_then(|descriptor_options| descriptor_options.symbol.clone())
            .unwrap_or(String::from("fish.fill"))
    }
    pub fn menubar_indicator_style(&self) -> IndicatorStyle {
        self.inner()
            .decorations
            .as_ref()
            .and_then(|decorations| decorations.menu.as_ref())
            .and_then(|menubar| menubar.indicator.as_ref())
            .and_then(|indicator| indicator.style)
            .unwrap_or(IndicatorStyle::Mono)
    }
    pub fn menubar_indicator_format(&self) -> IndicatorFormat {
        self.inner()
            .decorations
            .as_ref()
            .and_then(|decorations| decorations.menu.as_ref())
            .and_then(|menubar| menubar.indicator.as_ref())
            .and_then(|indicator| indicator.format)
            .unwrap_or(IndicatorFormat::Default)
    }
    pub fn menubar_indicator_font_size(&self) -> f64 {
        const DEFAULT_FONT_SIZE: f64 = 13.0;
        const MIN_FONT_SIZE: f64 = 1.0;
        const MAX_FONT_SIZE: f64 = 24.0;
        self.inner()
            .decorations
            .as_ref()
            .and_then(|decorations| decorations.menu.as_ref())
            .and_then(|menubar| menubar.indicator.as_ref())
            .and_then(|indicator| indicator.font_size)
            .filter(|font_size| font_size.is_finite())
            .unwrap_or(DEFAULT_FONT_SIZE)
            .clamp(MIN_FONT_SIZE, MAX_FONT_SIZE)
    }
    pub fn menubar_indicator_active_character(&self) -> char {
        self.inner()
            .decorations
            .as_ref()
            .and_then(|decorations| decorations.menu.as_ref())
            .and_then(|menubar| menubar.indicator.as_ref())
            .and_then(|indicator| indicator.active_character)
            .unwrap_or('☉')
    }
    pub fn menubar_indicator_inactive_character(&self) -> char {
        self.inner()
            .decorations
            .as_ref()
            .and_then(|decorations| decorations.menu.as_ref())
            .and_then(|menubar| menubar.indicator.as_ref())
            .and_then(|indicator| indicator.inactive_character)
            .unwrap_or('â—‹')
    }
}

fn resolve_menubar_color(hex: &str) -> (f64, f64, f64) {
    let check_string = hex.is_empty();
    if !check_string {
        return parse_hex_color(hex);
    }
    (f64::NAN, f64::NAN, f64::NAN)
}

fn parse_hex_color(hex: &str) -> (f64, f64, f64) {
    let hex = hex.strip_prefix('#').unwrap_or(hex);
    if hex.len() != 6 {
        return (1.0, 1.0, 1.0);
    }
    let r = u8::from_str_radix(&hex[0..2], 16).unwrap_or(255);
    let g = u8::from_str_radix(&hex[2..4], 16).unwrap_or(255);
    let b = u8::from_str_radix(&hex[4..6], 16).unwrap_or(255);
    (
        f64::from(r) / 255.0,
        f64::from(g) / 255.0,
        f64::from(b) / 255.0,
    )
}

impl Default for Config {
    /// Returns a default `Config` instance with an empty `InnerConfig`.
    fn default() -> Self {
        Config {
            inner: Arc::new(ArcSwap::from_pointee(InnerConfig::default())),
        }
    }
}

impl TryFrom<&str> for Config {
    type Error = crate::errors::Error;

    fn try_from(input: &str) -> std::result::Result<Self, Self::Error> {
        Ok(Config {
            inner: Arc::new(ArcSwap::from_pointee(InnerConfig::new(input)?)),
        })
    }
}

impl From<(MainOptions, Vec<WindowParams>)> for Config {
    fn from((options, params): (MainOptions, Vec<WindowParams>)) -> Self {
        Self {
            inner: Arc::new(ArcSwap::from_pointee(InnerConfig {
                options,
                windows: params
                    .into_iter()
                    .enumerate()
                    .map(|(nr, param)| Some((format!("param{nr}"), param)))
                    .collect(),
                ..Default::default()
            })),
        }
    }
}

#[derive(Deserialize, Debug)]
#[serde(untagged)]
enum OneOrMore {
    Single(Keybinding),
    Multiple(Vec<Keybinding>),
}

impl OneOrMore {
    fn all(&self) -> Vec<&Keybinding> {
        match self {
            OneOrMore::Single(one) => vec![one],
            OneOrMore::Multiple(many) => many.iter().collect::<Vec<_>>(),
        }
    }

    fn all_mut(&mut self) -> Vec<&mut Keybinding> {
        match self {
            OneOrMore::Single(one) => vec![one],
            OneOrMore::Multiple(many) => many.iter_mut().collect::<Vec<_>>(),
        }
    }
}

/// `InnerConfig` holds the actual configuration data parsed from a file, including options, keybindings, and window parameters.
/// It is typically accessed via an `Arc<RwLock<InnerConfig>>` within the `Config` struct.
#[derive(Deserialize, Debug, Default)]
struct InnerConfig {
    // Defaulted so a config may omit these; otherwise serde requires them.
    #[serde(default)]
    options: MainOptions,
    #[serde(default)]
    bindings: HashMap<String, OneOrMore>,
    windows: Option<HashMap<String, WindowParams>>,
    decorations: Option<decorations::DecorationsOptions>,
    default_workspaces: Option<u32>,
    swipe: Option<swipe::SwipeOptions>,
    padding: Option<padding::PaddingOptions>,
    restore: Option<RestoreOptions>,
}

impl InnerConfig {
    /// Creates a new `InnerConfig` by reading and parsing the configuration file from the specified `path`.
    ///
    /// # Arguments
    ///
    /// * `path` - A reference to the path of the configuration file.
    ///
    /// # Returns
    ///
    /// `Ok(InnerConfig)` if the configuration is parsed successfully, otherwise `Err(Error)` with an error message.
    fn new(input: &str) -> Result<InnerConfig> {
        InnerConfig::parse_config(input)
    }

    /// Parses the configuration from a string `input`.
    /// It populates the `code` and `command` fields of `Keybinding` by looking up virtual keys and literal keycodes.
    ///
    /// # Arguments
    ///
    /// * `input` - The string content of the configuration file.
    ///
    /// # Returns
    ///
    /// `Ok(InnerConfig)` if the parsing is successful, otherwise `Err(Error)` with an error message.
    fn parse_config(input: &str) -> Result<InnerConfig> {
        let config: InnerConfig = toml::from_str(input)?;
        if !config.needs_virtual_keys() {
            return Ok(config);
        }

        let virtual_keys = generate_virtual_keymap();
        Self::parse_config_with_virtual_keys(input, &virtual_keys)
    }

    fn parse_config_with_virtual_keys(
        input: &str,
        virtual_keys: &[(String, u8)],
    ) -> Result<InnerConfig> {
        let mut config: InnerConfig = toml::from_str(input)?;

        for (command, bindings) in &mut config.bindings {
            let argv = command.split('_').collect::<Vec<_>>();
            for binding in bindings.all_mut() {
                binding.command = parse_command(&argv)?;

                if let Some(code) = keycode_for_key_name(&binding.key, virtual_keys) {
                    binding.code = code;
                    info!("bind: {binding:?}");
                } else {
                    error!("{}: invalid key '{}'", function_name!(), &binding.key);
                }
            }
        }

        // Resolve passthrough keybinding strings into (keycode, modifiers) pairs.
        if let Some(windows) = &mut config.windows {
            for params in windows.values_mut() {
                for input in &params.bindings_passthrough {
                    match resolve_keybinding_str(input, virtual_keys) {
                        Ok(pair) => params.parsed_passthrough.push(pair),
                        Err(err) => error!("passthrough: {err}"),
                    }
                }
            }
        }

        Ok(config)
    }

    fn needs_virtual_keys(&self) -> bool {
        !self.bindings.is_empty()
            || self.windows.as_ref().is_some_and(|windows| {
                windows
                    .values()
                    .any(|params| !params.bindings_passthrough.is_empty())
            })
    }
}

#[derive(Clone, Copy, Debug, Deserialize, PartialEq)]
#[cfg_attr(test, derive(serde::Serialize))]
#[serde(rename_all = "snake_case")]
pub enum MissingWindowBehavior {
    Ignore,
}

#[derive(Clone, Debug, Deserialize, Default)]
#[cfg_attr(test, derive(serde::Serialize))]
pub struct RestoreOptions {
    pub enabled: Option<bool>,
    pub startup_grace_ms: Option<u64>,
    pub missing_windows: Option<MissingWindowBehavior>,
}

/// `MainOptions` represents the primary configuration options for the window manager.
/// These options control various behaviors such as mouse focus, gesture recognition, and window animation.
#[derive(Deserialize, Clone, Debug, Default)]
#[cfg_attr(test, derive(serde::Serialize))]
pub struct MainOptions {
    /// Enables or disables focus follows mouse behavior.
    pub focus_follows_mouse: Option<bool>,
    /// Enables or disables mouse follows focus behavior.
    pub mouse_follows_focus: Option<bool>,
    /// Warps the mouse to the closest screen when at the edge.
    pub horizontal_mouse_warp: Option<i16>,
    /// Vertical pixel offset applied to the warp landing position, signed by
    /// warp direction. Use to compensate for physical desk arrangement
    /// differing from the macOS arrangement (e.g. portrait monitor sitting
    /// higher or lower than the laptop). When warping downward (target below
    /// source) the offset is added; when warping upward, subtracted.
    pub horizontal_mouse_warp_offset: Option<i32>,
    /// A list of preset column widths (as ratios) used for resizing windows.
    #[serde(default = "default_preset_column_widths")]
    pub preset_column_widths: Vec<f64>,
    /// A list of preset heights (as ratios of the viewport) used when resizing
    /// a window vertically inside a stack.
    #[serde(default = "default_preset_stack_heights")]
    pub preset_stack_heights: Vec<f64>,
    /// The animation speed for window movements in pixels per second.
    pub animation_speed: Option<f64>,
    /// Automatically center the window when switching focus with keyboard.
    pub auto_center: Option<bool>,
    /// Height of off-screen window slivers as a ratio (0.0–1.0) of the display height.
    /// Lower values hide the window's corner radius at screen edges.
    /// Default: 1.0 (full height).
    pub sliver_height: Option<f64>,
    /// Width of off-screen window slivers in pixels.
    /// Default: 5 pixels.
    pub sliver_width: Option<u16>,
    /// Legacy top-level padding (deprecated; use `[padding]`).
    pub padding_top: Option<u16>,
    pub padding_bottom: Option<u16>,
    pub padding_left: Option<u16>,
    pub padding_right: Option<u16>,
    /// Legacy top-level dim options (deprecated; use `[decorations.inactive.dim]`).
    pub dim_inactive_windows: Option<f32>,
    pub dim_inactive_color: Option<String>,
    /// Legacy top-level border options (deprecated; use `[decorations.active.border]`).
    pub border_active_window: Option<bool>,
    pub border_color: Option<String>,
    pub border_opacity: Option<f64>,
    pub border_width: Option<f64>,
    #[serde(
        default,
        deserialize_with = "decorations::deserialize_border_radius_option"
    )]
    pub border_radius: Option<BorderRadiusOption>,
    /// Legacy top-level swipe options (deprecated; use `[swipe]`).
    pub swipe_gesture_fingers: Option<usize>,
    pub swipe_gesture_direction: Option<SwipeGestureDirection>,

    #[allow(dead_code)]
    pub continuous_swipe: Option<bool>,
    pub swipe_sensitivity: Option<f64>,
    pub swipe_deceleration: Option<f64>,
    /// The modifier key used for mouse-based window resizing.
    #[serde(default, deserialize_with = "deserialize_modifier")]
    #[cfg_attr(test, serde(serialize_with = "serialize_modifier"))]
    pub mouse_resize_modifier: Option<Modifiers>,
    /// Override the system menubar height (in pixels).
    /// When set, this value is used instead of the height reported by macOS.
    pub menubar_height: Option<u16>,
    /// How much of a window may be hidden before a focus change forces it into
    /// view. 0.0 (default) = always bring into view. 1.0 = never move unless
    /// fully invisible. E.g. 0.5 = tolerate up to 50% hidden.
    pub window_hidden_ratio: Option<f64>,

    /// Whether grow/shrink cycles back when reaching the end of presets. Applies
    /// to both the horizontal and the vertical resize commands.
    /// Default: true (cycles). Set to false to stop at the limits.
    pub window_resize_cycle: Option<bool>,

    /// If enabled, an empty virtual workspace will be removed.
    /// Default: true.
    pub reap_empty_workspaces: Option<bool>,

    /// Disable detection of native macOS tabs. When set, newly-spawned windows are
    /// never auto-merged into a tab group with an existing same-app sibling.
    /// Default: false.
    pub disable_native_tabs: Option<bool>,

    /// Enable animation of virtual workspace swaps.
    /// Off by default, because people use virtual workspaces due to the slow animation of the
    /// native macOS workspaces.
    pub virtual_workspace_animations: Option<bool>,

    /// When moving a window to another virtual workspace, insert it at the column
    /// matching its current on-screen position (keeping it where you see it,
    /// shifting the rest) instead of appending it to the end of the strip.
    /// Off by default.
    pub insert_windows_mid_strip: Option<bool>,

    /// If a non-enumerated (e.g. South) gesture or window movement would target a nonexistent
    /// virtual workspace, create the workspace automatically.
    pub create_virtual_workspace_automatically: Option<bool>,
}

/// Returns a default set of column widths.
pub fn default_preset_column_widths() -> Vec<f64> {
    vec![0.25, 0.33333, 0.50, 0.66667, 0.75, 1.0, 1.5, 2.0]
}

/// Returns a default set of stacked window heights. Unlike widths there is no
/// vertical scrolling, so ratios never exceed the viewport.
pub fn default_preset_stack_heights() -> Vec<f64> {
    vec![0.25, 0.33333, 0.50, 0.66667, 0.75]
}

/// `Keybinding` represents a keyboard shortcut and the command it triggers.
/// It includes the key, its raw keycode, modifier keys, and the associated command.
#[derive(Debug)]
pub struct Keybinding {
    pub key: String,
    pub code: u8,
    pub modifiers: Modifiers,
    pub command: Command,
}

impl<'de> Deserialize<'de> for Keybinding {
    /// Deserializes a `Keybinding` from a string input. The input string is expected to be in a format like "`modifier+modifier-key`" or "`key`".
    /// Examples: "`ctrl+alt-q`", "`shift-tab`", "`h`".
    ///
    /// # Arguments
    ///
    /// * `deserializer` - The deserializer used to parse the input.
    ///
    /// # Returns
    ///
    /// `Ok(Self)` if the deserialization is successful, otherwise `Err(D::Error)` with a custom error message.
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let input = String::deserialize(deserializer)?;
        let mut parts = input.split('-').map(str::trim).collect::<Vec<_>>();
        let key = parts.pop();

        if parts.len() > 1 || key.is_none() {
            return Err(de::Error::custom(format!("Too many dashes: {input:?}")));
        }

        let modifiers = match parts.pop() {
            Some(modifiers) => parse_modifiers(modifiers).map_err(de::Error::custom)?,
            None => Modifiers::empty(),
        };

        Ok(Keybinding {
            key: key.unwrap().to_string(),
            code: 0,
            modifiers,
            command: Command::Quit,
        })
    }
}

/// The initial width of a managed window, either fixed or based on the focused window.
#[derive(Clone, Copy, Debug, Deserialize)]
#[serde(untagged)]
pub enum InitialWindowWidth {
    Ratio(f64),
    Mode(InitialWindowWidthMode),
}

#[derive(Clone, Copy, Debug, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum InitialWindowWidthMode {
    ComplementFocused,
}

impl InitialWindowWidth {
    pub fn ratio(self, focused_ratio: Option<f64>) -> f64 {
        match self {
            Self::Ratio(ratio) => ratio,
            Self::Mode(InitialWindowWidthMode::ComplementFocused) => {
                // The first window, or one opened from an almost full-width
                // window, should occupy the display rather than a tiny sliver.
                let Some(ratio) = focused_ratio.filter(|ratio| ratio.is_finite() && *ratio > 0.0)
                else {
                    return 1.0;
                };
                if ratio >= 0.95 { 1.0 } else { 1.0 - ratio }
            }
        }
    }
}

#[test]
#[allow(clippy::float_cmp)]
fn test_initial_window_width_config() {
    let config = Config::try_from(
        r#"
[windows.dynamic]
title = ".*"
width = "complement_focused"
"#,
    )
    .expect("dynamic width rule parses");
    let width = config.find_window_properties("Window 1", "")[0]
        .width
        .expect("matched width rule");
    assert_eq!(width.ratio(Some(0.25)), 0.75);
    assert_eq!(width.ratio(Some(0.5)), 0.5);
    assert_eq!(width.ratio(Some(0.95)), 1.0);
    assert_eq!(width.ratio(Some(1.0)), 1.0);
    assert_eq!(width.ratio(None), 1.0);

    let config = Config::try_from(
        r#"
[windows.fixed]
title = ".*"
width = 0.5
"#,
    )
    .expect("fixed width rule still parses");
    let width = config.find_window_properties("Window 1", "")[0]
        .width
        .expect("matched width rule");
    assert_eq!(width.ratio(Some(0.25)), 0.5);
}

/// `WindowParams` defines rules and properties for specific windows based on their title or bundle ID.
/// These parameters can override default window management behavior, such as forcing a window to float or setting its initial index.
#[derive(Clone, Debug, Deserialize)]
pub struct WindowParams {
    /// A regular expression to match against the window's title.
    #[serde(deserialize_with = "deserialize_title")]
    title: Regex,
    /// An optional bundle identifier to match against the application's bundle ID.
    bundle_id: Option<String>,
    /// If `true`, the window will be managed as a floating window (not tiled).
    pub floating: Option<bool>,
    /// If `true`, force the process/window to be managed even if macOS reports it as
    /// unobservable or the window does not look like a standard window.
    pub manage: Option<bool>,
    /// An optional preferred index for the window's position in the window strip.
    pub index: Option<usize>,
    pub vertical_padding: Option<i32>,
    pub horizontal_padding: Option<i32>,
    pub dont_focus: Option<bool>,
    /// A positive initial width ratio relative to the display width, or
    /// `"complement_focused"` to fill the width left by the focused window.
    /// Fixed ratios above 1.0 create an oversized, horizontally scrollable window.
    /// Overrides the default column width when the window is first managed.
    pub width: Option<InitialWindowWidth>,
    /// Grid placement for floating windows: "cols:rows:x:y:w:h".
    /// Divides the display into a grid and positions the window at the given cell/span.
    pub grid: Option<String>,
    /// Per-window override for the active window border corner radius.
    pub border_radius: Option<f64>,
    /// Keyboard shortcuts that should be passed through to this app instead of
    /// being intercepted by paneru. Uses the same `"modifier+modifier-key"`
    /// format as `[bindings]` (e.g. `"ctrl+alt-h"`).
    #[serde(default)]
    bindings_passthrough: Vec<String>,
    /// Resolved `(keycode, modifiers)` pairs from `bindings_passthrough`.
    #[serde(skip)]
    parsed_passthrough: Vec<(u8, Modifiers)>,
}

impl WindowParams {
    #![allow(unused)]
    pub fn new(title: &str, bundle_id: Option<String>) -> Self {
        Self {
            title: Regex::new(title).unwrap(),
            bundle_id,
            floating: None,
            manage: None,
            index: None,
            vertical_padding: None,
            horizontal_padding: None,
            dont_focus: None,
            width: None,
            grid: None,
            border_radius: None,
            bindings_passthrough: Vec::new(),
            parsed_passthrough: Vec::new(),
        }
    }

    /// Returns the resolved passthrough keybindings for this window rule.
    pub fn passthrough_keys(&self) -> &[(u8, Modifiers)] {
        &self.parsed_passthrough
    }

    /// Parses the grid string into `(x_ratio, y_ratio, w_ratio, h_ratio)`, all 0.0–1.0.
    pub fn grid_ratios(&self) -> Option<(f64, f64, f64, f64)> {
        let grid = self.grid.as_ref()?;
        let parts: Vec<f64> = grid.split(':').filter_map(|s| s.parse().ok()).collect();
        if parts.len() != 6 {
            return None;
        }
        let (cols, rows) = (parts[0], parts[1]);
        if cols <= 0.0 || rows <= 0.0 {
            return None;
        }
        Some((
            parts[2] / cols,
            parts[3] / rows,
            parts[4] / cols,
            parts[5] / rows,
        ))
    }
}

/// Deserializes a regular expression from a string for window titles.
fn deserialize_title<'de, D>(deserializer: D) -> std::result::Result<Regex, D::Error>
where
    D: Deserializer<'de>,
{
    let s = String::deserialize(deserializer)?;
    Regex::new(&s).map_err(de::Error::custom)
}

fn deserialize_modifier<'de, D>(deserializer: D) -> std::result::Result<Option<Modifiers>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let Some(s) = Option::<String>::deserialize(deserializer)? else {
        return Ok(None);
    };
    parse_modifiers(&s)
        .map(Some)
        .map_err(|e: Error| serde::de::Error::custom(e.to_string()))
}

#[cfg(test)]
#[allow(clippy::ref_option, clippy::trivially_copy_pass_by_ref)]
pub(crate) fn serialize_modifier<S: serde::Serializer>(
    val: &Option<Modifiers>,
    serializer: S,
) -> std::result::Result<S::Ok, S::Error> {
    serializer.serialize_some(&val.as_ref().map(Modifiers::bits))
}

#[cfg(feature = "lua")]
pub(crate) fn format_modifiers(modifiers: Modifiers) -> String {
    let mut rem = modifiers;
    let mut parts = Vec::new();
    for (mask, name) in [
        (Modifiers::ALT, "alt"),
        (Modifiers::LALT, "lalt"),
        (Modifiers::RALT, "ralt"),
        (Modifiers::SHIFT, "shift"),
        (Modifiers::LSHIFT, "lshift"),
        (Modifiers::RSHIFT, "rshift"),
        (Modifiers::CMD, "cmd"),
        (Modifiers::LCMD, "lcmd"),
        (Modifiers::RCMD, "rcmd"),
        (Modifiers::CTRL, "ctrl"),
        (Modifiers::LCTRL, "lctrl"),
        (Modifiers::RCTRL, "rctrl"),
        (Modifiers::FN, "fn"),
    ] {
        if rem.contains(mask) {
            parts.push(name);
            rem.remove(mask);
        }
    }
    parts.join(" + ")
}

/// Builds a [`Config`] from the Lua table passed to `paneru.setup{...}`,
/// reusing the same serde `Deserialize` that parses the TOML file. Keybindings
/// are not read here — they go through the Lua keybind pipeline via
/// `paneru.bind` — so any `bindings` field is cleared.
///
/// # Errors
///
/// Returns an error if `value` is not a table or fails to deserialize.
#[cfg(feature = "lua")]
pub(crate) fn config_from_lua(lua: &mlua::Lua, value: mlua::Value) -> mlua::Result<Config> {
    use mlua::LuaSerdeExt;

    if !value.is_table() {
        return Err(mlua::Error::RuntimeError(
            "paneru.setup: expected a table".to_string(),
        ));
    }

    let mut inner: InnerConfig = lua.from_value(value)?;
    inner.bindings.clear();

    // Resolve window passthrough chords into keycodes, mirroring the TOML
    // second pass. `parsed_passthrough` is `#[serde(skip)]`, so it starts empty.
    let needs_keys = inner.windows.as_ref().is_some_and(|windows| {
        windows
            .values()
            .any(|params| !params.bindings_passthrough.is_empty())
    });
    if needs_keys {
        // The primed keymap, not a fresh one: this runs on the Lua worker, and
        // generating it goes through Carbon/TIS. See [`prime_virtual_keymap`].
        let virtual_keys = virtual_keymap();
        if let Some(windows) = &mut inner.windows {
            for params in windows.values_mut() {
                for chord in &params.bindings_passthrough {
                    match resolve_keybinding_str(chord, virtual_keys) {
                        Ok(pair) => params.parsed_passthrough.push(pair),
                        Err(err) => error!("paneru.setup passthrough: {err}"),
                    }
                }
            }
        }
    }

    Ok(Config {
        inner: Arc::new(ArcSwap::from_pointee(inner)),
    })
}

/// Resolves a keybinding chord string like `"ctrl+alt-h"` into a `(keycode, Modifiers)`
/// pair, generating the layout-aware virtual keymap on demand.
///
/// This is the entry point used by the Lua runtime's `paneru.bind`, so scripted
/// keybinds accept the exact same chord syntax as the TOML `[bindings]` table.
#[cfg(feature = "lua")]
pub(crate) fn resolve_chord(input: &str) -> Result<(u8, Modifiers)> {
    // Fast path: avoids the virtual keymap for common chords, keeping this
    // testable headlessly.
    if let Ok(resolved) = resolve_keybinding_str(input, &[]) {
        return Ok(resolved);
    }
    resolve_keybinding_str(input, virtual_keymap())
}

/// The layout-aware virtual keymap, computed once.
///
/// `generate_virtual_keymap` goes through Carbon/TIS, which is main-thread/
/// GUI-session sensitive, but `paneru.bind` runs on the Lua worker thread. So
/// the daemon primes this from the main thread at startup; the worker only
/// ever reads what was left behind.
#[cfg(feature = "lua")]
static VIRTUAL_KEYMAP: std::sync::OnceLock<Vec<(String, u8)>> = std::sync::OnceLock::new();

/// Computes the virtual keymap now, on the calling thread. Call once from the
/// main thread before anything can reach [`resolve_chord`].
#[cfg(feature = "lua")]
pub(crate) fn prime_virtual_keymap() {
    let _ = VIRTUAL_KEYMAP.set(generate_virtual_keymap());
}

/// The primed keymap. Falls back to computing it in place if priming never
/// happened (harmless in unit tests, rare elsewhere).
#[cfg(feature = "lua")]
fn virtual_keymap() -> &'static [(String, u8)] {
    VIRTUAL_KEYMAP.get_or_init(generate_virtual_keymap)
}

/// Resolves a keybinding string like `"ctrl+alt-h"` into a `(keycode, Modifiers)` pair.
fn resolve_keybinding_str(input: &str, virtual_keys: &[(String, u8)]) -> Result<(u8, Modifiers)> {
    let mut parts: Vec<&str> = input.split('-').map(str::trim).collect();
    let key = parts
        .pop()
        .ok_or_else(|| Error::InvalidConfig("Empty keybinding string".to_string()))?;

    let modifiers = match parts.pop() {
        Some(mods) => parse_modifiers(mods)?,
        None => Modifiers::empty(),
    };

    if !parts.is_empty() {
        return Err(Error::InvalidConfig(format!(
            "Too many dashes in keybinding: {input:?}"
        )));
    }

    let code = keycode_for_key_name(key, virtual_keys).ok_or_else(|| {
        Error::InvalidConfig(format!("Unknown key '{key}' in keybinding: {input:?}"))
    })?;

    Ok((code, modifiers))
}

fn keycode_for_key_name(key: &str, virtual_keys: &[(String, u8)]) -> Option<u8> {
    virtual_keys
        .iter()
        .find(|(k, _)| k == key)
        .map(|(_, c)| *c)
        .or_else(|| virtual_keycode().find(|(k, _)| *k == key).map(|(_, c)| *c))
        .or_else(|| literal_keycode().find(|(k, _)| *k == key).map(|(_, c)| *c))
}

/// Parses a string containing modifier names (e.g., "alt", "shift", "cmd", "ctrl") separated by "+", and returns their combined bitmask.
///
/// # Arguments
///
/// * `input` - The string containing modifier names (e.g., "ctrl+alt").
///
/// # Returns
///
/// `Ok(Modifiers)` with the combined modifier bitmask if parsing is successful, otherwise `Err(String)` with an error message for an invalid modifier.
fn parse_modifiers(input: &str) -> Result<Modifiers> {
    let mut out = Modifiers::empty();

    let modifiers = input.split('+').map(str::trim).collect::<Vec<_>>();
    for modifier in &modifiers {
        out |= match *modifier {
            "alt" => Modifiers::ALT,
            "lalt" => Modifiers::LALT,
            "ralt" => Modifiers::RALT,
            "shift" => Modifiers::SHIFT,
            "lshift" => Modifiers::LSHIFT,
            "rshift" => Modifiers::RSHIFT,
            "cmd" => Modifiers::CMD,
            "lcmd" => Modifiers::LCMD,
            "rcmd" => Modifiers::RCMD,
            "ctrl" => Modifiers::CTRL,
            "lctrl" => Modifiers::LCTRL,
            "rctrl" => Modifiers::RCTRL,
            "fn" => Modifiers::FN,
            _ => {
                return Err(Error::InvalidConfig(format!(
                    "{}: Invalid modifier: {modifier}",
                    function_name!()
                )));
            }
        }
    }
    Ok(out)
}

#[link(name = "Carbon", kind = "framework")]
unsafe extern "C" {
    /// Returns a reference to the currently selected keyboard layout input source that is ASCII-capable.
    ///
    /// # Returns
    ///
    /// A raw pointer to the `TISInputSourceRef` (a `c_void` pointer) if successful, otherwise `null_mut()`.
    fn TISCopyCurrentASCIICapableKeyboardLayoutInputSource() -> *mut c_void;

    /// Retrieves a specified property of an input source.
    ///
    /// # Arguments
    ///
    /// * `keyboard` - The raw pointer to the `TISInputSourceRef`.
    /// * `property` - The `CFStringRef` representing the property to retrieve (e.g., `kTISPropertyUnicodeKeyLayoutData`).
    ///
    /// # Returns
    ///
    /// A raw pointer to `CFData` containing the property value.
    fn TISGetInputSourceProperty(keyboard: *const c_void, property: CFStringRef) -> *mut CFData;

    /// Translates a virtual key code to a Unicode string according to the specified keyboard layout.
    ///
    /// # Arguments
    ///
    /// * `keyLayoutPtr` - A pointer to the keyboard layout data.
    /// * `virtualKeyCode` - The virtual key code to translate.
    /// * `keyAction` - The key action (e.g., `UCKeyAction::Down`).
    /// * `modifierKeyState` - The state of the modifier keys (e.g., `kUCKeyModifierAlphaLockBit`).
    /// * `keyboardType` - The type of keyboard, typically obtained from `LMGetKbdType()`.
    /// * `keyTranslateOptions` - Options for the translation process.
    /// * `deadKeyState` - A mutable reference to a `u32` representing the dead key state.
    /// * `maxStringLength` - The maximum length of the output Unicode string buffer.
    /// * `actualStringLength` - A mutable reference to an `isize` to store the actual length of the output Unicode string.
    /// * `unicodeString` - A mutable pointer to the buffer to store the resulting Unicode string.
    ///
    /// # Returns
    ///
    /// An `OSStatus` indicating success or failure.
    fn UCKeyTranslate(
        keyLayoutPtr: *mut u8,
        virtualKeyCode: u16,
        keyAction: u16,
        modifierKeyState: u32,
        keyboardType: u32,
        keyTranslateOptions: u32,
        deadKeyState: &mut u32,
        maxStringLength: usize,
        actualStringLength: &mut isize,
        unicodeString: *mut u16,
    ) -> OSStatus;

    /// Returns the keyboard type for the system.
    ///
    /// # Returns
    ///
    /// A `u8` representing the keyboard type.
    fn LMGetKbdType() -> u8;

    /// A constant `CFStringRef` representing the property key for Unicode keyboard layout data.
    static kTISPropertyUnicodeKeyLayoutData: CFStringRef;

}

/// Returns an iterator over static tuples of virtual key names and their corresponding keycodes.
/// These keycodes identify physical keys on an ANSI-standard US keyboard layout.
///
/// # Returns
///
/// An iterator yielding references to `(&'static str, u8)` tuples.
fn virtual_keycode() -> impl Iterator<Item = &'static (&'static str, u8)> {
    /*
     *  Summary:
     *    Virtual keycodes
     *
     *  Discussion:
     *    These constants are the virtual keycodes defined originally in
     *    Inside Mac Volume V, pg. V-191. They identify physical keys on a
     *    keyboard. Those constants with "ANSI" in the name are labeled
     *    according to the key position on an ANSI-standard US keyboard.
     *    For example, kVK_ANSI_A indicates the virtual keycode for the key
     *    with the letter 'A' in the US keyboard layout. Other keyboard
     *    layouts may have the 'A' key label on a different physical key;
     *    in this case, pressing 'A' will generate a different virtual
     *    keycode.
     */
    static VIRTUAL_KEYCODE: LazyLock<Vec<(&'static str, u8)>> = LazyLock::new(|| {
        vec![
            ("a", 0x00),
            ("s", 0x01),
            ("d", 0x02),
            ("f", 0x03),
            ("h", 0x04),
            ("g", 0x05),
            ("z", 0x06),
            ("x", 0x07),
            ("c", 0x08),
            ("v", 0x09),
            ("section", 0x0a), // iso keyboards only.
            ("b", 0x0b),
            ("q", 0x0c),
            ("w", 0x0d),
            ("e", 0x0e),
            ("r", 0x0f),
            ("y", 0x10),
            ("t", 0x11),
            ("1", 0x12),
            ("2", 0x13),
            ("3", 0x14),
            ("4", 0x15),
            ("6", 0x16),
            ("5", 0x17),
            ("equal", 0x18),
            ("9", 0x19),
            ("7", 0x1a),
            ("minus", 0x1b),
            ("8", 0x1c),
            ("0", 0x1d),
            ("rightbracket", 0x1e),
            ("o", 0x1f),
            ("u", 0x20),
            ("leftbracket", 0x21),
            ("i", 0x22),
            ("p", 0x23),
            ("l", 0x25),
            ("j", 0x26),
            ("quote", 0x27),
            ("k", 0x28),
            ("semicolon", 0x29),
            ("backslash", 0x2a),
            ("comma", 0x2b),
            ("slash", 0x2c),
            ("n", 0x2d),
            ("m", 0x2e),
            ("period", 0x2f),
            ("grave", 0x32),
            ("keypaddecimal", 0x41),
            ("keypadmultiply", 0x43),
            ("keypadplus", 0x45),
            ("keypadclear", 0x47),
            ("keypaddivide", 0x4b),
            ("keypadenter", 0x4c),
            ("keypadminus", 0x4e),
            ("keypadequals", 0x51),
            ("keypad0", 0x52),
            ("keypad1", 0x53),
            ("keypad2", 0x54),
            ("keypad3", 0x55),
            ("keypad4", 0x56),
            ("keypad5", 0x57),
            ("keypad6", 0x58),
            ("keypad7", 0x59),
            ("keypad8", 0x5b),
            ("keypad9", 0x5c),
        ]
    });
    VIRTUAL_KEYCODE.iter()
}

/// Returns an iterator over static tuples of literal key names and their corresponding keycodes.
/// These keycodes are for keys that are independent of the keyboard layout (e.g., Return, Tab, Space).
///
/// # Returns
///
/// An iterator yielding references to `(&'static str, u8)` tuples.
fn literal_keycode() -> impl Iterator<Item = &'static (&'static str, u8)> {
    /* keycodes for keys that are independent of keyboard layout*/
    static LITERAL_KEYCODE: LazyLock<Vec<(&'static str, u8)>> = LazyLock::new(|| {
        vec![
            ("return", 0x24),
            ("tab", 0x30),
            ("space", 0x31),
            ("delete", 0x33),
            ("escape", 0x35),
            ("command", 0x37),
            ("shift", 0x38),
            ("capslock", 0x39),
            ("option", 0x3a),
            ("control", 0x3b),
            ("rightcommand", 0x36),
            ("rightshift", 0x3c),
            ("rightoption", 0x3d),
            ("rightcontrol", 0x3e),
            ("function", 0x3f),
            ("f17", 0x40),
            ("volumeup", 0x48),
            ("volumedown", 0x49),
            ("mute", 0x4a),
            ("f18", 0x4f),
            ("f19", 0x50),
            ("f20", 0x5a),
            ("f5", 0x60),
            ("f6", 0x61),
            ("f7", 0x62),
            ("f3", 0x63),
            ("f8", 0x64),
            ("f9", 0x65),
            ("f11", 0x67),
            ("f13", 0x69),
            ("f16", 0x6a),
            ("f14", 0x6b),
            ("f10", 0x6d),
            ("contextualmenu", 0x6e),
            ("f12", 0x6f),
            ("f15", 0x71),
            ("help", 0x72),
            ("home", 0x73),
            ("pageup", 0x74),
            ("forwarddelete", 0x75),
            ("f4", 0x76),
            ("end", 0x77),
            ("f2", 0x78),
            ("pagedown", 0x79),
            ("f1", 0x7a),
            ("leftarrow", 0x7b),
            ("rightarrow", 0x7c),
            ("downarrow", 0x7d),
            ("uparrow", 0x7e),
        ]
    });
    LITERAL_KEYCODE.iter()
}

/// Represents the action of a key, used in `UCKeyTranslate`.
enum UCKeyAction {
    /// The key is going down.
    Down = 0, // key is going down
              /*
              Up = 1,      // key is going up
              AutoKey = 2, // auto-key down
              Display = 3, // get information for key display (as in Key Caps)
              */
}

/// Generates a vector of (`key_name`, keycode) tuples for virtual keys based on the current ASCII-capable keyboard layout.
/// This involves using macOS Carbon API functions to translate virtual keycodes to Unicode characters.
///
/// # Returns
///
/// A `Vec<(String, u8)>` containing the translated key names and their keycodes. Returns an empty vector if an error occurs during keyboard layout fetching.
fn generate_virtual_keymap() -> Vec<(String, u8)> {
    let keyboard = AXUIWrapper::from_retained(unsafe {
        TISCopyCurrentASCIICapableKeyboardLayoutInputSource()
    })
    .ok();
    let keyboard_layout = keyboard
        .and_then(|keyboard| {
            NonNull::new(unsafe {
                TISGetInputSourceProperty(
                    keyboard.as_ptr::<c_void>(),
                    kTISPropertyUnicodeKeyLayoutData,
                )
            })
        })
        .and_then(|uchr| NonNull::new(unsafe { CFData::byte_ptr(uchr.as_ref()).cast_mut() }));
    let Some(keyboard_layout) = keyboard_layout else {
        error!(
            "{}: problem fetching current virtual keyboard layout.",
            function_name!()
        );
        return vec![];
    };

    let mut state = 0u32;
    let mut chars = vec![0u16; 256];
    let mut got: isize = 0;
    virtual_keycode()
        .filter_map(|(_, keycode)| {
            unsafe {
                UCKeyTranslate(
                    keyboard_layout.as_ptr(),
                    (*keycode).into(),
                    UCKeyAction::Down as u16,
                    0,
                    LMGetKbdType().into(),
                    1,
                    &mut state,
                    chars.len(),
                    &mut got,
                    chars.as_mut_ptr(),
                )
            }
            .to_result(function_name!())
            .ok()
            .map(|()| {
                let name = unsafe { CFString::with_characters(None, chars.as_ptr(), got) }
                    .map(|chars| chars.to_string());
                name.zip(Some(*keycode))
            })
        })
        .flatten()
        .collect()
}

#[cfg(test)]
fn test_virtual_keymap() -> Vec<(String, u8)> {
    virtual_keycode()
        .map(|(key, code)| ((*key).to_string(), *code))
        .collect()
}

#[test]
#[allow(clippy::float_cmp)]
#[allow(clippy::too_many_lines)]
fn test_config_parsing() {
    let input = r#"
[options]
focus_follows_mouse = true

[bindings]
quit = "ctrl+alt-q"
window_manage = "ctrl+alt-t"
window_stack = ["ctrl-s", "alt-s"]
window_shrink = "alt-d"
window_snap = "fn-x"

[windows]

[windows.pip]
title = "picture.*picture"
bundle_id = "com.something.apple"
floating = true
index = 1
"#;
    let virtual_keys = test_virtual_keymap();
    let config = Config {
        inner: Arc::new(ArcSwap::from_pointee(
            InnerConfig::parse_config_with_virtual_keys(input, &virtual_keys)
                .expect("Failed to parse config"),
        )),
    };
    let find_key = |k| {
        virtual_keycode()
            .find_map(|(s, v)| (format!("{k}") == *s).then_some(*v))
            .unwrap()
    };

    assert_eq!(config.inner().options.focus_follows_mouse, Some(true));

    // Modifiers: alt = 1<<0, ctrl = 1<<3.
    let keycode = find_key('q');
    assert!(matches!(
        config.find_keybind(keycode, Modifiers::ALT | Modifiers::CTRL),
        Some(Command::Quit)
    ));

    assert!(matches!(
        config.find_keybind(keycode, Modifiers::LALT | Modifiers::LCTRL),
        Some(Command::Quit)
    ));

    assert!(matches!(
        config.find_keybind(keycode, Modifiers::RALT | Modifiers::RCTRL),
        Some(Command::Quit)
    ));

    let keycode = find_key('t');
    assert!(matches!(
        config.find_keybind(keycode, Modifiers::ALT | Modifiers::CTRL),
        Some(Command::Window(Operation::Manage))
    ));

    assert!(matches!(
        config.find_keybind(keycode, Modifiers::LALT | Modifiers::LCTRL),
        Some(Command::Window(Operation::Manage))
    ));

    assert!(matches!(
        config.find_keybind(keycode, Modifiers::RALT | Modifiers::RCTRL),
        Some(Command::Window(Operation::Manage))
    ));

    let keycode = find_key('s');
    assert!(matches!(
        config.find_keybind(keycode, Modifiers::CTRL),
        Some(Command::Window(Operation::Stack(true)))
    ));

    assert!(matches!(
        config.find_keybind(keycode, Modifiers::LCTRL),
        Some(Command::Window(Operation::Stack(true)))
    ));

    assert!(matches!(
        config.find_keybind(keycode, Modifiers::RCTRL),
        Some(Command::Window(Operation::Stack(true)))
    ));

    assert!(matches!(
        config.find_keybind(keycode, Modifiers::ALT),
        Some(Command::Window(Operation::Stack(true)))
    ));

    assert!(matches!(
        config.find_keybind(keycode, Modifiers::LALT),
        Some(Command::Window(Operation::Stack(true)))
    ));

    assert!(matches!(
        config.find_keybind(keycode, Modifiers::RALT),
        Some(Command::Window(Operation::Stack(true)))
    ));

    let keycode = find_key('d');
    assert!(matches!(
        config.find_keybind(keycode, Modifiers::ALT),
        Some(Command::Window(Operation::Resize(ResizeDirection::Shrink)))
    ));

    assert!(matches!(
        config.find_keybind(keycode, Modifiers::LALT),
        Some(Command::Window(Operation::Resize(ResizeDirection::Shrink)))
    ));

    assert!(matches!(
        config.find_keybind(keycode, Modifiers::RALT),
        Some(Command::Window(Operation::Resize(ResizeDirection::Shrink)))
    ));

    let props = config.find_window_properties("picture in picture", "com.something.apple");
    assert_eq!(props[0].floating, Some(true));
    assert_eq!(props[0].index, Some(1));

    let keycode = find_key('x');
    assert!(matches!(
        config.find_keybind(keycode, Modifiers::FN),
        Some(Command::Window(Operation::Snap))
    ));

    let defaults = Config::default();
    assert_eq!(defaults.swipe_sensitivity(), 0.35);
    assert_eq!(defaults.swipe_deceleration(), 4.0);
}

#[test]
fn test_config_parsing_absolute_virtual_workspace_bindings() {
    let input = r#"
[options]

[bindings]
window_virtualnum_3 = "cmd + alt - 3"
window_virtualsendnum_3 = "cmd + alt + shift - 3"
"#;
    let virtual_keys = test_virtual_keymap();
    let config = Config {
        inner: Arc::new(ArcSwap::from_pointee(
            InnerConfig::parse_config_with_virtual_keys(input, &virtual_keys)
                .expect("Failed to parse config"),
        )),
    };
    let find_key = |k| {
        virtual_keycode()
            .find_map(|(s, v)| (format!("{k}") == *s).then_some(*v))
            .unwrap()
    };
    let keycode = find_key('3');
    assert!(matches!(
        config.find_keybind(keycode, Modifiers::CMD | Modifiers::ALT),
        Some(Command::Window(Operation::VirtualNumber(2)))
    ));
    assert!(matches!(
        config.find_keybind(keycode, Modifiers::CMD | Modifiers::ALT | Modifiers::SHIFT),
        Some(Command::Window(Operation::VirtualMoveNumber(
            2,
            MoveFocus::Stay
        )))
    ));
}

#[test]
fn test_parse_resize_commands() {
    assert!(matches!(
        parse_command(&["window", "resize"]).unwrap(),
        Command::Window(Operation::Resize(ResizeDirection::Grow))
    ));
    assert!(matches!(
        parse_command(&["window", "grow"]).unwrap(),
        Command::Window(Operation::Resize(ResizeDirection::Grow))
    ));
    assert!(matches!(
        parse_command(&["window", "resize", "shrink"]).unwrap(),
        Command::Window(Operation::Resize(ResizeDirection::Shrink))
    ));
    assert!(matches!(
        parse_command(&["window", "shrink"]).unwrap(),
        Command::Window(Operation::Resize(ResizeDirection::Shrink))
    ));
}

#[test]
fn test_parse_vertical_resize_commands() {
    assert!(matches!(
        parse_command(&["window", "vertical"]).unwrap(),
        Command::Window(Operation::ResizeVertical(ResizeDirection::Grow))
    ));
    assert!(matches!(
        parse_command(&["window", "vertical", "resize"]).unwrap(),
        Command::Window(Operation::ResizeVertical(ResizeDirection::Grow))
    ));
    assert!(matches!(
        parse_command(&["window", "vertical", "grow"]).unwrap(),
        Command::Window(Operation::ResizeVertical(ResizeDirection::Grow))
    ));
    assert!(matches!(
        parse_command(&["window", "vertical", "shrink"]).unwrap(),
        Command::Window(Operation::ResizeVertical(ResizeDirection::Shrink))
    ));
    assert!(matches!(
        parse_command(&["window", "vertical", "resize", "shrink"]).unwrap(),
        Command::Window(Operation::ResizeVertical(ResizeDirection::Shrink))
    ));
    assert!(parse_command(&["window", "vertical", "wider"]).is_err());
}

#[test]
fn test_parse_restart_command() {
    assert!(matches!(
        parse_command(&["restart"]).unwrap(),
        Command::Restart
    ));
}

#[test]
fn test_parse_absolute_virtual_workspace_commands() {
    assert!(matches!(
        parse_command(&["window", "virtualnum", "3"]).unwrap(),
        Command::Window(Operation::VirtualNumber(2))
    ));
    assert!(parse_command(&["workspace", "virtual", "3"]).is_err());
    assert!(matches!(
        parse_command(&["window", "virtualmove", "3"]).unwrap(),
        Command::Window(Operation::VirtualMoveNumber(2, MoveFocus::Follow))
    ));
    assert!(matches!(
        parse_command(&["window", "virtualsend", "3"]).unwrap(),
        Command::Window(Operation::VirtualMoveNumber(2, MoveFocus::Stay))
    ));
    assert!(matches!(
        parse_command(&["window", "virtualmovenum", "3"]).unwrap(),
        Command::Window(Operation::VirtualMoveNumber(2, MoveFocus::Follow))
    ));
    assert!(matches!(
        parse_command(&["window", "virtualsendnum", "3"]).unwrap(),
        Command::Window(Operation::VirtualMoveNumber(2, MoveFocus::Stay))
    ));
    assert!(matches!(
        parse_command(&["window", "virtualadd"]).unwrap(),
        Command::Window(Operation::VirtualAdd)
    ));
}

#[test]
fn test_default_workspaces() {
    let base = "[options]\n[bindings]\n";
    let config = Config::try_from(base).unwrap();
    assert_eq!(config.default_workspaces(), 1);

    let config = Config::try_from(&*format!("default_workspaces = 4\n{base}")).unwrap();
    assert_eq!(config.default_workspaces(), 4);

    // Zero is clamped up to 1 (the physical space always exists).
    let config = Config::try_from(&*format!("default_workspaces = 0\n{base}")).unwrap();
    assert_eq!(config.default_workspaces(), 1);
}

#[test]
#[allow(clippy::float_cmp)]
fn test_grid_ratios() {
    use regex::Regex;

    let make = |grid: Option<&str>| WindowParams {
        title: Regex::new(".*").unwrap(),
        bundle_id: None,
        floating: None,
        manage: None,
        index: None,
        vertical_padding: None,
        horizontal_padding: None,
        dont_focus: None,
        width: None,
        grid: grid.map(Into::into),
        border_radius: None,
        bindings_passthrough: vec![],
        parsed_passthrough: vec![],
    };

    // Standard 2x2 grid, cell (1,1), span 1x1 → bottom-right quarter.
    assert_eq!(
        make(Some("2:2:1:1:1:1")).grid_ratios(),
        Some((0.5, 0.5, 0.5, 0.5))
    );

    // 3x3 grid, cell (0,0), span 2x1 → top-left, 2/3 width, 1/3 height.
    assert_eq!(
        make(Some("3:3:0:0:2:1")).grid_ratios(),
        Some((0.0, 0.0, 2.0 / 3.0, 1.0 / 3.0))
    );

    // Full screen: 1x1 grid, cell (0,0), span 1x1.
    assert_eq!(
        make(Some("1:1:0:0:1:1")).grid_ratios(),
        Some((0.0, 0.0, 1.0, 1.0))
    );

    // Invalid: too few parts.
    assert_eq!(make(Some("2:2:1:1")).grid_ratios(), None);

    // Invalid: zero columns.
    assert_eq!(make(Some("0:2:0:0:1:1")).grid_ratios(), None);

    // No grid set.
    assert_eq!(make(None).grid_ratios(), None);
}

#[test]
fn test_parse_hex_color_valid() {
    assert_eq!(
        parse_hex_color("#89b4fa"),
        (
            f64::from(0x89) / 255.0,
            f64::from(0xb4) / 255.0,
            f64::from(0xfa) / 255.0
        )
    );
    assert_eq!(parse_hex_color("#000000"), (0.0, 0.0, 0.0));
    assert_eq!(parse_hex_color("#FFFFFF"), (1.0, 1.0, 1.0));
    assert_eq!(parse_hex_color("#FF0000"), (1.0, 0.0, 0.0));
}

#[test]
fn test_parse_hex_color_no_hash() {
    assert_eq!(
        parse_hex_color("89b4fa"),
        (
            f64::from(0x89) / 255.0,
            f64::from(0xb4) / 255.0,
            f64::from(0xfa) / 255.0
        )
    );
    assert_eq!(parse_hex_color("FF0000"), (1.0, 0.0, 0.0));
}

#[test]
fn test_parse_hex_color_invalid_length() {
    // Short strings fall back to white.
    assert_eq!(parse_hex_color("#FFF"), (1.0, 1.0, 1.0));
    assert_eq!(parse_hex_color(""), (1.0, 1.0, 1.0));
    assert_eq!(parse_hex_color("#FF"), (1.0, 1.0, 1.0));
}

#[test]
fn test_parse_hex_color_malformed_hex() {
    // Non-hex digits fall back to 255 per channel.
    assert_eq!(parse_hex_color("ZZZZZZ"), (1.0, 1.0, 1.0));
    assert_eq!(parse_hex_color("GG0000"), (1.0, 0.0, 0.0));
}

#[test]
#[allow(clippy::float_cmp)]
fn test_config_defaults() {
    let config = Config::default();
    assert_eq!(config.dim_inactive_opacity(), 0.0);
    assert_eq!(config.dim_inactive_color(), (0.0, 0.0, 0.0));
    assert!(!config.border_active_window());
    assert_eq!(config.border_color(), (1.0, 1.0, 1.0));
    assert_eq!(config.border_opacity(), 1.0);
    assert_eq!(config.border_width(), 2.0);
    assert_eq!(config.border_radius(), BorderRadiusOption::Auto);
    assert_eq!(config.menubar_height(), None);
}

#[test]
fn test_first_launch_creates_parseable_config_without_overwriting_it() {
    let unique = format!(
        "paneru-first-launch-{}-{}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    );
    let directory = std::env::temp_dir().join(unique);
    let path = directory.join("paneru.toml");

    assert!(create_configuration_file_at(&path).unwrap());
    Config::new(&path).expect("generated configuration should parse");

    let custom = "[options]\nauto_center = false\n\n[bindings]\n";
    std::fs::write(&path, custom).unwrap();
    assert!(!create_configuration_file_at(&path).unwrap());
    assert_eq!(std::fs::read_to_string(&path).unwrap(), custom);

    std::fs::remove_dir_all(directory).unwrap();
}

#[test]
fn defaults_config_matches_the_generated_stub() {
    let stub = InnerConfig::new(DEFAULT_CONFIGURATION).expect("the stub should parse");
    let defaults = Config::defaults().expect("defaults should always build");
    assert_eq!(
        format!("{stub:?}"),
        format!("{:?}", defaults.inner.load()),
        "a missing TOML should behave exactly like the generated stub"
    );
}

#[test]
fn test_window_rules_manage() {
    let input = r#"
[options]

[bindings]

[windows.btt_main]
bundle_id = "com.hegenberg.BetterTouchTool"
title = "BetterTouchTool"
manage = true

[windows.btt_floating]
bundle_id = "com.hegenberg.BetterTouchTool"
title = "Screenshot.*"
floating = true
"#;
    let config = Config::try_from(input).expect("config should parse");

    // Main window should match the manage rule.
    let props = config.find_window_properties("BetterTouchTool", "com.hegenberg.BetterTouchTool");
    assert_eq!(props.len(), 1);
    assert_eq!(props[0].manage, Some(true));

    // Screenshot window matches the floating rule.
    let props = config.find_window_properties("Screenshot 1", "com.hegenberg.BetterTouchTool");
    assert_eq!(props.len(), 1);
    assert_eq!(props[0].floating, Some(true));
}

#[test]
fn test_restore_config_defaults() {
    let config = Config::try_from("[options]\n\n[bindings]\n").expect("config should parse");

    assert!(config.restore_enabled());
    assert_eq!(config.restore_startup_grace(), Duration::from_secs(2));
    assert_eq!(
        config.restore_missing_windows(),
        MissingWindowBehavior::Ignore
    );
}

#[test]
fn test_restore_config_explicit_values() {
    let config = Config::try_from(
        r#"
[options]

[restore]
enabled = false
startup_grace_ms = 750
missing_windows = "ignore"

[bindings]
"#,
    )
    .expect("config should parse");

    assert!(!config.restore_enabled());
    assert_eq!(config.restore_startup_grace(), Duration::from_millis(750));
    assert_eq!(
        config.restore_missing_windows(),
        MissingWindowBehavior::Ignore
    );
}

#[test]
fn test_restore_config_rejects_unsupported_missing_window_policy() {
    let err = Config::try_from(
        r#"
[options]

[restore]
missing_windows = "reserve"

[bindings]
"#,
    )
    .expect_err("unsupported restore missing-window policy should fail");

    assert!(err.to_string().contains("unknown variant"));
}

#[test]
fn test_static_virtual_key_names_can_be_bound() {
    let config = Config::try_from(
        r#"
[options]

[bindings]
window_grow = "alt - minus"
"#,
    )
    .unwrap();
    let minus_keycode = virtual_keycode()
        .find_map(|(key, code)| (*key == "minus").then_some(*code))
        .unwrap();

    assert!(matches!(
        config.find_keybind(minus_keycode, Modifiers::ALT),
        Some(Command::Window(Operation::Resize(ResizeDirection::Grow)))
    ));
}

#[cfg(all(test, feature = "lua"))]
mod lua_setup_tests {
    use super::*;
    use mlua::Lua;

    /// Runs a `paneru.setup`-style table (as a Lua chunk that returns it) through
    /// the same `config_from_lua` path `paneru.setup` uses.
    fn config_from_source(source: &str) -> Config {
        let lua = Lua::new();
        let value: mlua::Value = lua.load(source).eval().expect("lua chunk should evaluate");
        config_from_lua(&lua, value).expect("config_from_lua should succeed")
    }

    #[test]
    fn setup_table_populates_accessors() {
        let config = config_from_source(
            r"return {
                default_workspaces = 3,
                options = {
                    sliver_width = 9,
                    focus_follows_mouse = false,
                    preset_stack_heights = { 0.3, 0.7 },
                },
                padding = { top = 10, bottom = 4 },
            }",
        );
        assert_eq!(config.default_workspaces(), 3);
        assert_eq!(config.sliver_width(), 9);
        assert!(!config.focus_follows_mouse());
        assert_eq!(config.preset_stack_heights(), vec![0.3, 0.7]);
        let (top, _right, bottom, _left) = config.edge_padding();
        assert_eq!((top, bottom), (10, 4));
    }

    #[test]
    fn missing_options_and_bindings_are_ok() {
        // Regression guard for the `#[serde(default)]` fix: a table that omits
        // `options` and `bindings` must still deserialize.
        let config = config_from_source(r"return { padding = { top = 4 } }");
        assert_eq!(config.default_workspaces(), 1);
        assert_eq!(config.edge_padding().0, 4);
    }

    #[test]
    fn window_rule_passthrough_is_resolved() {
        let config = config_from_source(
            r#"return {
                windows = { term = { title = "kitty", bindings_passthrough = { "ctrl+alt-h" } } },
            }"#,
        );
        let rules = config.find_window_properties("kitty", "");
        assert_eq!(rules.len(), 1);
        assert!(
            !rules[0].passthrough_keys().is_empty(),
            "passthrough chords should resolve to keycodes"
        );
    }

    #[test]
    fn non_table_argument_is_rejected() {
        let lua = Lua::new();
        assert!(config_from_lua(&lua, mlua::Value::Integer(3)).is_err());
    }
}