libloadorder 18.8.1

A cross-platform library for manipulating the load order and active status of plugins for the Elder Scrolls and Fallout games.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
/*
Notes on OpenMW support:

OpenMW defines its load order and its external plugins directories in its config
files. Unfortunately, where those config files are loaded from is a mix of
platform-specific, configured at compile time, and configured within other
config files. The last config file to be loaded is the one that gets treated as
writeable user config. See here for reference:

<https://gitlab.com/OpenMW/openmw/-/blob/openmw-49-rc4/components/files/configurationmanager.cpp>
<https://gitlab.com/OpenMW/openmw/-/blob/openmw-49-rc4/components/files/linuxpath.cpp>
<https://gitlab.com/OpenMW/openmw/-/blob/openmw-49-rc4/components/files/windowspath.cpp>

This is further complicated when OpenMW is installed as a Flatpak app, because
the config may define paths that are only valid within the app's Flatpak runtime
environment (e.g. starting with /app). It's also possible to define config at
runtime using CLI parameters.

libloadorder attempts to support this system, minus the CLI parameters. The game
path given when creating a GameSettings object must be the path containing the
OpenMW executable.

If a local path is provided, it is used to replace the last config file that is
loaded with the config in the local path. If there is no config in the local
path, the config from last loaded config file is effectively removed. If
provided, any `config` entries in the local path's config file will be ignored.

On Linux, OpenMW's global config and global data paths are specified at compile
time, and I'm not aware of any way to retrieve them. As such, libloadorder
guesses their paths based on the game path, so that the correct paths should be
guessed for all of the release distributions listed at
<https://openmw.org/downloads/>.
*/
#[cfg(not(windows))]
use std::ffi::OsString;
use std::{
    collections::HashSet,
    fs::create_dir_all,
    path::{Path, PathBuf},
};

use crate::Error;

pub(crate) fn user_config_dir(game_path: &Path) -> Result<PathBuf, Error> {
    let fixed_paths = FixedPaths::new(game_path)?;
    let config_state = load_game_configs(&fixed_paths)?;

    Ok(config_state.user_config_dir)
}

pub(crate) fn resources_vfs_path(game_path: &Path, local_path: &Path) -> Result<PathBuf, Error> {
    let config = load_game_config_with_user_config_dir(game_path, local_path)?;

    // Default value is relative to OpenMW's current working directory, assume
    // that's the OpenMW executable's directory, i.e. the game path.
    // <https://gitlab.com/OpenMW/openmw/-/blob/openmw-49-rc4/components/config/gamesettings.cpp?ref_type=tags#L61>
    Ok(config
        .resources
        .unwrap_or_else(|| game_path.join("resources"))
        .join("vfs"))
}

pub(crate) fn additional_data_paths(
    game_path: &Path,
    local_path: &Path,
) -> Result<Vec<PathBuf>, Error> {
    load_game_config_with_user_config_dir(game_path, local_path)
        .map(OpenMWConfig::into_additional_data_paths)
}

pub(crate) fn non_user_additional_data_paths(game_path: &Path) -> Result<Vec<PathBuf>, Error> {
    load_non_user_config(game_path).map(OpenMWConfig::into_additional_data_paths)
}

pub(crate) fn read_active_plugin_names(user_config_path: &Path) -> Result<Vec<String>, Error> {
    let Some(ini) = read_openmw_cfg(user_config_path)? else {
        return Ok(Vec::new());
    };

    let active_plugin_names: Vec<_> = ini
        .general_section()
        .get_all("content")
        .map(ToOwned::to_owned)
        .collect();

    Ok(active_plugin_names)
}

pub(crate) fn non_user_active_plugin_names(game_path: &Path) -> Result<Vec<String>, Error> {
    load_non_user_config(game_path).map(|c| c.content)
}

#[cfg(windows)]
fn default_user_config_dir() -> Result<PathBuf, Error> {
    // <https://gitlab.com/OpenMW/openmw/-/blob/openmw-49-rc4/components/files/windowspath.cpp?ref_type=tags#L35>
    dirs::document_dir()
        .map(|d| d.join("My Games\\OpenMW"))
        .ok_or_else(|| Error::NoDocumentsPath)
}

#[cfg(not(windows))]
fn default_user_config_dir(game_path: &Path) -> Result<PathBuf, Error> {
    // <https://gitlab.com/OpenMW/openmw/-/blob/openmw-49-rc4/components/files/linuxpath.cpp?ref_type=tags#L64>
    if is_flatpak_install(game_path) {
        // When run as a Flatpak, OpenMW sees a different XDG_CONFIG_HOME
        // value.
        dirs::home_dir().map(|d| d.join(".var/app/org.openmw.OpenMW/config/openmw"))
    } else {
        // Checking $HOST_XDG_CONFIG_HOME first in case libloadorder is running
        // as part of a Flatpak app.
        std::env::var_os("HOST_XDG_CONFIG_HOME")
            .and_then(is_absolute_path)
            .or_else(dirs::config_dir)
            .map(|p| p.join("openmw"))
    }
    .ok_or_else(|| Error::NoUserConfigPath)
}

#[cfg(not(windows))]
fn default_user_data_dir(is_flatpak_install: bool) -> Result<PathBuf, Error> {
    // <https://gitlab.com/OpenMW/openmw/-/blob/openmw-49-rc4/components/files/linuxpath.cpp?ref_type=tags#L69>
    if is_flatpak_install {
        dirs::home_dir().map(|d| d.join(".var/app/org.openmw.OpenMW/data/openmw"))
    } else {
        // Checking $HOST_XDG_DATA_HOME first in case libloadorder is
        // running as part of a Flatpak app.
        std::env::var_os("HOST_XDG_DATA_HOME")
            .and_then(is_absolute_path)
            .or_else(dirs::data_local_dir)
            .map(|p| p.join("openmw"))
    }
    .ok_or_else(|| Error::NoUserDataPath)
}

#[expect(
    unsafe_code,
    reason = "There is currently no way to get this data safely"
)]
#[cfg(windows)]
fn default_global_config_dir() -> Result<PathBuf, Error> {
    // This is similar to OpenMW's approach here:
    // <https://gitlab.com/OpenMW/openmw/-/blob/openmw-49-rc4/components/files/windowspath.cpp?ref_type=tags#L55>
    // Though it errors instead of falling back to the current working directory
    // if the Program Files path cannot be obtained.
    use std::{ffi::OsString, os::windows::ffi::OsStringExt};
    use windows_sys::core::PWSTR;
    use windows_sys::Win32::UI::Shell;

    let mut pwstr: PWSTR = std::ptr::null_mut();
    // SAFETY: There's nothing unsafe about calling SHGetKnownFolderPath()
    // with these arguments.
    let result = unsafe {
        Shell::SHGetKnownFolderPath(
            &Shell::FOLDERID_ProgramFiles,
            0,
            std::ptr::null_mut(),
            &raw mut pwstr,
        )
    };

    windows_result::HRESULT(result).ok()?;

    // SAFETY: This is safe because the pointer is definitely not null when wcslen is called.
    let pwstr_length = unsafe {
        unsafe extern "C" {
            fn wcslen(s: *const u16) -> usize;
        }

        if pwstr.is_null() {
            return Err(Error::NoProgramFilesPath);
        }

        wcslen(pwstr)
    };

    // SAFETY: pwstr and pwstr_length satisfy the safety conditions of from_raw_parts().
    let wide_slice = unsafe { core::slice::from_raw_parts(pwstr, pwstr_length) };

    let program_files_path = PathBuf::from(OsString::from_wide(wide_slice));

    // SAFETY: This is safe because CoTaskMemFree() is being used with a
    // pointer to memory that was allocated by SHGetKnownFolderPath().
    unsafe {
        // Now free the pwstr as documented here:
        // <https://learn.microsoft.com/en-us/windows/win32/api/shlobj_core/nf-shlobj_core-shgetknownfolderpath>
        windows_sys::Win32::System::Com::CoTaskMemFree(pwstr.cast());
    }

    Ok(program_files_path.join("OpenMW"))
}

#[cfg(not(windows))]
fn default_global_config_dir(game_path: &Path) -> PathBuf {
    // This path is hardcoded at compile time:
    // <https://gitlab.com/OpenMW/openmw/-/blob/openmw-49-rc4/components/files/linuxpath.cpp?ref_type=tags#L81>
    // So just make an educated guess based on the game path.
    if game_path.join("resources/vfs").exists() {
        // Probably a single directory install from the release archive.
        game_path.to_path_buf()
    } else if is_flatpak_install(game_path) {
        // Probably installed from Flathub.
        game_path.join("../etc/openmw")
    } else {
        // Probably installed from the OS package manager.
        let host_etc_path = Path::new("/run/host/etc/openmw");
        if host_etc_path.exists() {
            // libloadorder is probably running as part of a Flatpak app.
            host_etc_path.into()
        } else {
            "/etc/openmw".into()
        }
    }
}

#[cfg(not(windows))]
fn default_global_data_dir(game_path: &Path) -> PathBuf {
    // This path is hardcoded at compile time:
    // <https://gitlab.com/OpenMW/openmw/-/blob/openmw-49-rc4/components/files/linuxpath.cpp?ref_type=tags#L108>
    // So just make an educated guess based on the game path.
    if game_path.join("resources/vfs").exists() {
        // Probably a single directory install from the release archive.
        game_path.to_path_buf()
    } else if is_flatpak_install(game_path) {
        // Probably installed from Flathub.
        game_path.join("../share/games/openmw")
    } else {
        let host_share_games_path = Path::new("/run/host/usr/share/games/openmw");
        let host_share_path = Path::new("/run/host/usr/share/openmw");
        let share_games_path = Path::new("/usr/share/games/openmw");
        if host_share_games_path.exists() {
            // libloadorder is probably running as part of a Flatpak app, and
            // OpenMW was probably installed using Ubuntu's, Debian's or Arch's
            // package manager.
            host_share_games_path.into()
        } else if host_share_path.exists() {
            // libloadorder is probably running as part of a Flatpak app, and
            // OpenMW was probably installed using OpenSUSE's package manager.
            host_share_path.into()
        } else if share_games_path.exists() {
            // Probably installed using Ubuntu's, Debian's or Arch's package
            // manager.
            share_games_path.into()
        } else {
            // Probably installed using OpenSUSE's package manager.
            "/usr/share/openmw".into()
        }
    }
}

#[cfg(not(windows))]
fn is_absolute_path(value: OsString) -> Option<PathBuf> {
    let path = PathBuf::from(value);
    path.is_absolute().then_some(path)
}

#[cfg(not(windows))]
fn is_flatpak_install(game_path: &Path) -> bool {
    // The presence of a metadata file seems to be the most reliable indicator
    // of a Flatpak install.
    // <https://docs.flatpak.org/en/latest/flatpak-command-reference.html#flatpak-metadata>
    // The game path is expected to be files/share/games/openmw, relative to the
    // Flatpak app's top-level deploy directory (where the metadata file is).
    let metadata_file_path = game_path.join("../../metadata");

    ini::Ini::load_from_file(metadata_file_path)
        .map(|ini| {
            if let Some(name) = ini.get_from(Some("Application"), "name") {
                name == "org.openmw.OpenMW"
            } else {
                false
            }
        })
        .unwrap_or(false)
}

#[derive(Clone, Debug, Default, Eq, PartialEq, Ord, PartialOrd, Hash)]
struct FixedPaths {
    local: PathBuf,
    user_config: PathBuf,
    user_data: PathBuf,
    global_config: PathBuf,
    global_data: PathBuf,
    flatpak_app: Option<PathBuf>,
}

impl FixedPaths {
    #[cfg(windows)]
    fn new(game_path: &Path) -> Result<FixedPaths, Error> {
        let user_config = default_user_config_dir()?;
        let global_config = default_global_config_dir()?;

        // The user data path is the same as the user config path on Windows:
        // <https://gitlab.com/OpenMW/openmw/-/blob/openmw-49-rc4/components/files/windowspath.cpp?ref_type=tags#L49>
        let user_data = user_config.clone();

        // The global data path is the same as the global config path on Windows:
        // // <https://gitlab.com/OpenMW/openmw/-/blob/openmw-49-rc4/components/files/windowspath.cpp?ref_type=tags#L84>
        let global_data = global_config.clone();

        Ok(FixedPaths {
            local: game_path.to_path_buf(),
            user_config,
            user_data,
            global_config,
            global_data,
            flatpak_app: None,
        })
    }

    #[cfg(not(windows))]
    fn new(game_path: &Path) -> Result<FixedPaths, Error> {
        let is_flatpak_install = is_flatpak_install(game_path);

        let user_config = default_user_config_dir(game_path)?;
        let user_data = default_user_data_dir(is_flatpak_install)?;
        let global_config = default_global_config_dir(game_path);
        let global_data = default_global_data_dir(game_path);

        Ok(FixedPaths {
            local: game_path.to_path_buf(),
            user_config,
            user_data,
            global_config,
            global_data,
            flatpak_app: is_flatpak_install.then(|| game_path.join("..")),
        })
    }
}

#[derive(Clone, Debug, Default, Eq, PartialEq, Ord, PartialOrd, Hash)]
struct OpenMWConfig {
    replace: Vec<String>,
    config: Vec<PathBuf>,
    resources: Option<PathBuf>,
    data_local: Option<PathBuf>,
    data: Vec<PathBuf>,
    content: Vec<String>,
}

impl OpenMWConfig {
    fn reduce(configs: Vec<Self>) -> Self {
        configs
            .into_iter()
            .reduce(|acc, e| e.reduce_into(acc))
            .unwrap_or_default()
    }

    fn reduce_into(mut self, mut accumulator: Self) -> Self {
        OpenMWConfig {
            resources: accumulator.resources.or(self.resources),
            data_local: accumulator.data_local.or(self.data_local),
            config: if self.replace.iter().any(|r| r == "config") {
                self.config
            } else {
                accumulator.config.append(&mut self.config);
                accumulator.config
            },
            data: if self.replace.iter().any(|r| r == "data") {
                self.data
            } else {
                accumulator.data.append(&mut self.data);
                accumulator.data
            },
            content: if self.replace.iter().any(|r| r == "content") {
                self.content
            } else {
                accumulator.content.append(&mut self.content);
                accumulator.content
            },
            replace: if self.replace.iter().any(|r| r == "replace") {
                self.replace
            } else {
                accumulator.replace.append(&mut self.replace);
                accumulator.replace
            },
        }
    }

    // This includes the value of data-local and the data values, but not the value of
    // <resources>/vfs. The value of user-data is of no interest to libloadorder.
    fn into_additional_data_paths(self) -> Vec<PathBuf> {
        let mut paths = Vec::new();

        if let Some(path) = self.data_local {
            paths.push(path);
        }

        paths.extend(self.data);

        paths
    }
}

fn parse_path_value(value: &str) -> String {
    // Values may be enclosed in double quotes and use & as an escape, see:
    // <https://gitlab.com/OpenMW/openmw/-/blob/openmw-0.49.0/components/config/gamesettings.cpp?ref_type=tags#L168>
    let Some(value) = value.strip_prefix('"') else {
        return value.to_owned();
    };

    // Although the cfg file is encoded in UTF-8, OpenMW iterates over UTF-16
    // code points. This iterates over Unicode scalar values: the only
    // difference is the absence of surrogate code points in the latter, which
    // is not a problem because they're only a representational artifact of
    // UTF-16, so the result will be the same in both cases.
    let mut result = String::with_capacity(value.len());
    let mut chars = value.chars();

    while let Some(c) = chars.next() {
        if c == '"' {
            break;
        }

        if c == '&' {
            if let Some(c) = chars.next() {
                result.push(c);
            }
        } else {
            result.push(c);
        }
    }

    result
}

fn resolve_path_value(
    parsed_path: String,
    config_dir_path: &Path,
    fixed_paths: &FixedPaths,
) -> Option<PathBuf> {
    if let Some(remainder) = parsed_path.strip_prefix('?') {
        if let Some((token, suffix)) = remainder.split_once('?') {
            let token_path = match token {
                "local" => &fixed_paths.local,
                "userconfig" => &fixed_paths.user_config,
                "userdata" => &fixed_paths.user_data,
                "global" => &fixed_paths.global_data,
                _ => return None,
            };
            if suffix.is_empty() {
                Some(token_path.clone())
            } else {
                Some(token_path.join(suffix))
            }
        } else {
            Some(parsed_path.into())
        }
    } else if Path::new(&parsed_path).is_relative() {
        Some(config_dir_path.join(parsed_path))
    } else if let Some(app_path) = &fixed_paths.flatpak_app {
        // Paths within the Flatpak app may be relative to the app's runtime
        // mount point, so replace that with the path of the Flatpak app's
        // files at rest on the host.
        if let Some(suffix) = parsed_path.strip_prefix("/app/") {
            Some(app_path.join(suffix))
        } else {
            Some(parsed_path.into())
        }
    } else {
        Some(parsed_path.into())
    }
}

fn load_config(
    config_dir_path: &Path,
    fixed_paths: &FixedPaths,
) -> Result<Option<OpenMWConfig>, Error> {
    let Some(ini) = read_openmw_cfg(&config_dir_path.join("openmw.cfg"))? else {
        return Ok(None);
    };

    let path_mapper = |s| resolve_path_value(parse_path_value(s), config_dir_path, fixed_paths);

    let data: Vec<_> = ini
        .general_section()
        .get_all("data")
        .filter_map(path_mapper)
        .collect();

    let resources = ini.general_section().get("resources").and_then(path_mapper);

    let data_local = ini
        .general_section()
        .get("data-local")
        .and_then(path_mapper);

    let config: Vec<_> = ini
        .general_section()
        .get_all("config")
        .filter_map(path_mapper)
        .collect();

    let replace: Vec<_> = ini
        .general_section()
        .get_all("replace")
        .map(ToOwned::to_owned)
        .collect();

    let content: Vec<_> = ini
        .general_section()
        .get_all("content")
        .map(ToOwned::to_owned)
        .collect();

    Ok(Some(OpenMWConfig {
        replace,
        config,
        resources,
        data_local,
        data,
        content,
    }))
}

#[derive(Clone, Debug, Default, Eq, PartialEq, Ord, PartialOrd, Hash)]
struct OpenMWConfigState {
    loaded_configs: Vec<OpenMWConfig>,
    user_config_dir: PathBuf,
}

fn load_game_configs(fixed_paths: &FixedPaths) -> Result<OpenMWConfigState, Error> {
    // This is based on
    // <https://gitlab.com/OpenMW/openmw/-/blob/openmw-49-rc4/components/files/configurationmanager.cpp#L65>
    // but skips handling of config provided as CLI parameters.

    let mut active_config_paths = Vec::new();

    let mut config = load_config(&fixed_paths.local, fixed_paths)?;
    if config.is_some() {
        active_config_paths.push(fixed_paths.local.clone());
    } else {
        active_config_paths.push(fixed_paths.global_config.clone());
        config = load_config(&fixed_paths.global_config, fixed_paths)?;
    }

    let Some(config) = config else {
        return Ok(OpenMWConfigState {
            loaded_configs: Vec::new(),
            user_config_dir: fixed_paths.global_config.clone(),
        });
    };

    let mut already_parsed_paths = HashSet::new();
    for path in &active_config_paths {
        already_parsed_paths.insert(path.clone());
    }

    let mut extra_config_dirs = config.config.clone();

    let mut parsed_configs = vec![config];

    while let Some(path) = extra_config_dirs.pop() {
        if already_parsed_paths.contains(&path) {
            continue;
        }

        already_parsed_paths.insert(path.clone());

        if let Some(config) = load_config(&path, fixed_paths)? {
            if config.replace.iter().any(|r| r == "config") && parsed_configs.len() > 1 {
                active_config_paths.truncate(1);
                parsed_configs.truncate(1);
            }

            extra_config_dirs.extend_from_slice(&config.config);
            parsed_configs.push(config);
        } else {
            // Record an empty config so that if this is the last (i.e. user)
            // config, we can pop it off to get the non-user configs.
            parsed_configs.push(OpenMWConfig::default());
        }

        active_config_paths.push(path);
    }

    Ok(OpenMWConfigState {
        loaded_configs: parsed_configs,
        user_config_dir: active_config_paths
            .last()
            .ok_or(Error::NoUserConfigPath)?
            .clone(),
    })
}

fn load_game_config_with_user_config_dir(
    game_path: &Path,
    user_config_dir: &Path,
) -> Result<OpenMWConfig, Error> {
    let fixed_paths = FixedPaths::new(game_path)?;
    let mut config_state = load_game_configs(&fixed_paths)?;

    if config_state.user_config_dir != user_config_dir {
        // Replace the last config with one from the given dir.
        let new_config = load_config(user_config_dir, &fixed_paths)?.unwrap_or_default();

        config_state.loaded_configs.pop();
        config_state.loaded_configs.push(new_config);
    }

    Ok(OpenMWConfig::reduce(config_state.loaded_configs))
}

fn load_non_user_config(game_path: &Path) -> Result<OpenMWConfig, Error> {
    let fixed_paths = FixedPaths::new(game_path)?;
    let mut config_state = load_game_configs(&fixed_paths)?;

    // We don't want the user config, so omit the last config when merging.
    config_state.loaded_configs.pop();

    Ok(OpenMWConfig::reduce(config_state.loaded_configs))
}

fn read_openmw_cfg(openmw_cfg_path: &Path) -> Result<Option<ini::Ini>, Error> {
    if !openmw_cfg_path.exists() {
        return Ok(None);
    }

    // openmw.cfg is encoded in UTF-8, see:
    // <https://gitlab.com/OpenMW/openmw/-/blob/openmw-0.49.0/components/config/gamesettings.cpp#L293>
    ini::Ini::load_from_file_opt(
        openmw_cfg_path,
        ini::ParseOption {
            enabled_quote: false,
            enabled_escape: false,
            ..ini::ParseOption::default()
        },
    )
    .map(Some)
    .map_err(|e| match e {
        ini::Error::Io(e) => Error::IoError(openmw_cfg_path.to_path_buf(), e),
        ini::Error::Parse(e) => Error::IniParsingError {
            path: openmw_cfg_path.to_path_buf(),
            line: e.line,
            column: e.col,
            message: e.msg.to_string(),
        },
    })
}

fn escape_openmw_data_value(value: &Path) -> Result<String, Error> {
    let str_value = value
        .to_str()
        .ok_or_else(|| Error::InvalidPath(value.to_path_buf()))?;

    let mut result = String::with_capacity(str_value.len() + 2);

    result.push('"');
    for char in str_value.chars() {
        if char == '&' || char == '"' {
            result.push('&');
        }

        result.push(char);
    }
    result.push('"');

    Ok(result)
}

pub(crate) fn write_openmw_cfg(
    openmw_cfg_path: &Path,
    data_paths: &[PathBuf],
    active_plugin_names: &[&str],
) -> Result<(), Error> {
    let mut ini = match read_openmw_cfg(openmw_cfg_path)? {
        Some(ini) => ini,
        None => ini::Ini::new(),
    };

    // Remove existing data paths.
    let _ = ini.general_section_mut().remove_all("data").count();

    // Add data paths.
    for data_path in data_paths {
        ini.general_section_mut()
            .append("data", escape_openmw_data_value(data_path)?);
    }

    // Remove existing load order.
    let _ = ini.general_section_mut().remove_all("content").count();

    // Add plugins in load order.
    for plugin_name in active_plugin_names {
        ini.general_section_mut().append("content", *plugin_name);
    }

    if let Some(parent_path) = openmw_cfg_path.parent().filter(|p| !p.exists()) {
        create_dir_all(parent_path).map_err(|e| Error::IoError(parent_path.to_path_buf(), e))?;
    }

    // OpenMW's launcher doesn't escape backslashes.
    ini.write_to_file_policy(openmw_cfg_path, ini::EscapePolicy::Nothing)
        .map_err(|e| Error::IoError(openmw_cfg_path.to_path_buf(), e))
}

#[cfg(test)]
mod tests {
    use tempfile::tempdir;

    use super::*;

    fn fixed_paths() -> FixedPaths {
        FixedPaths {
            local: "a".into(),
            user_config: "b".into(),
            user_data: "c".into(),
            global_config: "d".into(),
            global_data: "e".into(),
            flatpak_app: Some("f".into()),
        }
    }

    #[test]
    fn resources_vfs_path_should_be_relative_to_game_path_if_not_defined_in_config() {
        let tmp_dir = tempdir().unwrap();
        let game_path = tmp_dir.path().join("game");

        let path = resources_vfs_path(&game_path, &tmp_dir.path().join("local")).unwrap();

        assert_eq!(game_path.join("resources/vfs"), path);
    }

    #[test]
    fn read_active_plugin_names_should_return_content_values_in_order() {
        let tmp_dir = tempdir().unwrap();
        let ini_path = tmp_dir.path().join("openmw.cfg");

        std::fs::write(&ini_path, "content=a\ncontent=b\ncontent=c").unwrap();

        let data_paths = read_active_plugin_names(&ini_path).unwrap();

        let expected_names: &[String] = &["a".to_owned(), "b".to_owned(), "c".to_owned()];
        assert_eq!(expected_names, data_paths);
    }

    #[test]
    fn read_active_plugin_names_should_not_error_if_the_given_path_does_not_exist() {
        let data_paths = read_active_plugin_names(Path::new("missing")).unwrap();

        assert!(data_paths.is_empty());
    }

    #[test]
    #[cfg(windows)]
    fn default_user_config_dir_on_windows_should_be_in_my_games() {
        let path = default_user_config_dir().unwrap();

        assert_eq!(dirs::document_dir().unwrap().join("My Games\\OpenMW"), path);
    }

    #[test]
    #[cfg(not(windows))]
    fn default_user_config_dir_on_linux_flatpak_should_use_user_flatpak_config_dir() {
        let tmp_dir = tempdir().unwrap();
        let game_path = tmp_dir.path().join("files/bin");

        create_dir_all(&game_path).unwrap();
        std::fs::write(
            tmp_dir.path().join("metadata"),
            "[Application]\nname=org.openmw.OpenMW",
        )
        .unwrap();

        let path = default_user_config_dir(&game_path).unwrap();

        assert_eq!(
            dirs::home_dir()
                .unwrap()
                .join(".var/app/org.openmw.OpenMW/config/openmw"),
            path
        );
    }

    #[test]
    #[cfg(not(windows))]
    fn default_user_config_dir_on_linux_non_flatpak_should_use_user_config() {
        // Changing env vars on Linux within a running process is a can of worms, so don't try
        // setting HOST_XDG_CONFIG_HOME.
        let tmp_dir = tempdir().unwrap();
        let game_path = tmp_dir.path();

        let path = default_user_config_dir(game_path).unwrap();

        assert_eq!(dirs::config_dir().unwrap().join("openmw"), path);
    }

    #[test]
    #[cfg(not(windows))]
    fn default_user_data_dir_on_linux_flatpak_should_use_user_flatpak_data_dir() {
        let path = default_user_data_dir(true).unwrap();

        assert_eq!(
            dirs::home_dir()
                .unwrap()
                .join(".var/app/org.openmw.OpenMW/data/openmw"),
            path
        );
    }

    #[test]
    #[cfg(not(windows))]
    fn default_user_data_dir_on_linux_non_flatpak_should_user_local_data() {
        // Changing env vars on Linux within a running process is a can of worms, so don't try
        // setting HOST_XDG_DATA_HOME.
        let path = default_user_data_dir(false).unwrap();

        assert_eq!(dirs::data_local_dir().unwrap().join("openmw"), path);
    }

    #[test]
    #[cfg(windows)]
    fn default_global_config_dir_on_windows_should_be_in_program_files() {
        let path = default_global_config_dir().unwrap();

        assert!(path.ends_with("Program Files\\OpenMW"));
    }

    #[test]
    #[cfg(not(windows))]
    fn default_global_config_dir_on_linux_should_use_game_path_if_it_contains_resources_vfs() {
        let tmp_dir = tempdir().unwrap();
        let game_path = tmp_dir.path();
        create_dir_all(game_path.join("resources/vfs")).unwrap();

        let path = default_global_config_dir(game_path);

        assert_eq!(game_path, path);
    }

    #[test]
    #[cfg(not(windows))]
    fn default_global_config_dir_on_linux_flatpak_should_use_etc_folder_in_flatpak_files_dir() {
        let tmp_dir = tempdir().unwrap();
        let game_path = tmp_dir.path().join("files/bin");

        create_dir_all(&game_path).unwrap();
        std::fs::write(
            tmp_dir.path().join("metadata"),
            "[Application]\nname=org.openmw.OpenMW",
        )
        .unwrap();

        let path = default_global_config_dir(&game_path);

        assert_eq!(game_path.join("../etc/openmw"), path);
    }

    #[test]
    #[cfg(not(windows))]
    fn default_global_config_dir_on_linux_should_use_root_etc_folder_if_not_flatpak() {
        let tmp_dir = tempdir().unwrap();
        let game_path = tmp_dir.path();

        let path = default_global_config_dir(game_path);

        assert_eq!(Path::new("/etc/openmw"), path);
    }

    #[test]
    #[cfg(not(windows))]
    fn default_global_data_dir_on_linux_should_use_game_path_if_it_contains_resources_vfs() {
        let tmp_dir = tempdir().unwrap();
        let game_path = tmp_dir.path();
        create_dir_all(game_path.join("resources/vfs")).unwrap();

        let path = default_global_data_dir(game_path);

        assert_eq!(game_path, path);
    }

    #[test]
    #[cfg(not(windows))]
    fn default_global_data_dir_on_linux_flatpak_should_use_share_folder_in_flatpak_files_dir() {
        let tmp_dir = tempdir().unwrap();
        let game_path = tmp_dir.path().join("files/bin");

        create_dir_all(&game_path).unwrap();
        std::fs::write(
            tmp_dir.path().join("metadata"),
            "[Application]\nname=org.openmw.OpenMW",
        )
        .unwrap();

        let path = default_global_data_dir(&game_path);

        assert_eq!(game_path.join("../share/games/openmw"), path);
    }

    #[test]
    #[cfg(not(windows))]
    fn default_global_data_dir_on_linux_should_use_root_usr_share_games_folder_if_it_exists() {
        // Can't create the directory without root permissions, so just check if it exists and
        // adjust what's asserted accordingly.
        let tmp_dir = tempdir().unwrap();
        let game_path = tmp_dir.path();

        let path = default_global_data_dir(game_path);

        if std::fs::exists("/usr/share/games/openmw").unwrap() {
            assert_eq!(Path::new("/usr/share/games/openmw"), path);
        } else {
            assert_eq!(Path::new("/usr/share/openmw"), path);
        }
    }

    #[test]
    #[cfg(not(windows))]
    fn is_flatpak_install_should_be_true_if_a_flatpak_metadata_file_with_the_right_name_field_exists(
    ) {
        let tmp_dir = tempdir().unwrap();
        let game_path = tmp_dir.path().join("files/bin");

        create_dir_all(&game_path).unwrap();
        std::fs::write(
            tmp_dir.path().join("metadata"),
            "[Application]\nname=org.openmw.OpenMW",
        )
        .unwrap();

        assert!(is_flatpak_install(&game_path));
    }

    #[test]
    #[cfg(not(windows))]
    fn is_flatpak_install_should_be_false_if_a_flatpak_metadata_file_with_the_wrong_name_field_exists(
    ) {
        let tmp_dir = tempdir().unwrap();
        let game_path = tmp_dir.path().join("files/bin");

        create_dir_all(&game_path).unwrap();
        std::fs::write(
            tmp_dir.path().join("metadata"),
            "[Application]\nname=com.example.Wrong",
        )
        .unwrap();

        assert!(!is_flatpak_install(&game_path));
    }

    #[test]
    #[cfg(not(windows))]
    fn is_flatpak_install_should_be_false_if_a_metadata_file_of_the_wrong_format_exists() {
        let tmp_dir = tempdir().unwrap();
        let game_path = tmp_dir.path().join("files/bin");

        create_dir_all(&game_path).unwrap();
        std::fs::write(tmp_dir.path().join("metadata"), "org.openmw.OpenMW").unwrap();

        assert!(!is_flatpak_install(&game_path));
    }

    #[test]
    #[cfg(not(windows))]
    fn is_flatpak_install_should_be_false_if_no_metadata_file_exists() {
        let tmp_dir = tempdir().unwrap();
        let game_path = tmp_dir.path().join("files/bin");

        assert!(!is_flatpak_install(&game_path));
    }

    #[test]
    #[cfg(windows)]
    fn fixed_paths_new_on_windows_should_share_config_and_data_paths() {
        let game_path = Path::new("game");
        let paths = FixedPaths::new(game_path).unwrap();

        let expected_user_path = dirs::document_dir().unwrap().join("My Games\\OpenMW");

        assert_eq!(game_path, paths.local);
        assert_eq!(expected_user_path, paths.user_config);
        assert_eq!(expected_user_path, paths.user_data);
        assert!(paths.global_config.ends_with("Program Files\\OpenMW"));
        assert_eq!(paths.global_config, paths.global_data);
        assert!(paths.flatpak_app.is_none());
    }

    #[test]
    #[cfg(not(windows))]
    fn fixed_paths_on_linux_should_set_flatpak_app_path_to_none_if_is_not_flatpak_install() {
        let tmp_dir = tempdir().unwrap();

        let paths = FixedPaths::new(tmp_dir.path()).unwrap();

        assert_eq!(tmp_dir.path(), paths.local);
        assert_eq!(
            dirs::config_dir().unwrap().join("openmw"),
            paths.user_config
        );
        assert_eq!(
            dirs::data_local_dir().unwrap().join("openmw"),
            paths.user_data
        );
        assert_eq!(Path::new("/etc/openmw"), paths.global_config);
        assert_eq!(Path::new("/usr/share/openmw"), paths.global_data);
        assert!(paths.flatpak_app.is_none());
    }

    #[test]
    #[cfg(not(windows))]
    fn fixed_paths_on_linux_should_set_flatpak_app_path_to_dir_above_the_game_path_if_is_flatpak_install(
    ) {
        let tmp_dir = tempdir().unwrap();
        let game_path = tmp_dir.path().join("files/bin");

        create_dir_all(&game_path).unwrap();
        std::fs::write(
            tmp_dir.path().join("metadata"),
            "[Application]\nname=org.openmw.OpenMW",
        )
        .unwrap();

        let paths = FixedPaths::new(&game_path).unwrap();

        assert_eq!(game_path, paths.local);
        assert_eq!(
            dirs::home_dir()
                .unwrap()
                .join(".var/app/org.openmw.OpenMW/config/openmw"),
            paths.user_config
        );
        assert_eq!(
            dirs::home_dir()
                .unwrap()
                .join(".var/app/org.openmw.OpenMW/data/openmw"),
            paths.user_data
        );
        assert_eq!(game_path.join("../etc/openmw"), paths.global_config);
        assert_eq!(game_path.join("../share/games/openmw"), paths.global_data);
        assert_eq!(game_path.join(".."), paths.flatpak_app.unwrap());
    }

    #[test]
    fn openmw_config_reduce_into_should_replace_the_first_resources_only_if_it_is_none() {
        let first = OpenMWConfig::default();
        let second = OpenMWConfig {
            resources: Some("a".into()),
            ..Default::default()
        };
        let merged = second.reduce_into(first);

        assert_eq!(Some("a".into()), merged.resources);

        let third = OpenMWConfig {
            resources: Some("b".into()),
            ..Default::default()
        };
        let merged = third.reduce_into(merged);

        assert_eq!(Some("a".into()), merged.resources);
    }

    #[test]
    fn openmw_config_reduce_into_should_replace_the_first_data_local_only_if_it_is_none() {
        let first = OpenMWConfig::default();
        let second = OpenMWConfig {
            data_local: Some("a".into()),
            ..Default::default()
        };
        let merged = second.reduce_into(first);

        assert_eq!(Some("a".into()), merged.data_local);

        let third = OpenMWConfig {
            data_local: Some("b".into()),
            ..Default::default()
        };
        let merged = third.reduce_into(merged);

        assert_eq!(Some("a".into()), merged.data_local);
    }

    #[test]
    fn openmw_config_reduce_into_should_append_replace_values_unless_second_replace_contains_replace(
    ) {
        let first = OpenMWConfig {
            replace: vec!["a".into()],
            ..Default::default()
        };
        let second = OpenMWConfig {
            replace: vec!["b".into()],
            ..Default::default()
        };
        let merged = second.reduce_into(first);

        assert_eq!(vec!["a".to_owned(), "b".into()], merged.replace);

        let third = OpenMWConfig {
            replace: vec!["c".into(), "replace".into()],
            ..Default::default()
        };
        let merged = third.reduce_into(merged);

        assert_eq!(vec!["c".to_owned(), "replace".into()], merged.replace);
    }

    #[test]
    fn openmw_config_reduce_into_should_append_config_values_unless_second_replace_contains_config()
    {
        let first = OpenMWConfig {
            config: vec!["a".into()],
            ..Default::default()
        };
        let second = OpenMWConfig {
            config: vec!["b".into()],
            ..Default::default()
        };
        let merged = second.reduce_into(first);

        assert_eq!(vec![PathBuf::from("a"), "b".into()], merged.config);

        let third = OpenMWConfig {
            replace: vec!["config".into()],
            config: vec!["c".into()],
            ..Default::default()
        };
        let merged = third.reduce_into(merged);

        assert_eq!(vec![PathBuf::from("c")], merged.config);
    }

    #[test]
    fn openmw_config_reduce_into_should_append_data_values_unless_second_replace_contains_data() {
        let first = OpenMWConfig {
            data: vec!["a".into()],
            ..Default::default()
        };
        let second = OpenMWConfig {
            data: vec!["b".into()],
            ..Default::default()
        };
        let merged = second.reduce_into(first);

        assert_eq!(vec![PathBuf::from("a"), "b".into()], merged.data);

        let third = OpenMWConfig {
            replace: vec!["data".into()],
            data: vec!["c".into()],
            ..Default::default()
        };
        let merged = third.reduce_into(merged);

        assert_eq!(vec![PathBuf::from("c")], merged.data);
    }

    #[test]
    fn openmw_config_reduce_into_should_append_content_values_unless_second_replace_contains_content(
    ) {
        let first = OpenMWConfig {
            content: vec!["a".into()],
            ..Default::default()
        };
        let second = OpenMWConfig {
            content: vec!["b".into()],
            ..Default::default()
        };
        let merged = second.reduce_into(first);

        assert_eq!(vec!["a".to_owned(), "b".into()], merged.content);

        let third = OpenMWConfig {
            replace: vec!["content".into()],
            content: vec!["c".into()],
            ..Default::default()
        };
        let merged = third.reduce_into(merged);

        assert_eq!(vec!["c".to_owned()], merged.content);
    }

    #[test]
    fn openmw_config_into_additional_data_paths_should_use_data_local_and_data_paths() {
        let config = OpenMWConfig {
            data_local: Some("a".into()),
            data: vec!["b".into(), "c".into()],
            ..Default::default()
        };

        assert_eq!(
            vec![PathBuf::from("a"), "b".into(), "c".into()],
            config.into_additional_data_paths()
        );
    }

    #[test]
    fn parse_path_value_should_strip_enclosing_double_quotes_and_ampersand_escapes() {
        let parsed = parse_path_value("\"Path\\&&&\"&a&&&&\\Data Files\"");

        assert_eq!("Path\\&\"a&&\\Data Files", parsed);
    }

    #[test]
    fn parse_path_value_should_return_an_unquoted_value_as_is() {
        let value = "&\"&\"";
        let parsed = parse_path_value(value);

        assert_eq!(value, parsed);
    }

    #[test]
    fn resolve_path_value_should_return_empty_path_if_value_is_empty() {
        let resolved = resolve_path_value(String::new(), Path::new(""), &fixed_paths());

        assert_eq!(Some(PathBuf::new()), resolved);
    }

    #[test]
    fn resolve_path_value_should_resolve_a_relative_path_to_the_config_directory() {
        let value = "relative/path";
        let config_dir = Path::new("config/directory");
        let resolved = resolve_path_value(value.to_owned(), config_dir, &fixed_paths());

        assert_eq!(Some(config_dir.join(value)), resolved);
    }

    #[test]
    #[cfg(not(windows))]
    fn resolve_path_value_should_replace_app_prefix_if_flatpak_app_path_is_defined() {
        let value = "/app/path/to/somewhere".to_owned();
        let resolved = resolve_path_value(value, Path::new(""), &fixed_paths());

        assert_eq!(
            Some(fixed_paths().flatpak_app.unwrap().join("path/to/somewhere")),
            resolved
        );
    }

    #[test]
    #[cfg(not(windows))]
    fn resolve_path_value_should_not_replace_app_prefix_if_flatpak_app_path_is_not_defined() {
        let value = "/app/path/to/somewhere";
        let mut fixed_paths = fixed_paths();
        fixed_paths.flatpak_app = None;
        let resolved = resolve_path_value(value.to_owned(), Path::new(""), &fixed_paths);

        assert_eq!(Some(value.into()), resolved);
    }

    #[test]
    #[cfg(windows)]
    fn resolve_path_value_should_return_absolute_path_unchanged() {
        let value = "C:\\absolute\\path";
        let config_dir = Path::new("config/directory");
        let resolved = resolve_path_value(value.to_owned(), config_dir, &fixed_paths());

        assert_eq!(Some(value.into()), resolved);
    }

    #[test]
    fn resolve_path_value_should_not_replace_token_that_appears_after_the_start_of_the_value() {
        let value = "prefix?userconfig?";
        let config_dir = Path::new("config/directory");
        let resolved = resolve_path_value(value.to_owned(), config_dir, &fixed_paths());

        assert_eq!(Some(config_dir.join(value)), resolved);
    }

    #[test]
    fn resolve_path_value_should_replace_local_token_prefix() {
        let value = "?local?suffix";
        let fixed_paths = fixed_paths();
        let resolved = resolve_path_value(value.to_owned(), Path::new(""), &fixed_paths);

        assert_eq!(Some(fixed_paths.local.join("suffix")), resolved);
    }

    #[test]
    fn resolve_path_value_should_replace_userconfig_token_prefix() {
        let value = "?userconfig?suffix";
        let fixed_paths = fixed_paths();
        let resolved = resolve_path_value(value.to_owned(), Path::new(""), &fixed_paths);

        assert_eq!(Some(fixed_paths.user_config.join("suffix")), resolved);
    }

    #[test]
    fn resolve_path_value_should_replace_userdata_token_prefix() {
        let value = "?userdata?suffix";
        let fixed_paths = fixed_paths();
        let resolved = resolve_path_value(value.to_owned(), Path::new(""), &fixed_paths);

        assert_eq!(Some(fixed_paths.user_data.join("suffix")), resolved);
    }

    #[test]
    fn resolve_path_value_should_replace_global_token_prefix() {
        let value = "?global?suffix";
        let fixed_paths = fixed_paths();
        let resolved = resolve_path_value(value.to_owned(), Path::new(""), &fixed_paths);

        assert_eq!(Some(fixed_paths.global_data.join("suffix")), resolved);
    }

    #[test]
    fn resolve_path_value_should_return_none_if_token_prefix_is_unrecognised() {
        let value = "?other?suffix";
        let fixed_paths = fixed_paths();
        let resolved = resolve_path_value(value.to_owned(), Path::new(""), &fixed_paths);

        assert!(resolved.is_none());
    }

    #[test]
    fn resolve_path_value_should_handle_token_with_no_suffix() {
        let value = "?local?";
        let fixed_paths = fixed_paths();
        let resolved = resolve_path_value(value.to_owned(), Path::new(""), &fixed_paths);

        assert_eq!(Some(fixed_paths.local), resolved);
    }

    #[test]
    fn resolve_path_value_should_return_a_value_starting_with_a_question_mark_but_not_containing_another_unchanged(
    ) {
        let value = "?local";
        let resolved = resolve_path_value(value.to_owned(), Path::new(""), &fixed_paths());

        assert_eq!(Some(value.into()), resolved);
    }

    #[test]
    fn load_config_should_parse_and_resolve_paths() {
        let tmp_dir = tempdir().unwrap();
        let ini_path = tmp_dir.path().join("openmw.cfg");

        std::fs::write(
            &ini_path,
            "data=\"Path\\&&&\"&a&&&&\\Data Files\"\ndata=?local?games/path",
        )
        .unwrap();

        let fixed_paths = fixed_paths();
        let config = load_config(tmp_dir.path(), &fixed_paths).unwrap().unwrap();

        let expected_paths: &[PathBuf] = &[
            tmp_dir.path().join("Path\\&\"a&&\\Data Files"),
            fixed_paths.local.join("games/path"),
        ];
        assert_eq!(expected_paths, config.data);
    }

    #[test]
    fn load_config_should_not_error_if_the_given_path_does_not_exist() {
        let config = load_config(Path::new("missing"), &fixed_paths()).unwrap();

        assert!(config.is_none());
    }

    #[test]
    fn load_game_configs_should_use_global_config_dir_as_user_config_dir_if_no_configs_are_found() {
        let fixed_paths = fixed_paths();
        let state = load_game_configs(&fixed_paths).unwrap();

        assert!(state.loaded_configs.is_empty());
        assert_eq!(fixed_paths.global_config, state.user_config_dir);
    }

    #[test]
    fn load_game_configs_should_use_local_config_if_present() {
        let tmp_dir = tempdir().unwrap();
        let local_path = tmp_dir.path().join("local");
        let global_path = tmp_dir.path().join("global");

        create_dir_all(&local_path).unwrap();
        create_dir_all(&global_path).unwrap();

        std::fs::write(local_path.join("openmw.cfg"), "resources=./resources").unwrap();
        std::fs::write(global_path.join("openmw.cfg"), "resources=./other").unwrap();

        let fixed_paths = FixedPaths {
            local: local_path.clone(),
            global_config: global_path,
            ..fixed_paths()
        };
        let state = load_game_configs(&fixed_paths).unwrap();

        assert_eq!(
            vec![OpenMWConfig {
                resources: Some(local_path.join("resources")),
                ..Default::default()
            }],
            state.loaded_configs
        );
        assert_eq!(fixed_paths.local, state.user_config_dir);
    }

    #[test]
    fn load_game_configs_should_use_global_config_if_local_config_is_not_present() {
        let tmp_dir = tempdir().unwrap();
        let local_path = tmp_dir.path().join("local");
        let global_path = tmp_dir.path().join("global");

        create_dir_all(&local_path).unwrap();
        create_dir_all(&global_path).unwrap();

        std::fs::write(global_path.join("openmw.cfg"), "resources=./other").unwrap();

        let fixed_paths = FixedPaths {
            local: local_path,
            global_config: global_path.clone(),
            ..fixed_paths()
        };
        let state = load_game_configs(&fixed_paths).unwrap();

        assert_eq!(
            vec![OpenMWConfig {
                resources: Some(global_path.join("other")),
                ..Default::default()
            }],
            state.loaded_configs
        );
        assert_eq!(fixed_paths.global_config, state.user_config_dir);
    }

    #[test]
    fn load_game_configs_should_process_config_entries_in_filo_order_within_each_file() {
        let tmp_dir = tempdir().unwrap();
        let local_path = tmp_dir.path().join("local");
        let other_path_1 = tmp_dir.path().join("other1");
        let other_path_2 = tmp_dir.path().join("other2");
        let other_path_3 = tmp_dir.path().join("other3");

        create_dir_all(&local_path).unwrap();
        create_dir_all(&other_path_1).unwrap();
        create_dir_all(&other_path_2).unwrap();
        create_dir_all(&other_path_3).unwrap();

        std::fs::write(
            local_path.join("openmw.cfg"),
            format!(
                "config=\"{}\"\nconfig=\"{}\"\ncontent=a",
                other_path_1.to_str().unwrap(),
                other_path_2.to_str().unwrap()
            ),
        )
        .unwrap();
        std::fs::write(
            other_path_1.join("openmw.cfg"),
            format!(
                "config=\"{}\"\ncontent=b\ncontent=c",
                other_path_3.to_str().unwrap()
            ),
        )
        .unwrap();
        std::fs::write(other_path_2.join("openmw.cfg"), "content=d").unwrap();
        std::fs::write(other_path_3.join("openmw.cfg"), "content=e").unwrap();

        let fixed_paths = FixedPaths {
            local: local_path.clone(),
            ..fixed_paths()
        };
        let state = load_game_configs(&fixed_paths).unwrap();

        assert_eq!(
            vec![
                OpenMWConfig {
                    config: vec![other_path_1.clone(), other_path_2.clone()],
                    content: vec!["a".to_owned()],
                    ..Default::default()
                },
                OpenMWConfig {
                    content: vec!["d".to_owned()],
                    ..Default::default()
                },
                OpenMWConfig {
                    config: vec![other_path_3.clone()],
                    content: vec!["b".to_owned(), "c".to_owned()],
                    ..Default::default()
                },
                OpenMWConfig {
                    content: vec!["e".to_owned()],
                    ..Default::default()
                }
            ],
            state.loaded_configs
        );
        assert_eq!(other_path_3, state.user_config_dir);
    }

    #[test]
    fn load_game_configs_should_truncate_loaded_configs_when_it_encounters_a_replace_config_entry()
    {
        let tmp_dir = tempdir().unwrap();
        let local_path = tmp_dir.path().join("local");
        let other_path_1 = tmp_dir.path().join("other1");
        let other_path_2 = tmp_dir.path().join("other2");
        let other_path_3 = tmp_dir.path().join("other3");

        create_dir_all(&local_path).unwrap();
        create_dir_all(&other_path_1).unwrap();
        create_dir_all(&other_path_2).unwrap();
        create_dir_all(&other_path_3).unwrap();

        std::fs::write(
            local_path.join("openmw.cfg"),
            format!(
                "config=\"{}\"\nconfig=\"{}\"\ncontent=a",
                other_path_1.to_str().unwrap(),
                other_path_2.to_str().unwrap()
            ),
        )
        .unwrap();
        std::fs::write(
            other_path_1.join("openmw.cfg"),
            format!(
                "config=\"{}\"\ncontent=b\ncontent=c",
                other_path_3.to_str().unwrap()
            ),
        )
        .unwrap();
        std::fs::write(other_path_2.join("openmw.cfg"), "content=d").unwrap();
        std::fs::write(other_path_3.join("openmw.cfg"), "content=e\nreplace=config").unwrap();

        let fixed_paths = FixedPaths {
            local: local_path.clone(),
            ..fixed_paths()
        };
        let state = load_game_configs(&fixed_paths).unwrap();

        assert_eq!(
            vec![
                OpenMWConfig {
                    config: vec![other_path_1.clone(), other_path_2.clone()],
                    content: vec!["a".to_owned()],
                    ..Default::default()
                },
                OpenMWConfig {
                    replace: vec!["config".to_owned()],
                    content: vec!["e".to_owned()],
                    ..Default::default()
                }
            ],
            state.loaded_configs
        );
        assert_eq!(other_path_3, state.user_config_dir);
    }

    #[test]
    fn load_game_configs_should_record_empty_config_if_a_referenced_path_does_not_exist() {
        let tmp_dir = tempdir().unwrap();
        let local_path = tmp_dir.path().join("local");
        let other_path = tmp_dir.path().join("other1");

        create_dir_all(&local_path).unwrap();

        std::fs::write(
            local_path.join("openmw.cfg"),
            format!("config=\"{}\"\ncontent=a", other_path.to_str().unwrap()),
        )
        .unwrap();

        let fixed_paths = FixedPaths {
            local: local_path.clone(),
            ..fixed_paths()
        };
        let state = load_game_configs(&fixed_paths).unwrap();

        assert_eq!(
            vec![
                OpenMWConfig {
                    config: vec![other_path.clone()],
                    content: vec!["a".to_owned()],
                    ..Default::default()
                },
                OpenMWConfig::default()
            ],
            state.loaded_configs
        );
        assert_eq!(other_path, state.user_config_dir);
    }

    #[test]
    fn load_game_configs_should_not_get_stuck_in_a_loop() {
        let tmp_dir = tempdir().unwrap();
        let local_path = tmp_dir.path().join("local");

        create_dir_all(&local_path).unwrap();

        std::fs::write(
            local_path.join("openmw.cfg"),
            format!("config=\"{}\"\ncontent=a", local_path.to_str().unwrap()),
        )
        .unwrap();

        let fixed_paths = FixedPaths {
            local: local_path.clone(),
            ..fixed_paths()
        };
        let state = load_game_configs(&fixed_paths).unwrap();

        assert_eq!(
            vec![OpenMWConfig {
                config: vec![local_path.clone()],
                content: vec!["a".to_owned()],
                ..Default::default()
            }],
            state.loaded_configs
        );
        assert_eq!(local_path, state.user_config_dir);
    }

    #[test]
    fn load_game_config_with_user_config_dir_should_replace_last_loaded_config() {
        let tmp_dir = tempdir().unwrap();
        let game_path = tmp_dir.path().join("game");
        let other_path_1 = tmp_dir.path().join("other1");
        let other_path_2 = tmp_dir.path().join("other2");

        create_dir_all(&game_path).unwrap();
        create_dir_all(&other_path_1).unwrap();
        create_dir_all(&other_path_2).unwrap();

        std::fs::write(
            game_path.join("openmw.cfg"),
            format!("config=\"{}\"\ncontent=a", other_path_1.to_str().unwrap()),
        )
        .unwrap();
        std::fs::write(other_path_1.join("openmw.cfg"), "content=b").unwrap();
        std::fs::write(other_path_2.join("openmw.cfg"), "content=c").unwrap();

        let config = load_game_config_with_user_config_dir(&game_path, &other_path_2).unwrap();

        assert_eq!(
            OpenMWConfig {
                config: vec![other_path_1.clone()],
                content: vec!["a".to_owned(), "c".to_owned()],
                ..Default::default()
            },
            config
        );
    }

    #[test]
    fn load_game_config_with_user_config_dir_should_replace_last_loaded_config_even_if_the_given_dir_has_no_config(
    ) {
        let tmp_dir = tempdir().unwrap();
        let game_path = tmp_dir.path().join("game");
        let other_path_1 = tmp_dir.path().join("other1");
        let other_path_2 = tmp_dir.path().join("other2");

        create_dir_all(&game_path).unwrap();
        create_dir_all(&other_path_1).unwrap();
        create_dir_all(&other_path_2).unwrap();

        std::fs::write(
            game_path.join("openmw.cfg"),
            format!("config=\"{}\"\ncontent=a", other_path_1.to_str().unwrap()),
        )
        .unwrap();
        std::fs::write(other_path_1.join("openmw.cfg"), "content=b").unwrap();

        let config = load_game_config_with_user_config_dir(&game_path, &other_path_2).unwrap();

        assert_eq!(
            OpenMWConfig {
                config: vec![other_path_1.clone()],
                content: vec!["a".to_owned()],
                ..Default::default()
            },
            config
        );
    }

    #[test]
    fn load_non_user_config_should_drop_the_last_loaded_config() {
        let tmp_dir = tempdir().unwrap();
        let game_path = tmp_dir.path().join("game");
        let other_path = tmp_dir.path().join("other");

        create_dir_all(&game_path).unwrap();
        create_dir_all(&other_path).unwrap();

        std::fs::write(
            game_path.join("openmw.cfg"),
            format!("config=\"{}\"\ncontent=a", other_path.to_str().unwrap()),
        )
        .unwrap();
        std::fs::write(other_path.join("openmw.cfg"), "content=b").unwrap();

        let config = load_non_user_config(&game_path).unwrap();

        assert_eq!(
            OpenMWConfig {
                config: vec![other_path.clone()],
                content: vec!["a".to_owned()],
                ..Default::default()
            },
            config
        );
    }

    #[test]
    fn write_openmw_cfg_should_write_data_and_content_entries() {
        let tmp_dir = tempdir().unwrap();
        let ini_path = tmp_dir.path().join("openmw.cfg");

        std::fs::write(&ini_path, "").unwrap();

        let data_paths = &["C:\\Path\\&\"a&&\\Data Files".into(), "/games/path".into()];
        let active_plugin_names = &["a", "b", "c"];
        write_openmw_cfg(&ini_path, data_paths, active_plugin_names).unwrap();

        let file_content = std::fs::read_to_string(ini_path).unwrap();
        let lines: Vec<_> = file_content.lines().collect();

        assert_eq!(
            vec![
                "data=\"C:\\Path\\&&&\"a&&&&\\Data Files\"",
                "data=\"/games/path\"",
                "content=a",
                "content=b",
                "content=c"
            ],
            lines
        );
    }

    #[test]
    fn write_openmw_cfg_should_preserve_existing_entries_other_than_data_and_content() {
        let tmp_dir = tempdir().unwrap();
        let ini_path = tmp_dir.path().join("openmw.cfg");

        std::fs::write(
            &ini_path,
            "key1=value1\ndata=foo\nkey2=value2\nkey2=value3\ncontent=a\ncontent=b\ncontent=c\nkey3=value3")
        .unwrap();

        write_openmw_cfg(&ini_path, &[], &[]).unwrap();

        let file_content = std::fs::read_to_string(ini_path).unwrap();
        let lines: Vec<_> = file_content.lines().collect();

        assert_eq!(
            vec!["key1=value1", "key2=value2", "key2=value3", "key3=value3"],
            lines
        );
    }

    #[test]
    fn write_openmw_cfg_should_not_error_if_the_given_path_does_not_exist() {
        let tmp_dir = tempdir().unwrap();
        let ini_path = tmp_dir.path().join("openmw.cfg");

        write_openmw_cfg(&ini_path, &["foo".into()], &["bar"]).unwrap();

        let file_content = std::fs::read_to_string(ini_path).unwrap();
        let lines: Vec<_> = file_content.lines().collect();

        assert_eq!(vec!["data=\"foo\"", "content=bar"], lines);
    }

    #[test]
    fn write_openmw_cfg_should_create_parent_path_if_it_does_not_exist() {
        let tmp_dir = tempdir().unwrap();
        let ini_path = tmp_dir.path().join("a/b/c/d/openmw.cfg");

        assert!(write_openmw_cfg(&ini_path, &["foo".into()], &["bar"]).is_ok());
    }

    #[test]
    fn write_openmw_cfg_strips_comments() {
        let tmp_dir = tempdir().unwrap();
        let ini_path = tmp_dir.path().join("openmw.cfg");

        std::fs::write(&ini_path, "#Comment").unwrap();

        write_openmw_cfg(&ini_path, &[], &[]).unwrap();

        let file_content = std::fs::read_to_string(ini_path).unwrap();

        assert_eq!("", file_content);
    }
}