summaryrefslogtreecommitdiff
path: root/src/organizercore.cpp
blob: 1a89641defcbffdfba3d8af2fbcc062a8424bc3a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
#include "organizercore.h"

#include "delayedfilewriter.h"
#include "guessedvalue.h"
#include "imodinterface.h"
#include "imoinfo.h"
#include "iplugingame.h"
#include "iuserinterface.h"
#include "loadmechanism.h"
#include "messagedialog.h"
#include "modlistsortproxy.h"
#include "modrepositoryfileinfo.h"
#include "nexusinterface.h"
#include "plugincontainer.h"
#include "pluginlistsortproxy.h"
#include "profile.h"
#include "credentialsdialog.h"
#include "filedialogmemory.h"
#include "modinfodialog.h"
#include "spawn.h"
#include "syncoverwritedialog.h"
#include "nxmaccessmanager.h"
#include <ipluginmodpage.h>
#include <dataarchives.h>
#include <localsavegames.h>
#include <directoryentry.h>
#include <scopeguard.h>
#include <utility.h>
#include <usvfs.h>
#include "appconfig.h"
#include <report.h>
#include <questionboxmemory.h>
#include "lockeddialog.h"
#include "instancemanager.h"
#include <scriptextender.h>
#include "helper.h"
#include "previewdialog.h"

#include <QApplication>
#include <QCoreApplication>
#include <QDialog>
#include <QDialogButtonBox>
#include <QMessageBox>
#include <QNetworkInterface>
#include <QProcess>
#include <QTimer>
#include <QUrl>
#include <QWidget>

#include <QtDebug>
#include <QtGlobal> // for qUtf8Printable, etc

#include <Psapi.h>
#include <Shlobj.h>
#include <tlhelp32.h>
#include <tchar.h> // for _tcsicmp

#include <limits.h>
#include <stddef.h>
#include <string.h> // for memset, wcsrchr

#include <exception>
#include <functional>
#include <boost/algorithm/string/predicate.hpp>
#include <memory>
#include <set>
#include <string> //for wstring
#include <tuple>
#include <utility>


using namespace MOShared;
using namespace MOBase;

//static
CrashDumpsType OrganizerCore::m_globalCrashDumpsType = CrashDumpsType::None;

static bool isOnline()
{
  const auto runningFlags =
    QNetworkInterface::IsUp | QNetworkInterface::IsRunning;

  for (auto&& i : QNetworkInterface::allInterfaces()) {
    if (!(i.flags() & QNetworkInterface::IsLoopBack)) {
      if (i.flags() & runningFlags) {
        auto addresses = i.addressEntries();
        if (!addresses.empty()) {
          return true;
        }
      }
    }
  }

  return false;
}

static std::wstring getProcessName(HANDLE process)
{
  wchar_t buffer[MAX_PATH];
  const wchar_t *fileName = L"unknown";

  if (process == nullptr) return fileName;

  if (::GetProcessImageFileNameW(process, buffer, MAX_PATH) != 0) {
    fileName = wcsrchr(buffer, L'\\');
    if (fileName == nullptr) {
      fileName = buffer;
    }
    else {
      fileName += 1;
    }
  }

  return fileName;
}

// Get parent PID for the given process, return 0 on failure
static DWORD getProcessParentID(DWORD pid)
{
  HANDLE th = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  PROCESSENTRY32 pe = { 0 };
  pe.dwSize = sizeof(PROCESSENTRY32);

  DWORD res = 0;
  if (Process32First(th, &pe))
    do {
      if (pe.th32ProcessID == pid) {
        res = pe.th32ParentProcessID;
        break;
      }
    } while (Process32Next(th, &pe));

  CloseHandle(th);

  return res;
}

static void startSteam(QWidget *widget)
{
  QSettings steamSettings("HKEY_CURRENT_USER\\Software\\Valve\\Steam",
                          QSettings::NativeFormat);
  QString exe = steamSettings.value("SteamExe", "").toString();
  if (!exe.isEmpty()) {
    exe = QString("\"%1\"").arg(exe);
    // See if username and password supplied. If so, pass them into steam.
    QStringList args;
    QString username;
    QString password;
    if (Settings::instance().steam().login(username, password)) {
      args << "-login";
      args << username;
      if (password != "") {
        args << password;
      }
    }
    if (!QProcess::startDetached(exe, args)) {
      reportError(QObject::tr("Failed to start \"%1\"").arg(exe));
    } else {
      QMessageBox::information(
          widget, QObject::tr("Waiting"),
          QObject::tr("Please press OK once you're logged into steam."));
    }
  }
}

template <typename InputIterator>
QStringList toStringList(InputIterator current, InputIterator end)
{
  QStringList result;
  for (; current != end; ++current) {
    result.append(*current);
  }
  return result;
}

bool checkService()
{
  SC_HANDLE serviceManagerHandle = NULL;
  SC_HANDLE serviceHandle = NULL;
  LPSERVICE_STATUS_PROCESS serviceStatus = NULL;
  LPQUERY_SERVICE_CONFIG serviceConfig = NULL;
  bool serviceRunning = true;

  DWORD bytesNeeded;

  try {
    serviceManagerHandle = OpenSCManager(NULL, NULL, SERVICE_QUERY_STATUS | SERVICE_QUERY_CONFIG);
    if (!serviceManagerHandle) {
      log::warn("failed to open service manager (query status) (error {})", GetLastError());
      throw 1;
    }

    serviceHandle = OpenService(serviceManagerHandle, L"EventLog", SERVICE_QUERY_STATUS | SERVICE_QUERY_CONFIG);
    if (!serviceHandle) {
      log::warn("failed to open EventLog service (query status) (error {})", GetLastError());
      throw 2;
    }

    if (QueryServiceConfig(serviceHandle, NULL, 0, &bytesNeeded)
      || (GetLastError() != ERROR_INSUFFICIENT_BUFFER)) {
      log::warn("failed to get size of service config (error {})", GetLastError());
      throw 3;
    }

    DWORD serviceConfigSize = bytesNeeded;
    serviceConfig = (LPQUERY_SERVICE_CONFIG)LocalAlloc(LMEM_FIXED, serviceConfigSize);
    if (!QueryServiceConfig(serviceHandle, serviceConfig, serviceConfigSize, &bytesNeeded)) {
      log::warn("failed to query service config (error {})", GetLastError());
      throw 4;
    }

    if (serviceConfig->dwStartType == SERVICE_DISABLED) {
      log::error("Windows Event Log service is disabled!");
      serviceRunning = false;
    }

    if (QueryServiceStatusEx(serviceHandle, SC_STATUS_PROCESS_INFO, NULL, 0, &bytesNeeded)
      || (GetLastError() != ERROR_INSUFFICIENT_BUFFER)) {
      log::warn("failed to get size of service status (error {})", GetLastError());
      throw 5;
    }

    DWORD serviceStatusSize = bytesNeeded;
    serviceStatus = (LPSERVICE_STATUS_PROCESS)LocalAlloc(LMEM_FIXED, serviceStatusSize);
    if (!QueryServiceStatusEx(serviceHandle, SC_STATUS_PROCESS_INFO, (LPBYTE)serviceStatus, serviceStatusSize, &bytesNeeded)) {
      log::warn("failed to query service status (error {})", GetLastError());
      throw 6;
    }

    if (serviceStatus->dwCurrentState != SERVICE_RUNNING) {
      log::error("Windows Event Log service is not running");
      serviceRunning = false;
    }
  }
  catch (int e) {
    UNUSED_VAR(e);
    serviceRunning = false;
  }

  if (serviceStatus) {
    LocalFree(serviceStatus);
  }
  if (serviceConfig) {
    LocalFree(serviceConfig);
  }
  if (serviceHandle) {
    CloseServiceHandle(serviceHandle);
  }
  if (serviceManagerHandle) {
    CloseServiceHandle(serviceManagerHandle);
  }

  return serviceRunning;
}


OrganizerCore::OrganizerCore(Settings &settings)
  : m_UserInterface(nullptr)
  , m_PluginContainer(nullptr)
  , m_GameName()
  , m_CurrentProfile(nullptr)
  , m_Settings(settings)
  , m_Updater(NexusInterface::instance(m_PluginContainer))
  , m_AboutToRun()
  , m_FinishedRun()
  , m_ModInstalled()
  , m_ModList(m_PluginContainer, this)
  , m_PluginList(this)
  , m_DirectoryRefresher()
  , m_DirectoryStructure(new DirectoryEntry(L"data", nullptr, 0))
  , m_DownloadManager(NexusInterface::instance(m_PluginContainer), this)
  , m_InstallationManager()
  , m_RefresherThread()
  , m_DirectoryUpdate(false)
  , m_ArchivesInit(false)
  , m_PluginListsWriter(std::bind(&OrganizerCore::savePluginList, this))
{
  m_DownloadManager.setOutputDirectory(m_Settings.paths().downloads());

  NexusInterface::instance(m_PluginContainer)->setCacheDirectory(
    m_Settings.paths().cache());

  m_InstallationManager.setModsDirectory(m_Settings.paths().mods());
  m_InstallationManager.setDownloadDirectory(m_Settings.paths().downloads());

  connect(&m_DownloadManager, SIGNAL(downloadSpeed(QString, int)), this,
          SLOT(downloadSpeed(QString, int)));
  connect(&m_DirectoryRefresher, SIGNAL(refreshed()), this,
          SLOT(directory_refreshed()));

  connect(&m_ModList, SIGNAL(removeOrigin(QString)), this,
          SLOT(removeOrigin(QString)));

  connect(NexusInterface::instance(m_PluginContainer)->getAccessManager(),
          SIGNAL(validateSuccessful(bool)), this, SLOT(loginSuccessful(bool)));
  connect(NexusInterface::instance(m_PluginContainer)->getAccessManager(),
          SIGNAL(validateFailed(QString)), this, SLOT(loginFailed(QString)));

  // This seems awfully imperative
  connect(this, SIGNAL(managedGameChanged(MOBase::IPluginGame const *)),
          &m_Settings, SLOT(managedGameChanged(MOBase::IPluginGame const *)));
  connect(this, SIGNAL(managedGameChanged(MOBase::IPluginGame const *)),
          &m_DownloadManager,
          SLOT(managedGameChanged(MOBase::IPluginGame const *)));
  connect(this, SIGNAL(managedGameChanged(MOBase::IPluginGame const *)),
          &m_PluginList, SLOT(managedGameChanged(MOBase::IPluginGame const *)));

  connect(&m_PluginList, &PluginList::writePluginsList, &m_PluginListsWriter,
          &DelayedFileWriterBase::write);

  // make directory refresher run in a separate thread
  m_RefresherThread.start();
  m_DirectoryRefresher.moveToThread(&m_RefresherThread);
}

OrganizerCore::~OrganizerCore()
{
  m_RefresherThread.exit();
  m_RefresherThread.wait();

  prepareStart();

  // profile has to be cleaned up before the modinfo-buffer is cleared
  delete m_CurrentProfile;
  m_CurrentProfile = nullptr;

  ModInfo::clear();
  m_ModList.setProfile(nullptr);
  //  NexusInterface::instance()->cleanup();

  delete m_DirectoryStructure;
}

void OrganizerCore::storeSettings()
{
  if (m_CurrentProfile != nullptr) {
    m_Settings.game().setSelectedProfileName(m_CurrentProfile->name());
  }

  m_ExecutablesList.store(m_Settings);

  FileDialogMemory::save(m_Settings);

  const auto result = m_Settings.sync();

  if (result != QSettings::NoError) {
    QString reason;

    if (result == QSettings::AccessError) {
      reason = tr("File is write protected");
    } else if (result == QSettings::FormatError) {
      reason = tr("Invalid file format (probably a bug)");
    } else {
      reason = tr("Unknown error %1").arg(result);
    }

    QMessageBox::critical(
      qApp->activeWindow(), tr("Failed to write settings"),
      tr("An error occurred trying to write back MO settings to %1: %2")
      .arg(m_Settings.filename(), reason));
  }
}

bool OrganizerCore::testForSteam(bool *found, bool *access)
{
  HANDLE hProcessSnap;
  HANDLE hProcess;
  PROCESSENTRY32 pe32;
  DWORD lastError;

  if (found == nullptr || access == nullptr) {
    return false;
  }

  // Take a snapshot of all processes in the system.
  hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  if (hProcessSnap == INVALID_HANDLE_VALUE) {
    lastError = GetLastError();
    log::error("unable to get snapshot of processes (error {})", lastError);
    return false;
  }

  // Retrieve information about the first process,
  // and exit if unsuccessful
  pe32.dwSize = sizeof(PROCESSENTRY32);
  if (!Process32First(hProcessSnap, &pe32)) {
    lastError = GetLastError();
    log::error("unable to get first process (error {})", lastError);
    CloseHandle(hProcessSnap);
    return false;
  }

  *found = false;
  *access = true;

  // Now walk the snapshot of processes, and
  // display information about each process in turn
  do {
    if ((_tcsicmp(pe32.szExeFile, L"Steam.exe") == 0) ||
        (_tcsicmp(pe32.szExeFile, L"SteamService.exe") == 0)) {

      *found = true;

      // Try to open the process to determine if MO has the proper access
      hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
                             FALSE, pe32.th32ProcessID);
      if (hProcess == NULL) {
        lastError = GetLastError();
        if (lastError == ERROR_ACCESS_DENIED) {
          *access = false;
        }
      } else {
        CloseHandle(hProcess);
      }
      break;
    }

} while(Process32Next(hProcessSnap, &pe32));

CloseHandle(hProcessSnap);
return true;

}

void OrganizerCore::updateExecutablesList()
{
  if (m_PluginContainer == nullptr) {
    log::error("can't update executables list now");
    return;
  }

  m_ExecutablesList.load(managedGame(), m_Settings);

  // TODO this has nothing to do with executables list move to an appropriate
  // function!
  ModInfo::updateFromDisc(
    m_Settings.paths().mods(), &m_DirectoryStructure,
    m_PluginContainer, m_Settings.interface().displayForeign(), managedGame());
}

void OrganizerCore::setUserInterface(IUserInterface *userInterface,
                                     QWidget *widget)
{
  storeSettings();

  m_UserInterface = userInterface;

  if (widget != nullptr) {
    connect(&m_ModList, SIGNAL(modlistChanged(QModelIndex, int)), widget,
            SLOT(modlistChanged(QModelIndex, int)));
    connect(&m_ModList, SIGNAL(modlistChanged(QModelIndexList, int)), widget,
            SLOT(modlistChanged(QModelIndexList, int)));
    connect(&m_ModList, SIGNAL(showMessage(QString)), widget,
            SLOT(showMessage(QString)));
    connect(&m_ModList, SIGNAL(modRenamed(QString, QString)), widget,
            SLOT(modRenamed(QString, QString)));
    connect(&m_ModList, SIGNAL(modUninstalled(QString)), widget,
            SLOT(modRemoved(QString)));
    connect(&m_ModList, SIGNAL(removeSelectedMods()), widget,
            SLOT(removeMod_clicked()));
    connect(&m_ModList, SIGNAL(clearOverwrite()), widget,
      SLOT(clearOverwrite()));
    connect(&m_ModList, SIGNAL(requestColumnSelect(QPoint)), widget,
            SLOT(displayColumnSelection(QPoint)));
    connect(&m_ModList, SIGNAL(fileMoved(QString, QString, QString)), widget,
            SLOT(fileMoved(QString, QString, QString)));
    connect(&m_ModList, SIGNAL(modorder_changed()), widget,
            SLOT(modorder_changed()));
    connect(&m_PluginList, SIGNAL(writePluginsList()), widget,
      SLOT(esplist_changed()));
    connect(&m_PluginList, SIGNAL(esplist_changed()), widget,
      SLOT(esplist_changed()));
    connect(&m_DownloadManager, SIGNAL(showMessage(QString)), widget,
            SLOT(showMessage(QString)));
  }

  m_InstallationManager.setParentWidget(widget);
  m_Updater.setUserInterface(widget);

  if (userInterface != nullptr) {
    // this currently wouldn't work reliably if the ui isn't initialized yet to
    // display the result
    if (isOnline() && !m_Settings.network().offlineMode()) {
      m_Updater.testForUpdate();
    } else {
      log::debug("user doesn't seem to be connected to the internet");
    }
  }
}

void OrganizerCore::connectPlugins(PluginContainer *container)
{
  m_DownloadManager.setSupportedExtensions(
      m_InstallationManager.getSupportedExtensions());
  m_PluginContainer = container;
  m_Updater.setPluginContainer(m_PluginContainer);
  m_DownloadManager.setPluginContainer(m_PluginContainer);
  m_ModList.setPluginContainer(m_PluginContainer);

  if (!m_GameName.isEmpty()) {
    m_GamePlugin = m_PluginContainer->managedGame(m_GameName);
    emit managedGameChanged(m_GamePlugin);
  }
}

void OrganizerCore::disconnectPlugins()
{
  m_AboutToRun.disconnect_all_slots();
  m_FinishedRun.disconnect_all_slots();
  m_ModInstalled.disconnect_all_slots();
  m_ModList.disconnectSlots();
  m_PluginList.disconnectSlots();
  m_Updater.setPluginContainer(nullptr);
  m_DownloadManager.setPluginContainer(nullptr);
  m_ModList.setPluginContainer(nullptr);

  m_Settings.plugins().clearPlugins();
  m_GamePlugin      = nullptr;
  m_PluginContainer = nullptr;
}

void OrganizerCore::setManagedGame(MOBase::IPluginGame *game)
{
  m_GameName   = game->gameName();
  m_GamePlugin = game;
  qApp->setProperty("managed_game", QVariant::fromValue(m_GamePlugin));
  emit managedGameChanged(m_GamePlugin);
}

Settings &OrganizerCore::settings()
{
  return m_Settings;
}

bool OrganizerCore::nexusApi(bool retry)
{
  NXMAccessManager *accessManager
      = NexusInterface::instance(m_PluginContainer)->getAccessManager();

  if ((accessManager->validateAttempted() || accessManager->validated())
      && !retry) {
    // previous attempt, maybe even successful
    return false;
  } else {
    QString apiKey;
    if (m_Settings.nexus().apiKey(apiKey)) {
      // credentials stored or user entered them manually
      log::debug("attempt to verify nexus api key");
      accessManager->apiCheck(apiKey);
      return true;
    } else {
      // no credentials stored and user didn't enter them
      accessManager->refuseValidation();
      return false;
    }
  }
}

void OrganizerCore::startMOUpdate()
{
  if (nexusApi()) {
    m_PostLoginTasks.append([&]() { m_Updater.startUpdate(); });
  } else {
    m_Updater.startUpdate();
  }
}

void OrganizerCore::downloadRequestedNXM(const QString &url)
{
  log::debug("download requested: {}", url);
  if (nexusApi()) {
    m_PendingDownloads.append(url);
  } else {
    m_DownloadManager.addNXMDownload(url);
  }
}

void OrganizerCore::externalMessage(const QString &message)
{
  if (MOShortcut moshortcut{ message } ) {
    if(moshortcut.hasExecutable())
      runShortcut(moshortcut);
  }
  else if (isNxmLink(message)) {
    MessageDialog::showMessage(tr("Download started"), qApp->activeWindow());
    downloadRequestedNXM(message);
  }
}

void OrganizerCore::downloadRequested(QNetworkReply *reply, QString gameName, int modID,
                                      const QString &fileName)
{
  try {
    if (m_DownloadManager.addDownload(reply, QStringList(), fileName, gameName, modID, 0,
                                      new ModRepositoryFileInfo(gameName, modID))) {
      MessageDialog::showMessage(tr("Download started"), qApp->activeWindow());
    }
  } catch (const std::exception &e) {
    MessageDialog::showMessage(tr("Download failed"), qApp->activeWindow());
    log::error("exception starting download: {}", e.what());
  }
}

void OrganizerCore::removeOrigin(const QString &name)
{
  FilesOrigin &origin = m_DirectoryStructure->getOriginByName(ToWString(name));
  origin.enable(false);
  refreshLists();
}

void OrganizerCore::downloadSpeed(const QString &serverName, int bytesPerSecond)
{
  m_Settings.network().setDownloadSpeed(serverName, bytesPerSecond);
}

InstallationManager *OrganizerCore::installationManager()
{
  return &m_InstallationManager;
}

bool OrganizerCore::createDirectory(const QString &path) {
  if (!QDir(path).exists() && !QDir().mkpath(path)) {
    QMessageBox::critical(nullptr, QObject::tr("Error"),
                          QObject::tr("Failed to create \"%1\". Your user "
                                      "account probably lacks permission.")
                              .arg(QDir::toNativeSeparators(path)));
    return false;
  } else {
    return true;
  }
}

bool OrganizerCore::checkPathSymlinks() {
  bool hasSymlink = (QFileInfo(m_Settings.paths().profiles()).isSymLink() ||
    QFileInfo(m_Settings.paths().mods()).isSymLink() ||
    QFileInfo(m_Settings.paths().overwrite()).isSymLink());
  if (hasSymlink) {
    QMessageBox::critical(nullptr, QObject::tr("Error"),
      QObject::tr("One of the configured MO2 directories (profiles, mods, or overwrite) "
        "is on a path containing a symbolic (or other) link. This is incompatible "
        "with MO2's VFS system."));
    return false;
  }
  return true;
}

bool OrganizerCore::bootstrap() {
  return createDirectory(m_Settings.paths().profiles()) &&
         createDirectory(m_Settings.paths().mods()) &&
         createDirectory(m_Settings.paths().downloads()) &&
         createDirectory(m_Settings.paths().overwrite()) &&
         createDirectory(QString::fromStdWString(crashDumpsPath())) &&
         checkPathSymlinks() && cycleDiagnostics();
}

void OrganizerCore::createDefaultProfile()
{
  QString profilesPath = settings().paths().profiles();
  if (QDir(profilesPath).entryList(QDir::AllDirs | QDir::NoDotAndDotDot).size()
      == 0) {
    Profile newProf("Default", managedGame(), false);
  }
}

void OrganizerCore::prepareVFS()
{
  m_USVFS.updateMapping(fileMapping(m_CurrentProfile->name(), QString()));
}

void OrganizerCore::updateVFSParams(
  log::Levels logLevel, CrashDumpsType crashDumpsType, QString executableBlacklist)
{
  setGlobalCrashDumpsType(crashDumpsType);
  m_USVFS.updateParams(logLevel, crashDumpsType, executableBlacklist);
}

void OrganizerCore::setLogLevel(log::Levels level)
{
  m_Settings.diagnostics().setLogLevel(level);

  updateVFSParams(
    m_Settings.diagnostics().logLevel(),
    m_Settings.diagnostics().crashDumpsType(),
    m_Settings.executablesBlacklist());

  log::getDefault().setLevel(m_Settings.diagnostics().logLevel());
}

bool OrganizerCore::cycleDiagnostics() {
  if (int maxDumps = settings().diagnostics().crashDumpsMax())
    removeOldFiles(QString::fromStdWString(crashDumpsPath()), "*.dmp", maxDumps, QDir::Time|QDir::Reversed);
  return true;
}

//static
void OrganizerCore::setGlobalCrashDumpsType(CrashDumpsType type) {
  m_globalCrashDumpsType = type;
}

//static
std::wstring OrganizerCore::crashDumpsPath() {
  return (
    qApp->property("dataPath").toString() + "/"
    + QString::fromStdWString(AppConfig::dumpsDir())
    ).toStdWString();
}

bool OrganizerCore::getArchiveParsing() const
{
  return m_ArchiveParsing;
}

void OrganizerCore::setArchiveParsing(const bool archiveParsing)
{
  m_ArchiveParsing = archiveParsing;
}

void OrganizerCore::setCurrentProfile(const QString &profileName)
{
  if ((m_CurrentProfile != nullptr)
      && (profileName == m_CurrentProfile->name())) {
    return;
  }

  QDir profileBaseDir(settings().paths().profiles());
  QString profileDir = profileBaseDir.absoluteFilePath(profileName);

  if (!QDir(profileDir).exists()) {
    // selected profile doesn't exist. Ensure there is at least one profile,
    // then pick any one
    createDefaultProfile();

    profileDir = profileBaseDir.absoluteFilePath(
        profileBaseDir.entryList(QDir::AllDirs | QDir::NoDotAndDotDot).at(0));
  }

  Profile *newProfile = new Profile(QDir(profileDir), managedGame());

  delete m_CurrentProfile;
  m_CurrentProfile = newProfile;
  m_ModList.setProfile(newProfile);

  if (m_CurrentProfile->invalidationActive(nullptr)) {
    m_CurrentProfile->activateInvalidation();
  } else {
    m_CurrentProfile->deactivateInvalidation();
  }

  m_Settings.game().setSelectedProfileName(m_CurrentProfile->name());

  connect(m_CurrentProfile, SIGNAL(modStatusChanged(uint)), this, SLOT(modStatusChanged(uint)));
  connect(m_CurrentProfile, SIGNAL(modStatusChanged(QList<uint>)), this, SLOT(modStatusChanged(QList<uint>)));
  refreshDirectoryStructure();
}

MOBase::IModRepositoryBridge *OrganizerCore::createNexusBridge() const
{
  return new NexusBridge(m_PluginContainer);
}

QString OrganizerCore::profileName() const
{
  if (m_CurrentProfile != nullptr) {
    return m_CurrentProfile->name();
  } else {
    return "";
  }
}

QString OrganizerCore::profilePath() const
{
  if (m_CurrentProfile != nullptr) {
    return m_CurrentProfile->absolutePath();
  } else {
    return "";
  }
}

QString OrganizerCore::downloadsPath() const
{
  return QDir::fromNativeSeparators(m_Settings.paths().downloads());
}

QString OrganizerCore::overwritePath() const
{
  return QDir::fromNativeSeparators(m_Settings.paths().overwrite());
}

QString OrganizerCore::basePath() const
{
  return QDir::fromNativeSeparators(m_Settings.paths().base());
}

QString OrganizerCore::modsPath() const
{
  return QDir::fromNativeSeparators(m_Settings.paths().mods());
}

MOBase::VersionInfo OrganizerCore::appVersion() const
{
  return m_Updater.getVersion();
}

MOBase::IModInterface *OrganizerCore::getMod(const QString &name) const
{
  unsigned int index = ModInfo::getIndex(name);
  return index == UINT_MAX ? nullptr : ModInfo::getByIndex(index).data();
}

MOBase::IPluginGame *OrganizerCore::getGame(const QString &name) const
{
  for (IPluginGame *game : m_PluginContainer->plugins<IPluginGame>()) {
    if (game != nullptr && game->gameShortName().compare(name, Qt::CaseInsensitive) == 0)
      return game;
  }
  return nullptr;
}

MOBase::IModInterface *OrganizerCore::createMod(GuessedValue<QString> &name)
{
  bool merge = false;
  if (!m_InstallationManager.testOverwrite(name, &merge)) {
    return nullptr;
  }

  m_InstallationManager.setModsDirectory(m_Settings.paths().mods());

  QString targetDirectory
      = QDir::fromNativeSeparators(m_Settings.paths().mods())
            .append("/")
            .append(name);

  QSettings settingsFile(targetDirectory + "/meta.ini", QSettings::IniFormat);

  if (!merge) {
    settingsFile.setValue("modid", 0);
    settingsFile.setValue("version", "");
    settingsFile.setValue("newestVersion", "");
    settingsFile.setValue("category", 0);
    settingsFile.setValue("installationFile", "");

    settingsFile.remove("installedFiles");
    settingsFile.beginWriteArray("installedFiles", 0);
    settingsFile.endArray();
  }

  return ModInfo::createFrom(m_PluginContainer, m_GamePlugin, QDir(targetDirectory), &m_DirectoryStructure)
      .data();
}

bool OrganizerCore::removeMod(MOBase::IModInterface *mod)
{
  unsigned int index = ModInfo::getIndex(mod->name());
  if (index == UINT_MAX) {
    return mod->remove();
  } else {
    return ModInfo::removeMod(index);
  }
}

void OrganizerCore::modDataChanged(MOBase::IModInterface *)
{
  refreshModList(false);
}

QVariant OrganizerCore::pluginSetting(const QString &pluginName,
                                      const QString &key) const
{
  return m_Settings.plugins().pluginSetting(pluginName, key);
}

void OrganizerCore::setPluginSetting(const QString &pluginName,
                                     const QString &key, const QVariant &value)
{
  m_Settings.plugins().setPluginSetting(pluginName, key, value);
}

QVariant OrganizerCore::persistent(const QString &pluginName,
                                   const QString &key,
                                   const QVariant &def) const
{
  return m_Settings.plugins().pluginPersistent(pluginName, key, def);
}

void OrganizerCore::setPersistent(const QString &pluginName, const QString &key,
                                  const QVariant &value, bool sync)
{
  m_Settings.plugins().setPluginPersistent(pluginName, key, value, sync);
}

QString OrganizerCore::pluginDataPath() const
{
  return qApp->applicationDirPath() + "/" + ToQString(AppConfig::pluginPath())
         + "/data";
}

MOBase::IModInterface *OrganizerCore::installMod(const QString &fileName,
                                                 const QString &initModName)
{
  if (m_CurrentProfile == nullptr) {
    return nullptr;
  }

  if (m_InstallationManager.isRunning()) {
    QMessageBox::information(
      qApp->activeWindow(), tr("Installation cancelled"),
      tr("Another installation is currently in progress."), QMessageBox::Ok);
    return nullptr;
  }

  bool hasIniTweaks = false;
  GuessedValue<QString> modName;
  if (!initModName.isEmpty()) {
    modName.update(initModName, GUESS_USER);
  }
  m_CurrentProfile->writeModlistNow();
  m_InstallationManager.setModsDirectory(m_Settings.paths().mods());
  if (m_InstallationManager.install(fileName, modName, hasIniTweaks)) {
    MessageDialog::showMessage(tr("Installation successful"),
                               qApp->activeWindow());
    refreshModList();

    int modIndex = ModInfo::getIndex(modName);
    if (modIndex != UINT_MAX) {
      ModInfo::Ptr modInfo = ModInfo::getByIndex(modIndex);
      if (hasIniTweaks && (m_UserInterface != nullptr)
          && (QMessageBox::question(qApp->activeWindow(), tr("Configure Mod"),
                                    tr("This mod contains ini tweaks. Do you "
                                       "want to configure them now?"),
                                    QMessageBox::Yes | QMessageBox::No)
              == QMessageBox::Yes)) {
        m_UserInterface->displayModInformation(
          modInfo, modIndex, ModInfoTabIDs::IniFiles);
      }
      m_ModInstalled(modName);
      m_DownloadManager.markInstalled(fileName);
      emit modInstalled(modName);
      return modInfo.data();
    } else {
      reportError(tr("mod not found: %1").arg(qUtf8Printable(modName)));
    }
  } else if (m_InstallationManager.wasCancelled()) {
    QMessageBox::information(qApp->activeWindow(), tr("Installation cancelled"),
                             tr("The mod was not installed completely."),
                             QMessageBox::Ok);
  }
  return nullptr;
}

void OrganizerCore::installDownload(int index)
{
  if (m_InstallationManager.isRunning()) {
    QMessageBox::information(
      qApp->activeWindow(), tr("Installation cancelled"),
      tr("Another installation is currently in progress."), QMessageBox::Ok);
    return;
  }

  try {
    QString fileName = m_DownloadManager.getFilePath(index);
    QString gameName = m_DownloadManager.getGameName(index);
    int modID        = m_DownloadManager.getModID(index);
    int fileID       = m_DownloadManager.getFileInfo(index)->fileID;
    GuessedValue<QString> modName;

    // see if there already are mods with the specified mod id
    if (modID != 0) {
      std::vector<ModInfo::Ptr> modInfo = ModInfo::getByModID(gameName, modID);
      for (auto iter = modInfo.begin(); iter != modInfo.end(); ++iter) {
        std::vector<ModInfo::EFlag> flags = (*iter)->getFlags();
        if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_BACKUP)
            == flags.end()) {
          modName.update((*iter)->name(), GUESS_PRESET);
          (*iter)->saveMeta();
        }
      }
    }

    m_CurrentProfile->writeModlistNow();

    bool hasIniTweaks = false;
    m_InstallationManager.setModsDirectory(m_Settings.paths().mods());
    if (m_InstallationManager.install(fileName, modName, hasIniTweaks)) {
      MessageDialog::showMessage(tr("Installation successful"),
                                 qApp->activeWindow());
      refreshModList();

      int modIndex = ModInfo::getIndex(modName);
      if (modIndex != UINT_MAX) {
        ModInfo::Ptr modInfo = ModInfo::getByIndex(modIndex);
        modInfo->addInstalledFile(modID, fileID);

        if (hasIniTweaks && m_UserInterface != nullptr
            && (QMessageBox::question(qApp->activeWindow(), tr("Configure Mod"),
                                      tr("This mod contains ini tweaks. Do you "
                                         "want to configure them now?"),
                                      QMessageBox::Yes | QMessageBox::No)
                == QMessageBox::Yes)) {
          m_UserInterface->displayModInformation(
            modInfo, modIndex, ModInfoTabIDs::IniFiles);
        }

        m_ModInstalled(modName);
      } else {
        reportError(tr("mod not found: %1").arg(qUtf8Printable(modName)));
      }
      m_DownloadManager.markInstalled(index);

      emit modInstalled(modName);
    } else if (m_InstallationManager.wasCancelled()) {
      QMessageBox::information(
          qApp->activeWindow(), tr("Installation cancelled"),
          tr("The mod was not installed completely."), QMessageBox::Ok);
    }
  } catch (const std::exception &e) {
    reportError(e.what());
  }
}

QString OrganizerCore::resolvePath(const QString &fileName) const
{
  if (m_DirectoryStructure == nullptr) {
    return QString();
  }
  const FileEntry::Ptr file
      = m_DirectoryStructure->searchFile(ToWString(fileName), nullptr);
  if (file.get() != nullptr) {
    return ToQString(file->getFullPath());
  } else {
    return QString();
  }
}

QStringList OrganizerCore::listDirectories(const QString &directoryName) const
{
  QStringList result;
  DirectoryEntry *dir = m_DirectoryStructure;
  if (!directoryName.isEmpty())
    dir = dir->findSubDirectoryRecursive(ToWString(directoryName));
  if (dir != nullptr) {
    std::vector<DirectoryEntry *>::iterator current, end;
    dir->getSubDirectories(current, end);
    for (; current != end; ++current) {
      result.append(ToQString((*current)->getName()));
    }
  }
  return result;
}

QStringList OrganizerCore::findFiles(
    const QString &path,
    const std::function<bool(const QString &)> &filter) const
{
  QStringList result;
  DirectoryEntry *dir = m_DirectoryStructure;
  if (!path.isEmpty())
    dir = dir->findSubDirectoryRecursive(ToWString(path));
  if (dir != nullptr) {
    std::vector<FileEntry::Ptr> files = dir->getFiles();
    foreach (FileEntry::Ptr file, files) {
      if (filter(ToQString(file->getFullPath()))) {
        result.append(ToQString(file->getFullPath()));
      }
    }
  }
  return result;
}

QStringList OrganizerCore::getFileOrigins(const QString &fileName) const
{
  QStringList result;
  const FileEntry::Ptr file = m_DirectoryStructure->searchFile(ToWString(fileName), nullptr);

  if (file.get() != nullptr) {
    result.append(ToQString(
        m_DirectoryStructure->getOriginByID(file->getOrigin()).getName()));
    foreach (auto i, file->getAlternatives()) {
      result.append(
          ToQString(m_DirectoryStructure->getOriginByID(i.first).getName()));
    }
  }
  return result;
}

QList<MOBase::IOrganizer::FileInfo> OrganizerCore::findFileInfos(
    const QString &path,
    const std::function<bool(const MOBase::IOrganizer::FileInfo &)> &filter)
    const
{
  QList<IOrganizer::FileInfo> result;
  DirectoryEntry *dir = m_DirectoryStructure;
  if (!path.isEmpty())
    dir = dir->findSubDirectoryRecursive(ToWString(path));
  if (dir != nullptr) {
    std::vector<FileEntry::Ptr> files = dir->getFiles();
    foreach (FileEntry::Ptr file, files) {
      IOrganizer::FileInfo info;
      info.filePath    = ToQString(file->getFullPath());
      bool fromArchive = false;
      info.origins.append(ToQString(
          m_DirectoryStructure->getOriginByID(file->getOrigin(fromArchive))
              .getName()));
      info.archive = fromArchive ? ToQString(file->getArchive().first) : "";
      foreach (auto idx, file->getAlternatives()) {
        info.origins.append(
            ToQString(m_DirectoryStructure->getOriginByID(idx.first).getName()));
      }

      if (filter(info)) {
        result.append(info);
      }
    }
  }
  return result;
}

DownloadManager *OrganizerCore::downloadManager()
{
  return &m_DownloadManager;
}

PluginList *OrganizerCore::pluginList()
{
  return &m_PluginList;
}

ModList *OrganizerCore::modList()
{
  return &m_ModList;
}

QStringList OrganizerCore::modsSortedByProfilePriority() const
{
  QStringList res;
  for (int i = currentProfile()->getPriorityMinimum();
           i < currentProfile()->getPriorityMinimum() + (int)currentProfile()->numRegularMods();
           ++i) {
    int modIndex = currentProfile()->modIndexByPriority(i);
    auto modInfo = ModInfo::getByIndex(modIndex);
    if (!modInfo->hasFlag(ModInfo::FLAG_OVERWRITE) &&
        !modInfo->hasFlag(ModInfo::FLAG_BACKUP)) {
      res.push_back(ModInfo::getByIndex(modIndex)->name());
    }
  }
  return res;
}

QString OrganizerCore::findJavaInstallation(const QString& jarFile)
{
  if (!jarFile.isEmpty()) {
    // try to find java automatically based on the given jar file
    std::wstring jarFileW = jarFile.toStdWString();

    WCHAR buffer[MAX_PATH];
    if (::FindExecutableW(jarFileW.c_str(), nullptr, buffer) > (HINSTANCE)32) {
      DWORD binaryType = 0UL;
      if (!::GetBinaryTypeW(buffer, &binaryType)) {
        log::debug(
          "failed to determine binary type of \"{}\": {}",
          QString::fromWCharArray(buffer), ::GetLastError());
      } else if (binaryType == SCS_32BIT_BINARY || binaryType == SCS_64BIT_BINARY) {
        return QString::fromWCharArray(buffer);
      }
    }
  }

  // second attempt: look to the registry
  QSettings reg("HKEY_LOCAL_MACHINE\\Software\\JavaSoft\\Java Runtime Environment", QSettings::NativeFormat);
  if (reg.contains("CurrentVersion")) {
    QString currentVersion = reg.value("CurrentVersion").toString();
    return reg.value(QString("%1/JavaHome").arg(currentVersion)).toString().append("\\bin\\javaw.exe");
  }

  // not found
  return {};
}

bool OrganizerCore::getFileExecutionContext(
  QWidget* parent, const QFileInfo &targetInfo,
  QFileInfo &binaryInfo, QString &arguments, FileExecutionTypes& type)
{
  QString extension = targetInfo.suffix();
  if ((extension.compare("cmd", Qt::CaseInsensitive) == 0) ||
    (extension.compare("com", Qt::CaseInsensitive) == 0) ||
    (extension.compare("bat", Qt::CaseInsensitive) == 0)) {
    binaryInfo = QFileInfo("C:\\Windows\\System32\\cmd.exe");
    arguments = QString("/C \"%1\"").arg(QDir::toNativeSeparators(targetInfo.absoluteFilePath()));
    type = FileExecutionTypes::Executable;
    return true;
  } else if (extension.compare("exe", Qt::CaseInsensitive) == 0) {
    binaryInfo = targetInfo;
    type = FileExecutionTypes::Executable;
    return true;
  } else if (extension.compare("jar", Qt::CaseInsensitive) == 0) {
    auto java = findJavaInstallation(targetInfo.absoluteFilePath());

    if (java.isEmpty()) {
      java = QFileDialog::getOpenFileName(
        parent, QObject::tr("Select binary"),
        QString(), QObject::tr("Binary") + " (*.exe)");
    }

    if (java.isEmpty()) {
      return false;
    }

    binaryInfo = QFileInfo(java);
    arguments = QString("-jar \"%1\"").arg(QDir::toNativeSeparators(targetInfo.absoluteFilePath()));
    type = FileExecutionTypes::Executable;

    return true;
  } else {
    type = FileExecutionTypes::Other;
    return true;
  }
}

bool OrganizerCore::executeFileVirtualized(
  QWidget* parent, const QFileInfo& targetInfo)
{
  QFileInfo binaryInfo;
  QString arguments;
  FileExecutionTypes type;

  if (!getFileExecutionContext(parent, targetInfo, binaryInfo, arguments, type)) {
    return false;
  }

  switch (type)
  {
    case FileExecutionTypes::Executable: {
      spawnBinaryDirect(
        binaryInfo, arguments, currentProfile()->name(),
        targetInfo.absolutePath(), "", "");

      return true;
    }

    case FileExecutionTypes::Other: {
      ::ShellExecuteW(nullptr, L"open",
        ToWString(targetInfo.absoluteFilePath()).c_str(),
        nullptr, nullptr, SW_SHOWNORMAL);

      return true;
    }
  }

  // nop
  return false;
}

bool OrganizerCore::previewFileWithAlternatives(
  QWidget* parent, QString fileName, int selectedOrigin)
{
  fileName = QDir::fromNativeSeparators(fileName);

  // what we have is an absolute path to the file in its actual location (for the primary origin)
  // what we want is the path relative to the virtual data directory

  // we need to look in the virtual directory for the file to make sure the info is up to date.

  // check if the file comes from the actual data folder instead of a mod
  QDir gameDirectory = managedGame()->dataDirectory().absolutePath();
  QString relativePath = gameDirectory.relativeFilePath(fileName);
  QDir dirRelativePath = gameDirectory.relativeFilePath(fileName);

  // if the file is on a different drive the dirRelativePath will actually be an
  // absolute path so we make sure that is not the case
  if (!dirRelativePath.isAbsolute() && !relativePath.startsWith("..")) {
    fileName = relativePath;
  }
  else {
    // crude: we search for the next slash after the base mod directory to skip
    // everything up to the data-relative directory
    int offset = settings().paths().mods().size() + 1;
    offset = fileName.indexOf("/", offset);
    fileName = fileName.mid(offset + 1);
  }



  const FileEntry::Ptr file = directoryStructure()->searchFile(ToWString(fileName), nullptr);

  if (file.get() == nullptr) {
    reportError(tr("file not found: %1").arg(qUtf8Printable(fileName)));
    return false;
  }

  // set up preview dialog
  PreviewDialog preview(fileName, parent);

  auto addFunc = [&](int originId) {
    FilesOrigin &origin = directoryStructure()->getOriginByID(originId);
    QString filePath = QDir::fromNativeSeparators(ToQString(origin.getPath())) + "/" + fileName;
    if (QFile::exists(filePath)) {
      // it's very possible the file doesn't exist, because it's inside an archive. we don't support that
      QWidget *wid = m_PluginContainer->previewGenerator().genPreview(filePath);
      if (wid == nullptr) {
        reportError(tr("failed to generate preview for %1").arg(filePath));
      }
      else {
        preview.addVariant(ToQString(origin.getName()), wid);
      }
    }
  };

  if (selectedOrigin == -1) {
    // don't bother with the vector of origins, just add them as they come
    addFunc(file->getOrigin());
    for (auto alt : file->getAlternatives()) {
      addFunc(alt.first);
    }
  } else {
    std::vector<int> origins;

    // start with the primary origin
    origins.push_back(file->getOrigin());

    // add other origins, push to front if it's the selected one
    for (auto alt : file->getAlternatives()) {
      if (alt.first == selectedOrigin) {
        origins.insert(origins.begin(), alt.first);
      } else {
        origins.push_back(alt.first);
      }
    }

    // can't be empty; either the primary origin was the selected one, or it
    // was one of the alternatives, which got inserted in front

    if (origins[0] != selectedOrigin) {
      // sanity check, this shouldn't happen unless the caller passed an
      // incorrect id

      log::warn(
        "selected preview origin {} not found in list of alternatives",
        selectedOrigin);
    }

    for (int id : origins) {
      addFunc(id);
    }
  }

  if (preview.numVariants() > 0) {
    preview.exec();
    return true;
  }
  else {
    QMessageBox::information(
      parent, tr("Sorry"),
      tr("Sorry, can't preview anything. This function currently does not support extracting from bsas."));

    return false;
  }
}

bool OrganizerCore::previewFile(
  QWidget* parent, const QString& originName, const QString& path)
{
  if (!QFile::exists(path)) {
    reportError(tr("File '%1' not found.").arg(path));
    return false;
  }

  PreviewDialog preview(path, parent);

  QWidget *wid = m_PluginContainer->previewGenerator().genPreview(path);
  if (wid == nullptr) {
    reportError(tr("Failed to generate preview for %1").arg(path));
    return false;
  }

  preview.addVariant(originName, wid);
  preview.exec();

  return true;
}

void OrganizerCore::spawnBinary(const QFileInfo &binary,
                                const QString &arguments,
                                const QDir &currentDirectory,
                                const QString &steamAppID,
                                const QString &customOverwrite,
                                const QList<MOBase::ExecutableForcedLoadSetting> &forcedLibraries)
{
  DWORD processExitCode = 0;
  HANDLE processHandle = spawnBinaryDirect(binary, arguments, m_CurrentProfile->name(), currentDirectory, steamAppID, customOverwrite, forcedLibraries, &processExitCode);
  if (processHandle != INVALID_HANDLE_VALUE) {
    refreshDirectoryStructure();
    // need to remove our stored load order because it may be outdated if a foreign tool changed the
    // file time. After removing that file, refreshESPList will use the file time as the order
    if (managedGame()->loadOrderMechanism() == IPluginGame::LoadOrderMechanism::FileTime) {
      log::debug("removing loadorder.txt");
      QFile::remove(m_CurrentProfile->getLoadOrderFileName());
    }
    refreshDirectoryStructure();

    refreshESPList(true);
    savePluginList();

    //These callbacks should not fiddle with directoy structure and ESPs.
    m_FinishedRun(binary.absoluteFilePath(), processExitCode);
  }
}

HANDLE OrganizerCore::spawnBinaryDirect(const QFileInfo &binary,
                                        const QString &arguments,
                                        const QString &profileName,
                                        const QDir &currentDirectory,
                                        const QString &steamAppID,
                                        const QString &customOverwrite,
                                        const QList<MOBase::ExecutableForcedLoadSetting> &forcedLibraries,
                                        LPDWORD exitCode)
{
  HANDLE processHandle = spawnBinaryProcess(binary, arguments, profileName, currentDirectory, steamAppID, customOverwrite, forcedLibraries);
  if (Settings::instance().interface().lockGUI() && processHandle != INVALID_HANDLE_VALUE) {
    std::unique_ptr<LockedDialog> dlg;
    ILockedWaitingForProcess* uilock = nullptr;

    if (m_UserInterface != nullptr) {
      uilock = m_UserInterface->lock();
    }
    else {
      // i.e. when running command line shortcuts there is no m_UserInterface
      dlg.reset(new LockedDialog);
      dlg->show();
      dlg->setEnabled(true);
      uilock = dlg.get();
    }

    ON_BLOCK_EXIT([&]() {
      if (m_UserInterface != nullptr) {
        m_UserInterface->unlock();
      } });

    DWORD ignoreExitCode;
    waitForProcessCompletion(processHandle, exitCode ? exitCode : &ignoreExitCode, uilock);
    cycleDiagnostics();
  }

  return processHandle;
}


HANDLE OrganizerCore::spawnBinaryProcess(const QFileInfo &binary,
                                         const QString &arguments,
                                         const QString &profileName,
                                         const QDir &currentDirectory,
                                         const QString &steamAppID,
                                         const QString &customOverwrite,
                                         const QList<MOBase::ExecutableForcedLoadSetting> &forcedLibraries)
{
  prepareStart();

  if (!binary.exists()) {
    reportError(
        tr("Executable not found: %1").arg(qUtf8Printable(binary.absoluteFilePath())));
    return INVALID_HANDLE_VALUE;
  }

  if (!steamAppID.isEmpty()) {
    ::SetEnvironmentVariableW(L"SteamAPPId", ToWString(steamAppID).c_str());
  } else {
    ::SetEnvironmentVariableW(L"SteamAPPId",
                              ToWString(m_Settings.steam().appID()).c_str());
  }

  QWidget *window = qApp->activeWindow();
  if ((window != nullptr) && (!window->isVisible())) {
    window = nullptr;
  }

  // This could possibly be extracted somewhere else but it's probably for when
  // we have more than one provider of game registration.
  if ((QFileInfo(
           managedGame()->gameDirectory().absoluteFilePath("steam_api.dll"))
           .exists()
       || QFileInfo(managedGame()->gameDirectory().absoluteFilePath(
                        "steam_api64.dll"))
              .exists())
      && (m_Settings.game().loadMechanismType() == LoadMechanism::LOAD_MODORGANIZER)) {

    bool steamFound = true;
    bool steamAccess = true;
    if (!testForSteam(&steamFound, &steamAccess)) {
      log::error("unable to determine state of Steam");
    }

    if (!steamFound) {
      QDialogButtonBox::StandardButton result;
      result = QuestionBoxMemory::query(window, "steamQuery", binary.fileName(),
                  tr("Start Steam?"),
                  tr("Steam is required to be running already to correctly start the game. "
                    "Should MO try to start steam now?"),
                  QDialogButtonBox::Yes | QDialogButtonBox::No | QDialogButtonBox::Cancel);
      if (result == QDialogButtonBox::Yes) {
        startSteam(window);

        // double-check that Steam is started and MO has access
        steamFound = true;
        steamAccess = true;
        if (!testForSteam(&steamFound, &steamAccess)) {
          log::error("unable to determine state of Steam");
        } else if (!steamFound) {
          log::error("could not find Steam");
        }

      } else if (result == QDialogButtonBox::Cancel) {
        return INVALID_HANDLE_VALUE;
      }
    }

    if (!steamAccess) {
      QDialogButtonBox::StandardButton result;
      result = QuestionBoxMemory::query(window, "steamAdminQuery", binary.fileName(),
                  tr("Steam: Access Denied"),
                  tr("MO was denied access to the Steam process.  This normally indicates that "
                     "Steam is being run as administrator while MO is not.  This can cause issues "
                     "launching the game.  It is recommended to not run Steam as administrator unless "
                     "absolutely necessary.\n\n"
                     "Restart MO as administrator?"),
                  QDialogButtonBox::Yes | QDialogButtonBox::No | QDialogButtonBox::Cancel);
      if (result == QDialogButtonBox::Yes) {
        WCHAR cwd[MAX_PATH];
        if (!GetCurrentDirectory(MAX_PATH, cwd)) {
          log::error("unable to get current directory (error {})", GetLastError());
          cwd[0] = L'\0';
        }
        if (!Helper::adminLaunch(
          qApp->applicationDirPath().toStdWString(),
          qApp->applicationFilePath().toStdWString(),
          std::wstring(cwd))) {
          log::error("unable to relaunch MO as admin");
          return INVALID_HANDLE_VALUE;
        }
        qApp->exit(0);
        return INVALID_HANDLE_VALUE;
      } else if (result == QDialogButtonBox::Cancel) {
        return INVALID_HANDLE_VALUE;
      }
    }
  }

  while (m_DirectoryUpdate) {
    ::Sleep(100);
    QCoreApplication::processEvents();
  }

  // need to make sure all data is saved before we start the application
  if (m_CurrentProfile != nullptr) {
    m_CurrentProfile->writeModlistNow(true);
  }

  // TODO: should also pass arguments
  if (m_AboutToRun(binary.absoluteFilePath())) {
    try {
      m_USVFS.updateMapping(fileMapping(profileName, customOverwrite));
      m_USVFS.updateForcedLibraries(forcedLibraries);

    } catch (const UsvfsConnectorException &e) {
      log::debug(e.what());
      return INVALID_HANDLE_VALUE;
    } catch (const std::exception &e) {
      QMessageBox::warning(window, tr("Error"), e.what());
      return INVALID_HANDLE_VALUE;
    }

    // Check if the Windows Event Logging service is running.  For some reason, this seems to be
    // critical to the successful running of usvfs.
    if (!checkService()) {
      if (QuestionBoxMemory::query(window, QString("eventLogService"), binary.fileName(),
            tr("Windows Event Log Error"),
            tr("The Windows Event Log service is disabled and/or not running.  This prevents"
              " USVFS from running properly.  Your mods may not be working in the executable"
              " that you are launching.  Note that you may have to restart MO and/or your PC"
              " after the service is fixed.\n\nContinue launching %1?").arg(binary.fileName()),
            QDialogButtonBox::Yes | QDialogButtonBox::No) == QDialogButtonBox::No) {
        return INVALID_HANDLE_VALUE;
      }
    }

    for (auto exec : settings().executablesBlacklist().split(";")) {
      if (exec.compare(binary.fileName(), Qt::CaseInsensitive) == 0) {
        if (QuestionBoxMemory::query(window, QString("blacklistedExecutable"), binary.fileName(),
              tr("Blacklisted Executable"),
              tr("The executable you are attempted to launch is blacklisted in the virtual file"
                 " system.  This will likely prevent the executable, and any executables that are"
                 " launched by this one, from seeing any mods.  This could extend to INI files, save"
                 " games and any other virtualized files.\n\nContinue launching %1?").arg(binary.fileName()),
              QDialogButtonBox::Yes | QDialogButtonBox::No) == QDialogButtonBox::No) {
          return INVALID_HANDLE_VALUE;
        }
      }
    }

    QString modsPath = settings().paths().mods();

    // Check if this a request with either an executable or a working directory under our mods folder
    // then will start the process in a virtualized "environment" with the appropriate paths fixed:
    // (i.e. mods\FNIS\path\exe => game\data\path\exe)
    QString cwdPath = currentDirectory.absolutePath();
    bool virtualizedCwd = cwdPath.startsWith(modsPath, Qt::CaseInsensitive);
    QString binPath = binary.absoluteFilePath();
    bool virtualizedBin = binPath.startsWith(modsPath, Qt::CaseInsensitive);
    if (virtualizedCwd || virtualizedBin) {
      if (virtualizedCwd) {
        int cwdOffset = cwdPath.indexOf('/', modsPath.length() + 1);
        QString adjustedCwd = cwdPath.mid(cwdOffset, -1);
        cwdPath = m_GamePlugin->dataDirectory().absolutePath();
        if (cwdOffset >= 0)
          cwdPath += adjustedCwd;

      }

      if (virtualizedBin) {
        int binOffset = binPath.indexOf('/', modsPath.length() + 1);
        QString adjustedBin = binPath.mid(binOffset, -1);
        binPath = m_GamePlugin->dataDirectory().absolutePath();
        if (binOffset >= 0)
          binPath += adjustedBin;
      }

      QString cmdline
          = QString("launch \"%1\" \"%2\" %3")
                .arg(QDir::toNativeSeparators(cwdPath),
                     QDir::toNativeSeparators(binPath), arguments);

      log::debug("Spawning proxyed process <{}>", cmdline);

      return startBinary(QFileInfo(QCoreApplication::applicationFilePath()),
                         cmdline, QCoreApplication::applicationDirPath(), true);
    } else {
      log::debug("Spawning direct process <{}, {}, {}>", binPath, arguments, cwdPath);
      return startBinary(binary, arguments, currentDirectory, true);
    }
  } else {
    log::debug("start of \"{}\" canceled by plugin", binary.absoluteFilePath());
    return INVALID_HANDLE_VALUE;
  }
}

HANDLE OrganizerCore::runShortcut(const MOShortcut& shortcut)
{
  if (shortcut.hasInstance() && shortcut.instance() != InstanceManager::instance().currentInstance())
    throw std::runtime_error(
      QString("Refusing to run executable from different instance %1:%2")
      .arg(shortcut.instance(),shortcut.executable())
      .toLocal8Bit().constData());

  const Executable& exe = m_ExecutablesList.get(shortcut.executable());

  auto forcedLibaries = m_CurrentProfile->determineForcedLibraries(shortcut.executable());
  if (!m_CurrentProfile->forcedLibrariesEnabled(shortcut.executable())) {
    forcedLibaries.clear();
  }

  return spawnBinaryDirect(
    exe.binaryInfo(), exe.arguments(),
    m_CurrentProfile->name(),
    exe.workingDirectory().length() != 0
    ? exe.workingDirectory()
    : exe.binaryInfo().absolutePath(),
    exe.steamAppID(),
    "",
    forcedLibaries);
}

HANDLE OrganizerCore::startApplication(const QString &executable,
                                       const QStringList &args,
                                       const QString &cwd,
                                       const QString &profile,
                                       const QString &forcedCustomOverwrite,
                                       bool ignoreCustomOverwrite)
{
  QFileInfo binary;
  QString arguments        = args.join(" ");
  QString currentDirectory = cwd;
  QString profileName = profile;
  if (profile.length() == 0) {
    if (m_CurrentProfile != nullptr) {
      profileName = m_CurrentProfile->name();
    } else {
      throw MyException(tr("No profile set"));
    }
  }
  QString steamAppID;
  QString customOverwrite;
  QList<ExecutableForcedLoadSetting> forcedLibraries;
  if (executable.contains('\\') || executable.contains('/')) {
    // file path

    binary = QFileInfo(executable);
    if (binary.isRelative()) {
      // relative path, should be relative to game directory
      binary = QFileInfo(
          managedGame()->gameDirectory().absoluteFilePath(executable));
    }
    if (cwd.length() == 0) {
      currentDirectory = binary.absolutePath();
    }
    try {
      const Executable &exe = m_ExecutablesList.getByBinary(binary);
      steamAppID = exe.steamAppID();
      customOverwrite
          = m_CurrentProfile->setting("custom_overwrites", exe.title())
                .toString();
      if (m_CurrentProfile->forcedLibrariesEnabled(exe.title())) {
        forcedLibraries = m_CurrentProfile->determineForcedLibraries(exe.title());
      }
    } catch (const std::runtime_error &) {
      // nop
    }
  } else {
    // only a file name, search executables list
    try {
      const Executable &exe = m_ExecutablesList.get(executable);
      steamAppID = exe.steamAppID();
      customOverwrite
          = m_CurrentProfile->setting("custom_overwrites", exe.title())
                .toString();
      if (m_CurrentProfile->forcedLibrariesEnabled(exe.title())) {
        forcedLibraries = m_CurrentProfile->determineForcedLibraries(exe.title());
      }
      if (arguments == "") {
        arguments = exe.arguments();
      }
      binary = exe.binaryInfo();
      if (cwd.length() == 0) {
        currentDirectory = exe.workingDirectory();
      }
    } catch (const std::runtime_error &) {
      log::warn("\"{}\" not set up as executable", executable);
      binary = QFileInfo(executable);
    }
  }

  if (!forcedCustomOverwrite.isEmpty())
    customOverwrite = forcedCustomOverwrite;
  if (ignoreCustomOverwrite)
    customOverwrite.clear();

  return spawnBinaryDirect(binary,
                           arguments,
                           profileName,
                           currentDirectory,
                           steamAppID,
                           customOverwrite,
                           forcedLibraries);
}

bool OrganizerCore::waitForApplication(HANDLE handle, LPDWORD exitCode)
{
  if (!Settings::instance().interface().lockGUI())
    return true;

  ILockedWaitingForProcess* uilock = nullptr;
  if (m_UserInterface != nullptr) {
    uilock = m_UserInterface->lock();
  }

  ON_BLOCK_EXIT([&] () {
    if (m_UserInterface != nullptr) {
      m_UserInterface->unlock();
    } });
  return waitForProcessCompletion(handle, exitCode, uilock);
}

bool OrganizerCore::waitForProcessCompletion(HANDLE handle, LPDWORD exitCode, ILockedWaitingForProcess* uilock)
{
  bool originalHandle = true;
  bool newHandle = true;
  bool uiunlocked = false;

  DWORD currentPID = 0;
  QString processName;
  auto waitForChildUntil = GetTickCount64();
  if (handle != INVALID_HANDLE_VALUE) {
    currentPID = GetProcessId(handle);
    processName = QString::fromStdWString(getProcessName(handle));
  }

  // Certain process names we wish to "hide" for aesthetic reason:
  bool waitingOnHidden = false;
  std::vector<QString> hiddenList;
  hiddenList.push_back(QFileInfo(QCoreApplication::applicationFilePath()).fileName());
  for (QString hide : hiddenList)
    if (processName.contains(hide, Qt::CaseInsensitive))
      waitingOnHidden = true;
  // The main reason for adding the hidden list is to hide the MO proxy we use to spawn virtualized processes.
  // On the one hand we want to display the real executable without it feeling laggy, on the other we don't want
  // to requery processes all the time if for some reason we are waiting on hidden processes and find no "unhidden"
  // process. For this reason we use exponential backoff and also start with a delibrately low value to improve
  // the responsiveness of the initial update
  DWORD64 nextHiddenCheck = GetTickCount64();
  DWORD64 nextHiddenCheckDelay = 50;

  constexpr DWORD INPUT_EVENT = WAIT_OBJECT_0 + 1;
  DWORD res = WAIT_TIMEOUT;
  while (handle != INVALID_HANDLE_VALUE && (newHandle || res == WAIT_TIMEOUT || res == INPUT_EVENT))
  {
    if (newHandle) {
      processName += QString(" (%1)").arg(currentPID);
      if (uilock)
        uilock->setProcessName(processName);

      log::debug(
        "Waiting for {} process completion: {}",
        (originalHandle ? "spawned" : "usvfs"), processName);

      newHandle = false;
    }

    // Wait for a an event on the handle, a key press, mouse click or timeout
    res = MsgWaitForMultipleObjects(1, &handle, FALSE, 200, QS_KEY | QS_MOUSEBUTTON);
    if (res == WAIT_FAILED) {
      log::warn("Failed waiting for process completion : MsgWaitForMultipleObjects WAIT_FAILED {}", GetLastError());
      break;
    }

    // keep processing events so the app doesn't appear dead
    QCoreApplication::sendPostedEvents();
    QCoreApplication::processEvents();

    if (uilock && uilock->unlockForced()) {
      uiunlocked = true;
      break;
    }

    if (res == WAIT_OBJECT_0) {
      // process we were waiting on has completed
      if (originalHandle && exitCode && !::GetExitCodeProcess(handle, exitCode))
        log::warn("Failed getting exit code of complete process: {}", GetLastError());
      CloseHandle(handle);
      handle = INVALID_HANDLE_VALUE;
      originalHandle = false;
      // if the previous process spawned a child process and immediately exits we may miss it if we check immediately
      waitForChildUntil = GetTickCount64() + 800;
    }

    // search for another process to wait on if either:
    // 1. we just completed waiting for a process and need to find/wait for an inject child
    // 2. we are currently waiting on a hidden process so periodically check if there is a non-hidden process to wait on
    bool firstIteration = true;
    while ((handle == INVALID_HANDLE_VALUE && GetTickCount64() <= waitForChildUntil)
            || (waitingOnHidden && GetTickCount64() >= nextHiddenCheck))
    {
      if (firstIteration)
        firstIteration = false;
      else {
        QThread::msleep(200);
        QCoreApplication::sendPostedEvents();
        QCoreApplication::processEvents();
      }

      // search if there is another usvfs process active
      handle = findAndOpenAUSVFSProcess(hiddenList, currentPID);
      waitingOnHidden = false;
      newHandle = handle != INVALID_HANDLE_VALUE;
      if (newHandle) {
        currentPID = GetProcessId(handle);
        processName = QString::fromStdWString(getProcessName(handle));
        for (QString hide : hiddenList)
          if (processName.contains(hide, Qt::CaseInsensitive))
            waitingOnHidden = true;
      }
      if (waitingOnHidden) {
        nextHiddenCheck = GetTickCount64() + nextHiddenCheckDelay;
        nextHiddenCheckDelay = std::min(nextHiddenCheckDelay * 2, (DWORD64) 2000);
      }
      else {
        nextHiddenCheck = GetTickCount64();
        nextHiddenCheckDelay = 200;
      }
    }
  }

  if (res == WAIT_OBJECT_0)
    log::debug("Waiting for process completion successfull");
  else if (uiunlocked)
    log::debug("Waiting for process completion aborted by UI");
  else
    log::debug("Waiting for process completion not successfull: {}", res);

  if (handle != INVALID_HANDLE_VALUE)
    ::CloseHandle(handle);

  return res == WAIT_OBJECT_0;
}

HANDLE OrganizerCore::findAndOpenAUSVFSProcess(const std::vector<QString>& hiddenList, DWORD preferedParentPid) {
  // for practical reasons a querySize of 1 is probably enough, we use a larger query as a heuristics
  // to find a more "aesthetic injected processes (attempting to comply to hiddenList and preferedParentPid)
  constexpr size_t querySize = 100;
  DWORD pids[querySize];
  size_t found = querySize;
  if (!::GetVFSProcessList(&found, pids)) {
    log::warn("Failed seeking USVFS processes : GetVFSProcessList failed?!");
    return INVALID_HANDLE_VALUE;
  }

  HANDLE best_match = INVALID_HANDLE_VALUE;
  bool best_match_hidden = true;
  for (size_t i = 0; i < found; ++i) {
    if (pids[i] == GetCurrentProcessId())
      continue; // obviously don't wait for MO process

    HANDLE handle = ::OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE, FALSE, pids[i]);
    if (handle == INVALID_HANDLE_VALUE) {
      log::warn("Failed opening USVFS process {}: OpenProcess failed {}", pids[i], GetLastError());
      continue;
    }

    QString pname = QString::fromStdWString(getProcessName(handle));
    bool phidden = false;
    for (auto hide : hiddenList)
      if (pname.contains(hide, Qt::CaseInsensitive))
        phidden = true;

    bool pprefered = preferedParentPid && getProcessParentID(pids[i]) == preferedParentPid;

    if (best_match == INVALID_HANDLE_VALUE || best_match_hidden || (!phidden && pprefered)) {
      if (best_match != INVALID_HANDLE_VALUE)
        CloseHandle(best_match);
      best_match = handle;
      best_match_hidden = phidden;
    }
    else
      CloseHandle(handle);

    if (!phidden && pprefered)
      return best_match;
  }

  return best_match;
}

bool OrganizerCore::onAboutToRun(
    const std::function<bool(const QString &)> &func)
{
  auto conn = m_AboutToRun.connect(func);
  return conn.connected();
}

bool OrganizerCore::onFinishedRun(
    const std::function<void(const QString &, unsigned int)> &func)
{
  auto conn = m_FinishedRun.connect(func);
  return conn.connected();
}

bool OrganizerCore::onModInstalled(
    const std::function<void(const QString &)> &func)
{
  auto conn = m_ModInstalled.connect(func);
  return conn.connected();
}

void OrganizerCore::refreshModList(bool saveChanges)
{
  // don't lose changes!
  if (saveChanges) {
    m_CurrentProfile->writeModlistNow(true);
  }

  ModInfo::updateFromDisc(
    m_Settings.paths().mods(), &m_DirectoryStructure,
    m_PluginContainer, m_Settings.interface().displayForeign(), managedGame());

  m_CurrentProfile->refreshModStatus();

  m_ModList.notifyChange(-1);

  refreshDirectoryStructure();
}

void OrganizerCore::refreshESPList(bool force)
{
  if (m_DirectoryUpdate) {
    // don't mess up the esp list if we're currently updating the directory
    // structure
    m_PostRefreshTasks.append([=]() {
      this->refreshESPList(force);
    });
    return;
  }
  m_CurrentProfile->writeModlist();

  // clear list
  try {
    m_PluginList.refresh(m_CurrentProfile->name(), *m_DirectoryStructure,
                         m_CurrentProfile->getLockedOrderFileName(), force);
  } catch (const std::exception &e) {
    reportError(tr("Failed to refresh list of esps: %1").arg(e.what()));
  }
}

void OrganizerCore::refreshBSAList()
{
  DataArchives *archives = m_GamePlugin->feature<DataArchives>();

  if (archives != nullptr) {
    m_ArchivesInit = false;

    // default archives are the ones enabled outside MO. if the list can't be
    // found (which might
    // happen if ini files are missing) use hard-coded defaults (preferrably the
    // same the game would use)
    m_DefaultArchives = archives->archives(m_CurrentProfile);
    if (m_DefaultArchives.length() == 0) {
      m_DefaultArchives = archives->vanillaArchives();
    }

    m_ActiveArchives.clear();

    auto iter        = enabledArchives();
    m_ActiveArchives = toStringList(iter.begin(), iter.end());
    if (m_ActiveArchives.isEmpty()) {
      m_ActiveArchives = m_DefaultArchives;
    }

    if (m_UserInterface != nullptr) {
      m_UserInterface->updateBSAList(m_DefaultArchives, m_ActiveArchives);
    }

    m_ArchivesInit = true;
  }
}

void OrganizerCore::refreshLists()
{
  if ((m_CurrentProfile != nullptr) && m_DirectoryStructure->isPopulated()) {
    refreshESPList(true);
    refreshBSAList();
  } // no point in refreshing lists if no files have been added to the directory
    // tree
}

void OrganizerCore::updateModActiveState(int index, bool active)
{
  QList<unsigned int> modsToUpdate;
  modsToUpdate.append(index);
  updateModsActiveState(modsToUpdate, active);
}

void OrganizerCore::updateModsActiveState(const QList<unsigned int> &modIndices, bool active)
{
  int enabled = 0;
  for (auto index : modIndices) {
    ModInfo::Ptr modInfo = ModInfo::getByIndex(index);
    QDir dir(modInfo->absolutePath());
    for (const QString &esm :
      dir.entryList(QStringList() << "*.esm", QDir::Files)) {
      const FileEntry::Ptr file = m_DirectoryStructure->findFile(ToWString(esm));
      if (file.get() == nullptr) {
        log::warn("failed to activate {}", esm);
        continue;
      }

      if (active != m_PluginList.isEnabled(esm)
        && file->getAlternatives().empty()) {
        m_PluginList.blockSignals(true);
        m_PluginList.enableESP(esm, active);
        m_PluginList.blockSignals(false);
      }
    }

    for (const QString &esl :
      dir.entryList(QStringList() << "*.esl", QDir::Files)) {
      const FileEntry::Ptr file = m_DirectoryStructure->findFile(ToWString(esl));
      if (file.get() == nullptr) {
        log::warn("failed to activate {}", esl);
        continue;
      }

      if (active != m_PluginList.isEnabled(esl)
        && file->getAlternatives().empty()) {
        m_PluginList.blockSignals(true);
        m_PluginList.enableESP(esl, active);
        m_PluginList.blockSignals(false);
        ++enabled;
      }
    }
    QStringList esps = dir.entryList(QStringList() << "*.esp", QDir::Files);
    for (const QString &esp : esps) {
      const FileEntry::Ptr file = m_DirectoryStructure->findFile(ToWString(esp));
      if (file.get() == nullptr) {
        log::warn("failed to activate {}", esp);
        continue;
      }

      if (active != m_PluginList.isEnabled(esp)
        && file->getAlternatives().empty()) {
        m_PluginList.blockSignals(true);
        m_PluginList.enableESP(esp, active);
        m_PluginList.blockSignals(false);
        ++enabled;
      }
    }
  }
  if (active && (enabled > 1)) {
    MessageDialog::showMessage(
      tr("Multiple esps/esls activated, please check that they don't conflict."),
      qApp->activeWindow());
  }
  m_PluginList.refreshLoadOrder();
  // immediately save affected lists
  m_PluginListsWriter.writeImmediately(false);
}

void OrganizerCore::updateModInDirectoryStructure(unsigned int index,
                                                  ModInfo::Ptr modInfo)
{
  QMap<unsigned int, ModInfo::Ptr> allModInfo;
  allModInfo[index] = modInfo;
  updateModsInDirectoryStructure(allModInfo);
}

void OrganizerCore::updateModsInDirectoryStructure(QMap<unsigned int, ModInfo::Ptr> modInfo)
{
  for (auto idx : modInfo.keys()) {
    // add files of the bsa to the directory structure
    m_DirectoryRefresher.addModFilesToStructure(
      m_DirectoryStructure, modInfo[idx]->name(),
      m_CurrentProfile->getModPriority(idx), modInfo[idx]->absolutePath(),
      modInfo[idx]->stealFiles());
  }
  DirectoryRefresher::cleanStructure(m_DirectoryStructure);
  // need to refresh plugin list now so we can activate esps
  refreshESPList(true);
  // activate all esps of the specified mod so the bsas get activated along with
  // it
  m_PluginList.blockSignals(true);
  updateModsActiveState(modInfo.keys(), true);
  m_PluginList.blockSignals(false);
  // now we need to refresh the bsa list and save it so there is no confusion
  // about what archives are available and active
  refreshBSAList();
  if (m_UserInterface != nullptr) {
    m_UserInterface->archivesWriter().writeImmediately(false);
  }

  std::vector<QString> archives = enabledArchives();
  m_DirectoryRefresher.setMods(
    m_CurrentProfile->getActiveMods(),
    std::set<QString>(archives.begin(), archives.end()));

  // finally also add files from bsas to the directory structure
  for (auto idx : modInfo.keys()) {
    m_DirectoryRefresher.addModBSAToStructure(
      m_DirectoryStructure, modInfo[idx]->name(),
      m_CurrentProfile->getModPriority(idx), modInfo[idx]->absolutePath(),
      modInfo[idx]->archives());
  }
}

void OrganizerCore::loggedInAction(QWidget* parent, std::function<void ()> f)
{
  if (NexusInterface::instance(m_PluginContainer)->getAccessManager()->validated()) {
    f();
  } else {
    QString apiKey;
    if (settings().nexus().apiKey(apiKey)) {
      doAfterLogin([f]{ f(); });
      NexusInterface::instance(m_PluginContainer)->getAccessManager()->apiCheck(apiKey);
    } else {
      MessageDialog::showMessage(tr("You need to be logged in with Nexus"), parent);
    }
  }
}

void OrganizerCore::requestDownload(const QUrl &url, QNetworkReply *reply)
{
  if (m_PluginContainer != nullptr) {
    for (IPluginModPage *modPage :
         m_PluginContainer->plugins<MOBase::IPluginModPage>()) {
      ModRepositoryFileInfo *fileInfo = new ModRepositoryFileInfo();
      if (modPage->handlesDownload(url, reply->url(), *fileInfo)) {
        fileInfo->repository = modPage->name();
        m_DownloadManager.addDownload(reply, fileInfo);
        return;
      }
    }
  }

  // no mod found that could handle the download. Is it a nexus mod?
  if (url.host() == "www.nexusmods.com") {
    QString gameName = "";
    int modID  = 0;
    int fileID = 0;
    QRegExp nameExp("www\\.nexusmods\\.com/(\\a+)/");
    if (nameExp.indexIn(url.toString()) != -1) {
      gameName = nameExp.cap(1);
    }
    QRegExp modExp("mods/(\\d+)");
    if (modExp.indexIn(url.toString()) != -1) {
      modID = modExp.cap(1).toInt();
    }
    QRegExp fileExp("fid=(\\d+)");
    if (fileExp.indexIn(reply->url().toString()) != -1) {
      fileID = fileExp.cap(1).toInt();
    }
    m_DownloadManager.addDownload(reply,
                                  new ModRepositoryFileInfo(gameName, modID, fileID));
  } else {
    if (QMessageBox::question(qApp->activeWindow(), tr("Download?"),
                              tr("A download has been started but no installed "
                                 "page plugin recognizes it.\n"
                                 "If you download anyway no information (i.e. "
                                 "version) will be associated with the "
                                 "download.\n"
                                 "Continue?"),
                              QMessageBox::Yes | QMessageBox::No)
        == QMessageBox::Yes) {
      m_DownloadManager.addDownload(reply, new ModRepositoryFileInfo());
    }
  }
}

ModListSortProxy *OrganizerCore::createModListProxyModel()
{
  ModListSortProxy *result = new ModListSortProxy(m_CurrentProfile, this);
  result->setSourceModel(&m_ModList);
  return result;
}

PluginListSortProxy *OrganizerCore::createPluginListProxyModel()
{
  PluginListSortProxy *result = new PluginListSortProxy(this);
  result->setSourceModel(&m_PluginList);
  return result;
}

IPluginGame const *OrganizerCore::managedGame() const
{
  return m_GamePlugin;
}

std::vector<QString> OrganizerCore::enabledArchives()
{
  std::vector<QString> result;
  if (m_ArchiveParsing) {
    QFile archiveFile(m_CurrentProfile->getArchivesFileName());
    if (archiveFile.open(QIODevice::ReadOnly)) {
      while (!archiveFile.atEnd()) {
        result.push_back(QString::fromUtf8(archiveFile.readLine()).trimmed());
      }
      archiveFile.close();
    }
  }
  return result;
}

void OrganizerCore::refreshDirectoryStructure()
{
  if (!m_DirectoryUpdate) {
    m_CurrentProfile->writeModlistNow(true);

    m_DirectoryUpdate = true;
    std::vector<std::tuple<QString, QString, int>> activeModList
        = m_CurrentProfile->getActiveMods();
    auto archives = enabledArchives();
    m_DirectoryRefresher.setMods(
        activeModList, std::set<QString>(archives.begin(), archives.end()));

    QTimer::singleShot(0, &m_DirectoryRefresher, SLOT(refresh()));
  }
}

void OrganizerCore::directory_refreshed()
{
  DirectoryEntry *newStructure = m_DirectoryRefresher.getDirectoryStructure();
  Q_ASSERT(newStructure != m_DirectoryStructure);
  if (newStructure != nullptr) {
    std::swap(m_DirectoryStructure, newStructure);
    delete newStructure;
  } else {
    // TODO: don't know why this happens, this slot seems to get called twice
    // with only one emit
    return;
  }
  m_DirectoryUpdate = false;

  for (int i = 0; i < m_ModList.rowCount(); ++i) {
    ModInfo::Ptr modInfo = ModInfo::getByIndex(i);
    modInfo->clearCaches();
  }
  for (auto task : m_PostRefreshTasks) {
    task();
  }
  m_PostRefreshTasks.clear();

  if (m_CurrentProfile != nullptr) {
    refreshLists();
  }
}

void OrganizerCore::profileRefresh()
{
  // have to refresh mods twice (again in refreshModList), otherwise the refresh
  // isn't complete. Not sure why
  ModInfo::updateFromDisc(
    m_Settings.paths().mods(), &m_DirectoryStructure,
    m_PluginContainer, m_Settings.interface().displayForeign(), managedGame());

  m_CurrentProfile->refreshModStatus();

  refreshModList();
}

void OrganizerCore::modStatusChanged(unsigned int index)
{
  try {
    ModInfo::Ptr modInfo = ModInfo::getByIndex(index);
    if (m_CurrentProfile->modEnabled(index)) {
      updateModInDirectoryStructure(index, modInfo);
    } else {
      updateModActiveState(index, false);
      if (m_DirectoryStructure->originExists(ToWString(modInfo->name()))) {
        FilesOrigin &origin
            = m_DirectoryStructure->getOriginByName(ToWString(modInfo->name()));
        origin.enable(false);
      }
      if (m_UserInterface != nullptr) {
        m_UserInterface->archivesWriter().write();
      }
    }
    modInfo->clearCaches();

    for (unsigned int i = 0; i < m_CurrentProfile->numMods(); ++i) {
      ModInfo::Ptr modInfo = ModInfo::getByIndex(i);
      int priority = m_CurrentProfile->getModPriority(i);
      if (m_DirectoryStructure->originExists(ToWString(modInfo->name()))) {
        // priorities in the directory structure are one higher because data is
        // 0
        m_DirectoryStructure->getOriginByName(ToWString(modInfo->name()))
            .setPriority(priority + 1);
      }
    }
    m_DirectoryStructure->getFileRegister()->sortOrigins();

    refreshLists();
  } catch (const std::exception &e) {
    reportError(tr("failed to update mod list: %1").arg(e.what()));
  }
}

void OrganizerCore::modStatusChanged(QList<unsigned int> index) {
  try {
    QMap<unsigned int, ModInfo::Ptr> modsToEnable;
    QMap<unsigned int, ModInfo::Ptr> modsToDisable;
    for (auto idx : index) {
      if (m_CurrentProfile->modEnabled(idx)) {
        modsToEnable[idx] = ModInfo::getByIndex(idx);
      } else {
        modsToDisable[idx] = ModInfo::getByIndex(idx);
      }
    }
    if (!modsToEnable.isEmpty()) {
      updateModsInDirectoryStructure(modsToEnable);
      for (auto modInfo : modsToEnable.values()) {
        modInfo->clearCaches();
      }
    }
    if (!modsToDisable.isEmpty()) {
      updateModsActiveState(modsToDisable.keys(), false);
      for (auto idx : modsToDisable.keys()) {
        if (m_DirectoryStructure->originExists(ToWString(modsToDisable[idx]->name()))) {
          FilesOrigin &origin
            = m_DirectoryStructure->getOriginByName(ToWString(modsToDisable[idx]->name()));
          origin.enable(false);
        }
      }
      if (m_UserInterface != nullptr) {
        m_UserInterface->archivesWriter().write();
      }
    }

    for (unsigned int i = 0; i < m_CurrentProfile->numMods(); ++i) {
      ModInfo::Ptr modInfo = ModInfo::getByIndex(i);
      int priority = m_CurrentProfile->getModPriority(i);
      if (m_DirectoryStructure->originExists(ToWString(modInfo->name()))) {
        // priorities in the directory structure are one higher because data is
        // 0
        m_DirectoryStructure->getOriginByName(ToWString(modInfo->name()))
          .setPriority(priority + 1);
      }
    }
    m_DirectoryStructure->getFileRegister()->sortOrigins();

    refreshLists();
  } catch (const std::exception &e) {
    reportError(tr("failed to update mod list: %1").arg(e.what()));
  }
}

void OrganizerCore::loginSuccessful(bool necessary)
{
  if (necessary) {
    MessageDialog::showMessage(tr("login successful"), qApp->activeWindow());
  }
  for (QString url : m_PendingDownloads) {
    downloadRequestedNXM(url);
  }
  m_PendingDownloads.clear();
  for (auto task : m_PostLoginTasks) {
    task();
  }

  m_PostLoginTasks.clear();
  NexusInterface::instance(m_PluginContainer)->loginCompleted();
}

void OrganizerCore::loginSuccessfulUpdate(bool necessary)
{
  if (necessary) {
    MessageDialog::showMessage(tr("login successful"), qApp->activeWindow());
  }
  m_Updater.startUpdate();
}

void OrganizerCore::loginFailed(const QString &message)
{
  qCritical().nospace().noquote()
    << "Nexus API validation failed: " << message;

  if (QMessageBox::question(qApp->activeWindow(), tr("Login failed"),
                            tr("Login failed, try again?"))
      == QMessageBox::Yes) {
    if (nexusApi(true)) {
      return;
    }
  }

  if (!m_PendingDownloads.isEmpty()) {
    MessageDialog::showMessage(
        tr("login failed: %1. Download will not be associated with an account")
            .arg(message),
        qApp->activeWindow());
    for (QString url : m_PendingDownloads) {
      downloadRequestedNXM(url);
    }
    m_PendingDownloads.clear();
  } else {
    MessageDialog::showMessage(tr("login failed: %1").arg(message),
                               qApp->activeWindow());
    m_PostLoginTasks.clear();
  }
  NexusInterface::instance(m_PluginContainer)->loginCompleted();
}

void OrganizerCore::loginFailedUpdate(const QString &message)
{
  MessageDialog::showMessage(
      tr("login failed: %1. You need to log-in with Nexus to update MO.")
          .arg(message),
      qApp->activeWindow());
}

void OrganizerCore::syncOverwrite()
{
  unsigned int overwriteIndex         = ModInfo::findMod([](ModInfo::Ptr mod) -> bool {
    std::vector<ModInfo::EFlag> flags = mod->getFlags();
    return std::find(flags.begin(), flags.end(), ModInfo::FLAG_OVERWRITE)
           != flags.end();
  });

  ModInfo::Ptr modInfo = ModInfo::getByIndex(overwriteIndex);
  SyncOverwriteDialog syncDialog(modInfo->absolutePath(), m_DirectoryStructure,
                                 qApp->activeWindow());
  if (syncDialog.exec() == QDialog::Accepted) {
    syncDialog.apply(QDir::fromNativeSeparators(m_Settings.paths().mods()));
    modInfo->testValid();
    refreshDirectoryStructure();
  }
}

QString OrganizerCore::oldMO1HookDll() const
{
  if (auto extender = managedGame()->feature<ScriptExtender>()) {
    QString hookdll = QDir::toNativeSeparators(
      managedGame()->dataDirectory().absoluteFilePath(extender->PluginPath() + "/hook.dll"));
    if (QFile(hookdll).exists())
      return hookdll;
  }
  return QString();
}

std::vector<unsigned int> OrganizerCore::activeProblems() const
{
  std::vector<unsigned int> problems;
  const auto& hookdll = oldMO1HookDll();
  if (!hookdll.isEmpty()) {
    // This warning will now be shown every time the problems are checked, which is a bit
    // of a "log spam". But since this is a sever error which will most likely make the
    // game crash/freeze/etc. and is very hard to diagnose,  this "log spam" will make it
    // easier for the user to notice the warning.
    log::warn("hook.dll found in game folder: {}", hookdll);
    problems.push_back(PROBLEM_MO1SCRIPTEXTENDERWORKAROUND);
  }
  return problems;
}

QString OrganizerCore::shortDescription(unsigned int key) const
{
  switch (key) {
    case PROBLEM_MO1SCRIPTEXTENDERWORKAROUND: {
      return tr("MO1 \"Script Extender\" load mechanism has left hook.dll in your game folder");
    } break;
    default: {
      return tr("Description missing");
    } break;
  }
}

QString OrganizerCore::fullDescription(unsigned int key) const
{
  switch (key) {
    case PROBLEM_MO1SCRIPTEXTENDERWORKAROUND: {
      return tr("<a href=\"%1\">hook.dll</a> has been found in your game folder (right click to copy the full path). "
                "This is most likely a leftover of setting the ModOrganizer 1 load mechanism to \"Script Extender\", "
                "in which case you must remove this file either by changing the load mechanism in ModOrganizer 1 or "
                "manually removing the file, otherwise the game is likely to crash and burn.").arg(oldMO1HookDll());
      break;
    }
    default: {
      return tr("Description missing");
    } break;
  }
}

bool OrganizerCore::hasGuidedFix(unsigned int) const
{
  return false;
}

void OrganizerCore::startGuidedFix(unsigned int) const
{
}

bool OrganizerCore::saveCurrentLists()
{
  if (m_DirectoryUpdate) {
    log::warn("not saving lists during directory update");
    return false;
  }

  try {
    savePluginList();
    if (m_UserInterface != nullptr) {
      m_UserInterface->archivesWriter().write();
    }
  } catch (const std::exception &e) {
    reportError(tr("failed to save load order: %1").arg(e.what()));
  }

  return true;
}

void OrganizerCore::savePluginList()
{
  if (m_DirectoryUpdate) {
    // delay save till after directory update
    m_PostRefreshTasks.append([this]() {
      this->savePluginList();
    });
    return;
  }
  m_PluginList.saveTo(m_CurrentProfile->getLockedOrderFileName(),
                      m_CurrentProfile->getDeleterFileName(),
                      m_Settings.game().hideUncheckedPlugins());
  m_PluginList.saveLoadOrder(*m_DirectoryStructure);
}

void OrganizerCore::prepareStart()
{
  if (m_CurrentProfile == nullptr) {
    return;
  }
  m_CurrentProfile->writeModlist();
  m_CurrentProfile->createTweakedIniFile();
  saveCurrentLists();
  m_Settings.game().setupLoadMechanism();
  storeSettings();
}

std::vector<Mapping> OrganizerCore::fileMapping(const QString &profileName,
                                                const QString &customOverwrite)
{
  // need to wait until directory structure
  while (m_DirectoryUpdate) {
    ::Sleep(100);
    QCoreApplication::processEvents();
  }

  IPluginGame *game  = qApp->property("managed_game").value<IPluginGame *>();
  Profile profile(QDir(m_Settings.paths().profiles() + "/" + profileName),
                  game);

  MappingType result;

  QString dataPath
      = QDir::toNativeSeparators(game->dataDirectory().absolutePath());

  bool overwriteActive = false;

  for (auto mod : profile.getActiveMods()) {
    if (std::get<0>(mod).compare("overwrite", Qt::CaseInsensitive) == 0) {
      continue;
    }

    unsigned int modIndex = ModInfo::getIndex(std::get<0>(mod));
    ModInfo::Ptr modPtr   = ModInfo::getByIndex(modIndex);

    bool createTarget = customOverwrite == std::get<0>(mod);

    overwriteActive |= createTarget;

    if (modPtr->isRegular()) {
      result.insert(result.end(), {QDir::toNativeSeparators(std::get<1>(mod)),
                                   dataPath, true, createTarget});
    }
  }

  if (!overwriteActive && !customOverwrite.isEmpty()) {
    throw MyException(tr("The designated write target \"%1\" is not enabled.")
                          .arg(customOverwrite));
  }

  if (m_CurrentProfile->localSavesEnabled()) {
    LocalSavegames *localSaves = game->feature<LocalSavegames>();
    if (localSaves != nullptr) {
      MappingType saveMap
          = localSaves->mappings(currentProfile()->absolutePath() + "/saves");
      result.reserve(result.size() + saveMap.size());
      result.insert(result.end(), saveMap.begin(), saveMap.end());
    } else {
      log::warn("local save games not supported by this game plugin");
    }
  }

  result.insert(result.end(), {
                  QDir::toNativeSeparators(m_Settings.paths().overwrite()),
                  dataPath,
                  true,
                  customOverwrite.isEmpty()
                });

  for (MOBase::IPluginFileMapper *mapper :
       m_PluginContainer->plugins<MOBase::IPluginFileMapper>()) {
    IPlugin *plugin = dynamic_cast<IPlugin *>(mapper);
    if (plugin->isActive()) {
      MappingType pluginMap = mapper->mappings();
      result.reserve(result.size() + pluginMap.size());
      result.insert(result.end(), pluginMap.begin(), pluginMap.end());
    }
  }

  return result;
}


std::vector<Mapping> OrganizerCore::fileMapping(
    const QString &dataPath, const QString &relPath, const DirectoryEntry *base,
    const DirectoryEntry *directoryEntry, int createDestination)
{
  std::vector<Mapping> result;

  for (FileEntry::Ptr current : directoryEntry->getFiles()) {
    bool isArchive = false;
    int origin = current->getOrigin(isArchive);
    if (isArchive || (origin == 0)) {
      continue;
    }

    QString originPath
        = QString::fromStdWString(base->getOriginByID(origin).getPath());
    QString fileName = QString::fromStdWString(current->getName());
//    QString fileName = ToQString(current->getName());
    QString source   = originPath + relPath + fileName;
    QString target   = dataPath + relPath + fileName;
    if (source != target) {
      result.push_back({source, target, false, false});
    }
  }

  // recurse into subdirectories
  std::vector<DirectoryEntry *>::const_iterator current, end;
  directoryEntry->getSubDirectories(current, end);
  for (; current != end; ++current) {
    int origin = (*current)->anyOrigin();

    QString originPath
        = QString::fromStdWString(base->getOriginByID(origin).getPath());
    QString dirName = QString::fromStdWString((*current)->getName());
    QString source  = originPath + relPath + dirName;
    QString target  = dataPath + relPath + dirName;

    bool writeDestination
        = (base == directoryEntry) && (origin == createDestination);

    result.push_back({source, target, true, writeDestination});
    std::vector<Mapping> subRes = fileMapping(
        dataPath, relPath + dirName + "\\", base, *current, createDestination);
    result.insert(result.end(), subRes.begin(), subRes.end());
  }
  return result;
}