summaryrefslogtreecommitdiff
path: root/src/mainwindow.cpp
blob: 5d5a88cec5f1fb735c9f694fc505da0ab39b267c (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
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
/*
Copyright (C) 2012 Sebastian Herbord. All rights reserved.

This file is part of Mod Organizer.

Mod Organizer is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Mod Organizer is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Mod Organizer.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "mainwindow.h"
#include "ui_mainwindow.h"

#include "aboutdialog.h"
#include "browserdialog.h"
#include "categories.h"
#include "categoriesdialog.h"
#include "datatab.h"
#include "downloadlist.h"
#include "downloadstab.h"
#include "editexecutablesdialog.h"
#include "envshortcut.h"
#include "eventfilter.h"
#include "executableinfo.h"
#include "executableslist.h"
#include "filedialogmemory.h"
#include "filterlist.h"
#include "guessedvalue.h"
#include "imodinterface.h"
#include "installationmanager.h"
#include "instancemanager.h"
#include "instancemanagerdialog.h"
#include "iplugindiagnose.h"
#include "iplugingame.h"
#include "isavegame.h"
#include "isavegameinfowidget.h"
#include "listdialog.h"
#include "localsavegames.h"
#include "messagedialog.h"
#include "modlist.h"
#include "modlistcontextmenu.h"
#include "modlistviewactions.h"
#include "motddialog.h"
#include "nexusinterface.h"
#include "nxmaccessmanager.h"
#include "organizercore.h"
#include "overwriteinfodialog.h"
#include "pluginlist.h"
#include "previewdialog.h"
#include "previewgenerator.h"
#include "problemsdialog.h"
#include "profile.h"
#include "profilesdialog.h"
#include "savestab.h"
#include "selectiondialog.h"
#include "serverinfo.h"
#include "settingsdialog.h"
#include "shared/appconfig.h"
#include "spawn.h"
#include "statusbar.h"
#include "systemtraymanager.h"
#include <bsainvalidation.h>
#include <dataarchives.h>
#include <safewritefile.h>
#include <scopeguard.h>
#include <taskprogressmanager.h>
#include <uibase/game_features/savegameinfo.h>
#include <uibase/report.h>
#include <uibase/tutorialmanager.h>
#include <uibase/utility.h>
#include <uibase/versioninfo.h>
#include <usvfs/usvfs.h>

#include "directoryrefresher.h"
#include "shared/directoryentry.h"
#include "shared/fileentry.h"
#include "shared/filesorigin.h"

#include <QAbstractItemDelegate>
#include <QAction>
#include <QApplication>
#include <QBuffer>
#include <QButtonGroup>
#include <QCheckBox>
#include <QClipboard>
#include <QCloseEvent>
#include <QColor>
#include <QColorDialog>
#include <QCoreApplication>
#include <QCursor>
#include <QDebug>
#include <QDesktopServices>
#include <QDialog>
#include <QDialogButtonBox>
#include <QDirIterator>
#include <QDragEnterEvent>
#include <QDropEvent>
#include <QEvent>
#include <QFIleIconProvider>
#include <QFileDialog>
#include <QFont>
#include <QFuture>
#include <QHash>
#include <QIODevice>
#include <QIcon>
#include <QInputDialog>
#include <QItemSelection>
#include <QItemSelectionModel>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonValueRef>
#include <QLineEdit>
#include <QListWidgetItem>
#include <QMenu>
#include <QMessageBox>
#include <QMimeData>
#include <QModelIndex>
#include <QNetworkProxyFactory>
#include <QPainter>
#include <QPixmap>
#include <QPoint>
#include <QProcess>
#include <QProgressDialog>
#include <QPushButton>
#include <QRadioButton>
#include <QRect>
#include <QResizeEvent>
#include <QScopedPointer>
#include <QShortcut>
#include <QSize>
#include <QSizePolicy>
#include <QTime>
#include <QTimer>
#include <QToolButton>
#include <QToolTip>
#include <QTranslator>
#include <QTreeWidget>
#include <QTreeWidgetItemIterator>
#include <QUrl>
#include <QVariantList>
#include <QVersionNumber>
#include <QWebEngineProfile>
#include <QWhatsThis>
#include <QWidgetAction>

#include <QDebug>
#include <QtGlobal>

#ifndef Q_MOC_RUN
#include <boost/algorithm/string.hpp>
#include <boost/assign.hpp>
#include <boost/bind/bind.hpp>
#include <boost/range/adaptor/reversed.hpp>
#include <boost/thread.hpp>
#endif

#include <shlobj.h>

#include <exception>
#include <functional>
#include <limits.h>
#include <map>
#include <regex>
#include <sstream>
#include <stdexcept>
#include <utility>

#include "gameplugins.h"

#ifdef TEST_MODELS
#include "modeltest.h"
#endif  // TEST_MODELS

#pragma warning(disable : 4428)

using namespace MOBase;
using namespace MOShared;

const QSize SmallToolbarSize(24, 24);
const QSize MediumToolbarSize(32, 32);
const QSize LargeToolbarSize(42, 36);

QString UnmanagedModName()
{
  return QObject::tr("<Unmanaged>");
}

bool runLoot(QWidget* parent, OrganizerCore& core, bool didUpdateMasterList);

void setFilterShortcuts(QWidget* widget, QLineEdit* edit)
{
  auto activate = [=] {
    edit->setFocus();
    edit->selectAll();
  };

  auto reset = [=] {
    edit->clear();
    widget->setFocus();
  };

  auto hookActivate = [activate](auto* w) {
    auto* s = new QShortcut(QKeySequence::Find, w);
    s->setAutoRepeat(false);
    s->setContext(Qt::WidgetWithChildrenShortcut);
    QObject::connect(s, &QShortcut::activated, activate);
  };

  auto hookReset = [reset](auto* w) {
    auto* s = new QShortcut(QKeySequence(Qt::Key_Escape), w);
    s->setAutoRepeat(false);
    s->setContext(Qt::WidgetWithChildrenShortcut);
    QObject::connect(s, &QShortcut::activated, reset);
  };

  hookActivate(widget);
  hookReset(widget);

  hookActivate(edit);
  hookReset(edit);
}

MainWindow::MainWindow(Settings& settings, OrganizerCore& organizerCore,
                       PluginContainer& pluginContainer, QWidget* parent)
    : QMainWindow(parent), ui(new Ui::MainWindow), m_WasVisible(false),
      m_FirstPaint(true), m_linksSeparator(nullptr), m_Tutorial(this, "MainWindow"),
      m_OldProfileIndex(-1), m_OldExecutableIndex(-1),
      m_CategoryFactory(CategoryFactory::instance()), m_OrganizerCore(organizerCore),
      m_PluginContainer(pluginContainer),
      m_ArchiveListWriter(std::bind(&MainWindow::saveArchiveList, this)),
      m_LinkToolbar(nullptr), m_LinkDesktop(nullptr), m_LinkStartMenu(nullptr),
      m_SystemTrayManager(nullptr), m_NumberOfProblems(0),
      m_ProblemsCheckRequired(false)
{
  // disables incredibly slow menu fade in effect that looks and feels like crap.
  // this was only happening to users with the windows
  // "Fade or slide menus into view" effect enabled.
  // maybe in the future the effects will be better at this moment they aren't.
  QApplication::setEffectEnabled(Qt::UI_FadeMenu, false);
  QApplication::setEffectEnabled(Qt::UI_AnimateMenu, false);
  QApplication::setEffectEnabled(Qt::UI_AnimateCombo, false);
  QApplication::setEffectEnabled(Qt::UI_AnimateTooltip, false);
  QApplication::setEffectEnabled(Qt::UI_FadeTooltip, false);

  QWebEngineProfile::defaultProfile()->setPersistentCookiesPolicy(
      QWebEngineProfile::NoPersistentCookies);
  QWebEngineProfile::defaultProfile()->setHttpCacheMaximumSize(52428800);
  QWebEngineProfile::defaultProfile()->setCachePath(settings.paths().cache());
  QWebEngineProfile::defaultProfile()->setPersistentStoragePath(
      settings.paths().cache());

  // qt resets the thread name somewhere within the QWebEngineProfile calls
  // above
  MOShared::SetThisThreadName("main");

  ui->setupUi(this);
  languageChange(settings.interface().language());
  ui->statusBar->setup(ui, settings);

  m_SystemTrayManager = new SystemTrayManager(this, ui->logDock);

  {
    auto& ni = NexusInterface::instance();

    // there are two ways to get here:
    //  1) the user just started MO, and
    //  2) the user has changed some setting that required a restart
    //
    // "restarting" MO doesn't actually re-execute the binary, it just basically
    // executes most of main() again, so a bunch of things are actually not
    // reset
    //
    // one of these things is the api status, which will have fired its events
    // long before the execution gets here because stuff is still cached and no
    // real request to nexus is actually done
    //
    // therefore, when the user starts MO normally, the user account and stats
    // will be empty (which is fine) and populated later on when the api key
    // check has finished
    //
    // in the rare case where the user restarts MO through the settings, this
    // will correctly pick up the previous values
    updateWindowTitle(ni.getAPIUserAccount());
    ui->statusBar->setAPI(ni.getAPIStats(), ni.getAPIUserAccount());
  }

  m_CategoryFactory.loadCategories();

  ui->logList->setCore(m_OrganizerCore);

  setupToolbar();
  toggleMO2EndorseState();
  toggleUpdateAction();

  TaskProgressManager::instance().tryCreateTaskbar();

  setupModList();
  ui->espList->setup(m_OrganizerCore, this, ui);
  ui->bsaList->setLocalMoveOnly(true);
  ui->bsaList->setHeaderHidden(true);

  const bool pluginListAdjusted =
      settings.geometry().restoreState(ui->espList->header());

  // data tab
  m_DataTab.reset(new DataTab(m_OrganizerCore, m_PluginContainer, this, ui));
  m_DataTab->restoreState(settings);

  connect(m_DataTab.get(), &DataTab::executablesChanged, [&] {
    refreshExecutablesList();
  });

  connect(m_DataTab.get(), &DataTab::originModified, [&](int id) {
    originModified(id);
  });

  connect(m_DataTab.get(), &DataTab::displayModInformation,
          [&](auto&& m, auto&& i, auto&& tab) {
            displayModInformation(m, i, tab);
          });

  // downloads tab
  m_DownloadsTab.reset(new DownloadsTab(m_OrganizerCore, ui));

  // saves tab
  m_SavesTab.reset(new SavesTab(this, m_OrganizerCore, ui));

  // Hide stuff we do not need:
  auto& features = m_OrganizerCore.gameFeatures();
  if (!features.gameFeature<GamePlugins>()) {
    ui->tabWidget->removeTab(ui->tabWidget->indexOf(ui->espTab));
  }
  if (!features.gameFeature<DataArchives>()) {
    ui->tabWidget->removeTab(ui->tabWidget->indexOf(ui->bsaTab));
  }

  settings.geometry().restoreState(ui->downloadView->header());
  settings.geometry().restoreState(ui->savegameList->header());

  ui->splitter->setStretchFactor(0, 3);
  ui->splitter->setStretchFactor(1, 2);

  resizeLists(pluginListAdjusted);

  QMenu* linkMenu = new QMenu(this);
  m_LinkToolbar   = linkMenu->addAction(QIcon(":/MO/gui/link"), tr("Toolbar and Menu"),
                                        this, SLOT(linkToolbar()));
  m_LinkDesktop   = linkMenu->addAction(QIcon(":/MO/gui/link"), tr("Desktop"), this,
                                        SLOT(linkDesktop()));
  m_LinkStartMenu = linkMenu->addAction(QIcon(":/MO/gui/link"), tr("Start Menu"), this,
                                        SLOT(linkMenu()));
  ui->linkButton->setMenu(linkMenu);

  ui->listOptionsBtn->setMenu(
      new ModListGlobalContextMenu(m_OrganizerCore, ui->modList, this));

  ui->openFolderMenu->setMenu(openFolderMenu());

  // don't allow mouse wheel to switch grouping, too many people accidentally
  // turn on grouping and then don't understand what happened
  EventFilter* noWheel = new EventFilter(this, [](QObject*, QEvent* event) -> bool {
    return event->type() == QEvent::Wheel;
  });

  ui->groupCombo->installEventFilter(noWheel);
  ui->profileBox->installEventFilter(noWheel);

  updateSortButton();

  connect(&m_PluginContainer, SIGNAL(diagnosisUpdate()), this,
          SLOT(scheduleCheckForProblems()));

  connect(&m_OrganizerCore, &OrganizerCore::directoryStructureReady, this,
          &MainWindow::onDirectoryStructureChanged);
  connect(m_OrganizerCore.directoryRefresher(),
          SIGNAL(progress(const DirectoryRefreshProgress*)), this,
          SLOT(refresherProgress(const DirectoryRefreshProgress*)));
  connect(m_OrganizerCore.directoryRefresher(), SIGNAL(error(QString)), this,
          SLOT(showError(QString)));

  connect(&m_OrganizerCore.settings(), SIGNAL(languageChanged(QString)), this,
          SLOT(languageChange(QString)));
  connect(&m_OrganizerCore.settings(), SIGNAL(styleChanged(QString)), this,
          SIGNAL(styleChanged(QString)));

  connect(m_OrganizerCore.updater(), SIGNAL(restart()), this, SLOT(close()));
  connect(m_OrganizerCore.updater(), SIGNAL(updateAvailable()), this,
          SLOT(updateAvailable()));
  connect(m_OrganizerCore.updater(), SIGNAL(motdAvailable(QString)), this,
          SLOT(motdReceived(QString)));
  connect(&m_OrganizerCore, &OrganizerCore::refreshTriggered, this, [this]() {
    updateSortButton();
  });

  connect(&NexusInterface::instance(), SIGNAL(requestNXMDownload(QString)),
          &m_OrganizerCore, SLOT(downloadRequestedNXM(QString)));
  connect(&NexusInterface::instance(),
          SIGNAL(nxmDownloadURLsAvailable(QString, int, int, QVariant, QVariant, int)),
          this, SLOT(nxmDownloadURLs(QString, int, int, QVariant, QVariant, int)));
  connect(&NexusInterface::instance(), SIGNAL(needLogin()), &m_OrganizerCore,
          SLOT(nexusApi()));

  connect(NexusInterface::instance().getAccessManager(),
          &NXMAccessManager::credentialsReceived, this, &MainWindow::updateWindowTitle);
  connect(&NexusInterface::instance(), &NexusInterface::requestsChanged, ui->statusBar,
          &StatusBar::setAPI);

  connect(&TutorialManager::instance(), SIGNAL(windowTutorialFinished(QString)), this,
          SLOT(windowTutorialFinished(QString)));
  connect(ui->tabWidget, SIGNAL(currentChanged(int)), &TutorialManager::instance(),
          SIGNAL(tabChanged(int)));
  connect(ui->toolBar, SIGNAL(customContextMenuRequested(QPoint)), this,
          SLOT(toolBar_customContextMenuRequested(QPoint)));
  connect(ui->menuToolbars, &QMenu::aboutToShow, [&] {
    updateToolbarMenu();
  });
  connect(ui->menuView, &QMenu::aboutToShow, [&] {
    updateViewMenu();
  });
  connect(ui->actionTool->menu(), &QMenu::aboutToShow, [&] {
    updateToolMenu();
  });
  connect(&m_PluginContainer, &PluginContainer::pluginEnabled, this,
          [this](IPlugin* plugin) {
            if (m_PluginContainer.implementInterface<IPluginModPage>(plugin)) {
              updateModPageMenu();
            }
          });
  connect(&m_PluginContainer, &PluginContainer::pluginDisabled, this,
          [this](IPlugin* plugin) {
            if (m_PluginContainer.implementInterface<IPluginModPage>(plugin)) {
              updateModPageMenu();
            }
          });
  connect(&m_PluginContainer, &PluginContainer::pluginRegistered, this,
          &MainWindow::onPluginRegistrationChanged);
  connect(&m_PluginContainer, &PluginContainer::pluginUnregistered, this,
          &MainWindow::onPluginRegistrationChanged);

  connect(&m_OrganizerCore, &OrganizerCore::modInstalled, this,
          &MainWindow::modInstalled);

  connect(&m_CategoryFactory, SIGNAL(nexusCategoryRefresh(CategoriesDialog*)), this,
          SLOT(refreshNexusCategories(CategoriesDialog*)));
  connect(&m_CategoryFactory, SIGNAL(categoriesSaved()), this, SLOT(categoriesSaved()));

  m_CheckBSATimer.setSingleShot(true);
  connect(&m_CheckBSATimer, SIGNAL(timeout()), this, SLOT(checkBSAList()));

  setFilterShortcuts(ui->modList, ui->modFilterEdit);
  setFilterShortcuts(ui->espList, ui->espFilterEdit);
  setFilterShortcuts(ui->downloadView, ui->downloadFilterEdit);

  m_UpdateProblemsTimer.setSingleShot(true);
  connect(&m_UpdateProblemsTimer, &QTimer::timeout, this,
          &MainWindow::checkForProblemsAsync);
  connect(this, &MainWindow::checkForProblemsDone, this,
          &MainWindow::updateProblemsButton, Qt::ConnectionType::QueuedConnection);

  m_SaveMetaTimer.setSingleShot(false);
  connect(&m_SaveMetaTimer, SIGNAL(timeout()), this, SLOT(saveModMetas()));
  m_SaveMetaTimer.start(5000);

  FileDialogMemory::restore(settings);

  fixCategories();

  m_StartTime = QTime::currentTime();

  m_Tutorial.expose("modList", m_OrganizerCore.modList());
  m_Tutorial.expose("espList", m_OrganizerCore.pluginList());

  m_OrganizerCore.setUserInterface(this);
  m_OrganizerCore.onFinishedRun([=](const QString, unsigned int) {
    if (isHidden()) {
      m_SystemTrayManager->restoreFromSystemTray();
    }
  });

  connect(m_OrganizerCore.modList(), &ModList::showMessage, [=](auto&& message) {
    showMessage(message);
  });
  connect(m_OrganizerCore.modList(), &ModList::modRenamed,
          [=](auto&& oldName, auto&& newName) {
            modRenamed(oldName, newName);
          });
  connect(m_OrganizerCore.modList(), &ModList::modUninstalled, [=](auto&& name) {
    modRemoved(name);
  });
  connect(m_OrganizerCore.modList(), &ModList::fileMoved, [=](auto&&... args) {
    fileMoved(args...);
  });
  connect(m_OrganizerCore.installationManager(), &InstallationManager::modReplaced,
          [=](auto&& name) {
            modRemoved(name);
          });
  connect(m_OrganizerCore.downloadManager(), &DownloadManager::showMessage,
          [=](auto&& message) {
            showMessage(message);
          });
  for (const QString& fileName : m_PluginContainer.pluginFileNames()) {
    installTranslator(QFileInfo(fileName).baseName());
  }

  updateModPageMenu();

  // refresh profiles so the current profile can be activated
  refreshProfiles(false);

  ui->profileBox->setCurrentText(m_OrganizerCore.currentProfile()->name());

  if (settings.archiveParsing()) {
    ui->dataTabShowFromArchives->setCheckState(Qt::Checked);
    ui->dataTabShowFromArchives->setEnabled(true);
  } else {
    ui->dataTabShowFromArchives->setCheckState(Qt::Unchecked);
    ui->dataTabShowFromArchives->setEnabled(false);
  }

  QApplication::instance()->installEventFilter(this);

  scheduleCheckForProblems();
  refreshExecutablesList();
  updatePinnedExecutables();
  resetActionIcons();
  processUpdates();

  ui->modList->updateModCount();
  ui->espList->updatePluginCount();
  ui->statusBar->updateNormalMessage(m_OrganizerCore);
}

void MainWindow::setupModList()
{
  ui->modList->setup(m_OrganizerCore, m_CategoryFactory, this, ui);

  connect(&ui->modList->actions(), &ModListViewActions::overwriteCleared, [=]() {
    scheduleCheckForProblems();
  });
  connect(&ui->modList->actions(), &ModListViewActions::originModified, this,
          &MainWindow::originModified);
  connect(&ui->modList->actions(), &ModListViewActions::modInfoDisplayed, this,
          &MainWindow::modInfoDisplayed);

  connect(m_OrganizerCore.modList(), &ModList::modPrioritiesChanged, [&]() {
    m_ArchiveListWriter.write();
  });
}

void MainWindow::resetActionIcons()
{
  // this is a bit of a hack
  //
  // the .qss files have historically set qproperty-icon by id and these ids
  // correspond to the QActions created in the .ui file
  //
  // the problem is that QActions do not support having their icon property
  // set from a .qss because they're not widgets (they don't inherit from
  // QWidget), and styling only works on widget
  //
  // a QAction _does_ have an associated icon, it just can't be set from a .qss
  // file
  //
  // so here, a dummy QToolButton widget is created for each QAction and is
  // given the same name as the action, which makes it pick up the icon
  // specified in the .qss file
  //
  // that icon is then given to the widget used by the QAction (if it's some
  // sort of button, which typically happens on the toolbar) _and_ to the
  // QAction itself, which is used in the menu bar

  // clearing the notification, will be set below if the stylesheet has set
  // anything for it
  m_originalNotificationIcon = {};

  // QActions created from the .ui file are children of the main window
  for (QAction* action : findChildren<QAction*>()) {
    // creating a dummy button
    auto dummy = std::make_unique<QToolButton>();

    // reusing the action name
    dummy->setObjectName(action->objectName());

    // styling the button, this has to be done manually because the button is
    // never added anywhere
    style()->polish(dummy.get());

    // the button's icon may be null if it wasn't specified in the .qss file,
    // which can happen if the stylesheet just doesn't override icons, or for
    // other actions like the pinned custom executables
    const auto icon = dummy->icon();
    if (icon.isNull()) {
      continue;
    }

    // button associated with the action on the toolbar
    QWidget* actionWidget = ui->toolBar->widgetForAction(action);

    if (auto* actionButton = dynamic_cast<QAbstractButton*>(actionWidget)) {
      actionButton->setIcon(icon);
    }

    // the action's icon is used by the menu bar
    action->setIcon(icon);

    if (action == ui->actionNotifications) {
      // if the stylesheet has set a notification icon, remember it here so it
      // can be used in updateProblemsButton()
      m_originalNotificationIcon = icon;
    }
  }

  // update the button for the potentially new icon
  updateProblemsButton();
}

MainWindow::~MainWindow()
{
  try {
    cleanup();

    m_OrganizerCore.setUserInterface(nullptr);

    if (m_IntegratedBrowser) {
      m_IntegratedBrowser->close();
      m_IntegratedBrowser.reset();
    }

    delete ui;
  } catch (std::exception& e) {
    QMessageBox::critical(
        nullptr, tr("Crash on exit"),
        tr("MO crashed while exiting.  Some settings may not be saved.\n\nError: %1")
            .arg(e.what()),
        QMessageBox::Ok);
  }
}

void MainWindow::updateWindowTitle(const APIUserAccount& user)
{
  //"\xe2\x80\x93" is an "em dash", a longer "-"
  QString title =
      QString("%1 \xe2\x80\x93 Mod Organizer v%2")
          .arg(m_OrganizerCore.managedGame()->displayGameName(),
               m_OrganizerCore.getVersion().string(Version::FormatCondensed));

  if (!user.name().isEmpty()) {
    const QString premium = (user.type() == APIUserAccountTypes::Premium ? "*" : "");
    title.append(QString(" (%1%2)").arg(user.name(), premium));
  }

  this->setWindowTitle(title);
}

void MainWindow::resizeLists(bool pluginListCustom)
{
  // ensure the columns aren't so small you can't see them any more
  for (int i = 0; i < ui->modList->header()->count(); ++i) {
    if (ui->modList->header()->sectionSize(i) < 10) {
      ui->modList->header()->resizeSection(i, 10);
    }
  }

  if (!pluginListCustom) {
    // resize plugin list to fit content
    for (int i = 0; i < ui->espList->header()->count(); ++i) {
      ui->espList->header()->setSectionResizeMode(i, QHeaderView::ResizeToContents);
    }
    ui->espList->header()->setSectionResizeMode(0, QHeaderView::Stretch);
  }
}

void MainWindow::allowListResize()
{
  // allow resize on mod list
  for (int i = 0; i < ui->modList->header()->count(); ++i) {
    ui->modList->header()->setSectionResizeMode(i, QHeaderView::Interactive);
  }
  ui->modList->header()->setStretchLastSection(true);

  // allow resize on plugin list
  for (int i = 0; i < ui->espList->header()->count(); ++i) {
    ui->espList->header()->setSectionResizeMode(i, QHeaderView::Interactive);
  }
  ui->espList->header()->setStretchLastSection(true);
}

void MainWindow::updateStyle(const QString&)
{
  resetActionIcons();
}

void MainWindow::resizeEvent(QResizeEvent* event)
{
  m_Tutorial.resize(event->size());
  QMainWindow::resizeEvent(event);
}

void MainWindow::setupToolbar()
{
  setupActionMenu(ui->actionModPage);
  setupActionMenu(ui->actionTool);
  setupActionMenu(ui->actionHelp);
  setupActionMenu(ui->actionEndorseMO);

  createHelpMenu();
  createEndorseMenu();

  // find last separator, add a spacer just before it so the icons are
  // right-aligned
  m_linksSeparator = nullptr;
  for (auto* a : ui->toolBar->actions()) {
    if (a->isSeparator()) {
      m_linksSeparator = a;
    }
  }

  if (m_linksSeparator) {
    auto* spacer = new QWidget(ui->toolBar);
    spacer->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred);
    ui->toolBar->insertWidget(m_linksSeparator, spacer);

  } else {
    log::warn("no separator found on the toolbar, icons won't be right-aligned");
  }

  if (!InstanceManager::singleton().allowedToChangeInstance()) {
    ui->actionChange_Game->setVisible(false);
  }
}

void MainWindow::setupActionMenu(QAction* a)
{
  a->setMenu(new QMenu(this));

  auto* w = ui->toolBar->widgetForAction(a);
  if (auto* tb = dynamic_cast<QToolButton*>(w))
    tb->setPopupMode(QToolButton::InstantPopup);
}

void MainWindow::updatePinnedExecutables()
{
  for (auto* a : ui->toolBar->actions()) {
    if (a->objectName().startsWith("custom__")) {
      ui->toolBar->removeAction(a);
      a->deleteLater();
    }
  }

  ui->menuRun->clear();

  bool hasLinks = false;

  for (const auto& exe : *m_OrganizerCore.executablesList()) {
    if (!exe.hide() && exe.isShownOnToolbar()) {
      hasLinks = true;

      QAction* exeAction =
          new QAction(iconForExecutable(exe.binaryInfo().filePath()), exe.title());

      exeAction->setObjectName(QString("custom__") + exe.title());
      exeAction->setStatusTip(exe.binaryInfo().filePath());

      if (!connect(exeAction, SIGNAL(triggered()), this, SLOT(startExeAction()))) {
        log::debug("failed to connect trigger?");
      }

      if (m_linksSeparator) {
        ui->toolBar->insertAction(m_linksSeparator, exeAction);
      } else {
        // separator wasn't found, add it to the end
        ui->toolBar->addAction(exeAction);
      }

      ui->menuRun->addAction(exeAction);
    }
  }

  // don't show the menu if there are no links
  ui->menuRun->menuAction()->setVisible(hasLinks);
}

void MainWindow::updateToolbarMenu()
{
  ui->actionMainMenuToggle->setChecked(ui->menuBar->isVisible());
  ui->actionToolBarMainToggle->setChecked(ui->toolBar->isVisible());
  ui->actionStatusBarToggle->setChecked(ui->statusBar->isVisible());

  ui->actionToolBarSmallIcons->setChecked(ui->toolBar->iconSize() == SmallToolbarSize);
  ui->actionToolBarMediumIcons->setChecked(ui->toolBar->iconSize() ==
                                           MediumToolbarSize);
  ui->actionToolBarLargeIcons->setChecked(ui->toolBar->iconSize() == LargeToolbarSize);

  ui->actionToolBarIconsOnly->setChecked(ui->toolBar->toolButtonStyle() ==
                                         Qt::ToolButtonIconOnly);
  ui->actionToolBarTextOnly->setChecked(ui->toolBar->toolButtonStyle() ==
                                        Qt::ToolButtonTextOnly);
  ui->actionToolBarIconsAndText->setChecked(ui->toolBar->toolButtonStyle() ==
                                            Qt::ToolButtonTextUnderIcon);
}

void MainWindow::updateViewMenu()
{
  ui->actionViewLog->setChecked(ui->logDock->isVisible());
}

QMenu* MainWindow::createPopupMenu()
{
  auto* m = new QMenu;

  // add all the actions from the toolbars menu
  for (auto* a : ui->menuToolbars->actions()) {
    m->addAction(a);
  }

  m->addSeparator();

  // other actions
  m->addAction(ui->actionViewLog);

  // make sure the actions are updated
  updateToolbarMenu();
  updateViewMenu();

  return m;
}

void MainWindow::on_actionMainMenuToggle_triggered()
{
  ui->menuBar->setVisible(!ui->menuBar->isVisible());
}

void MainWindow::on_actionToolBarMainToggle_triggered()
{
  ui->toolBar->setVisible(!ui->toolBar->isVisible());
}

void MainWindow::on_actionStatusBarToggle_triggered()
{
  ui->statusBar->setVisible(!ui->statusBar->isVisible());
}

void MainWindow::on_actionToolBarSmallIcons_triggered()
{
  setToolbarSize(SmallToolbarSize);
}

void MainWindow::on_actionToolBarMediumIcons_triggered()
{
  setToolbarSize(MediumToolbarSize);
}

void MainWindow::on_actionToolBarLargeIcons_triggered()
{
  setToolbarSize(LargeToolbarSize);
}

void MainWindow::on_actionToolBarIconsOnly_triggered()
{
  setToolbarButtonStyle(Qt::ToolButtonIconOnly);
}

void MainWindow::on_actionToolBarTextOnly_triggered()
{
  setToolbarButtonStyle(Qt::ToolButtonTextOnly);
}

void MainWindow::on_actionToolBarIconsAndText_triggered()
{
  setToolbarButtonStyle(Qt::ToolButtonTextUnderIcon);
}

void MainWindow::on_actionViewLog_triggered()
{
  ui->logDock->setVisible(!ui->logDock->isVisible());
}

void MainWindow::setToolbarSize(const QSize& s)
{
  for (auto* tb : findChildren<QToolBar*>()) {
    tb->setIconSize(s);
  }
}

void MainWindow::setToolbarButtonStyle(Qt::ToolButtonStyle s)
{
  for (auto* tb : findChildren<QToolBar*>()) {
    tb->setToolButtonStyle(s);
  }
}

void MainWindow::on_centralWidget_customContextMenuRequested(const QPoint& pos)
{
  // this allows for getting the context menu even if both the menubar and all
  // the toolbars are hidden; an alternative is the Alt key handled in
  // keyPressEvent() below

  // the custom context menu event bubbles up to here if widgets don't actually
  // process this, which would show the menu when right-clicking button, labels,
  // etc.
  //
  // only show the context menu when right-clicking on the central widget
  // itself, which is basically just the outer edges of the main window
  auto* w = childAt(pos);
  if (w != ui->centralWidget) {
    return;
  }

  createPopupMenu()->exec(ui->centralWidget->mapToGlobal(pos));
}

void MainWindow::scheduleCheckForProblems()
{
  if (!m_UpdateProblemsTimer.isActive()) {
    m_UpdateProblemsTimer.start(500);
  }
}

void MainWindow::updateProblemsButton()
{
  // if the current stylesheet doesn't provide an icon, this is used instead
  const char* DefaultIconName = ":/MO/gui/warning";

  const std::size_t numProblems = m_NumberOfProblems;

  // original icon without a count painted on it
  const QIcon original = m_originalNotificationIcon.isNull()
                             ? QIcon(DefaultIconName)
                             : m_originalNotificationIcon;

  // final icon
  QIcon final;

  if (numProblems > 0) {
    ui->actionNotifications->setToolTip(tr("There are notifications to read"));

    // will contain the original icon, plus a notification count; this also
    // makes sure the pixmap is exactly 64x64 by requesting the icon that's
    // as close to 64x64 as possible, and then scaling it up if it's too small
    QPixmap merged = original.pixmap(64, 64).scaled(64, 64);

    {
      QPainter painter(&merged);

      const std::string badgeName =
          std::string(":/MO/gui/badge_") +
          (numProblems < 10 ? std::to_string(static_cast<long long>(numProblems))
                            : "more");

      painter.drawPixmap(32, 32, 32, 32, QPixmap(badgeName.c_str()));
    }

    final = QIcon(merged);
  } else {
    ui->actionNotifications->setToolTip(tr("There are no notifications"));

    // no change
    final = original;
  }

  ui->actionNotifications->setEnabled(numProblems > 0);

  // setting the icon on the action (shown on the menu)
  ui->actionNotifications->setIcon(final);

  // setting the icon on the toolbar button
  if (auto* actionWidget = ui->toolBar->widgetForAction(ui->actionNotifications)) {
    if (auto* button = dynamic_cast<QAbstractButton*>(actionWidget)) {
      button->setIcon(final);
    }
  }

  // updating the status bar, may be null very early when MO is starting
  if (ui->statusBar) {
    ui->statusBar->setNotifications(numProblems > 0);
  }
}

bool MainWindow::errorReported(QString& logFile)
{
  QDir dir(qApp->property("dataPath").toString() + "/" +
           QString::fromStdWString(AppConfig::logPath()));
  QFileInfoList files =
      dir.entryInfoList(QStringList("ModOrganizer_??_??_??_??_??.log"), QDir::Files,
                        QDir::Name | QDir::Reversed);

  if (files.count() > 0) {
    logFile = files.at(0).absoluteFilePath();
    QFile file(logFile);
    if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
      char buffer[1024];
      int line = 0;
      while (!file.atEnd()) {
        file.readLine(buffer, 1024);
        if (strncmp(buffer, "ERROR", 5) == 0) {
          return true;
        }

        // prevent this function from taking forever
        if (line++ >= 50000) {
          break;
        }
      }
    }
  }

  return false;
}

QFuture<void> MainWindow::checkForProblemsAsync()
{
  return QtConcurrent::run([this]() {
    checkForProblemsImpl();
  });
}

void MainWindow::checkForProblemsImpl()
{
  m_ProblemsCheckRequired = true;

  std::scoped_lock lk(m_CheckForProblemsMutex);

  // another thread might already have checked while this one was waiting on the lock
  if (m_ProblemsCheckRequired) {
    m_ProblemsCheckRequired = false;
    TimeThis tt("MainWindow::checkForProblemsImpl()");
    size_t numProblems = 0;
    for (QObject* pluginObj : m_PluginContainer.plugins<QObject>()) {
      IPlugin* plugin = qobject_cast<IPlugin*>(pluginObj);
      if (plugin == nullptr || m_PluginContainer.isEnabled(plugin)) {
        IPluginDiagnose* diagnose = qobject_cast<IPluginDiagnose*>(pluginObj);
        if (diagnose != nullptr)
          numProblems += diagnose->activeProblems().size();
      }
    }
    m_NumberOfProblems = numProblems;
    emit checkForProblemsDone();
  }
}

void MainWindow::about()
{
  AboutDialog(m_OrganizerCore.getVersion().string(Version::FormatCondensed), this)
      .exec();
}

void MainWindow::createEndorseMenu()
{
  auto* menu = ui->actionEndorseMO->menu();
  if (!menu) {
    // shouldn't happen
    return;
  }

  menu->clear();

  QAction* endorseAction = new QAction(tr("Endorse"), menu);
  connect(endorseAction, SIGNAL(triggered()), this, SLOT(actionEndorseMO()));
  menu->addAction(endorseAction);

  QAction* wontEndorseAction = new QAction(tr("Won't Endorse"), menu);
  connect(wontEndorseAction, SIGNAL(triggered()), this, SLOT(actionWontEndorseMO()));
  menu->addAction(wontEndorseAction);
}

void MainWindow::createHelpMenu()
{
  //: Translation strings for tutorial names
  static std::map<QString, const char*> translate = {
      {"First Steps", QT_TR_NOOP("First Steps")},
      {"Conflict Resolution", QT_TR_NOOP("Conflict Resolution")},
      {"Overview", QT_TR_NOOP("Overview")}};

  auto* menu = ui->actionHelp->menu();
  if (!menu) {
    // this happens on startup because languageChanged() (which calls this) is
    // called before the menus are actually created
    return;
  }

  menu->clear();

  QAction* helpAction = new QAction(tr("Help on UI"), menu);
  connect(helpAction, SIGNAL(triggered()), this, SLOT(helpTriggered()));
  menu->addAction(helpAction);

  QAction* wikiAction = new QAction(tr("Documentation"), menu);
  connect(wikiAction, SIGNAL(triggered()), this, SLOT(wikiTriggered()));
  menu->addAction(wikiAction);

  if (!m_OrganizerCore.managedGame()->getSupportURL().isEmpty()) {
    QAction* gameSupportAction = new QAction(tr("Game Support Wiki"), menu);
    connect(gameSupportAction, SIGNAL(triggered()), this, SLOT(gameSupportTriggered()));
    menu->addAction(gameSupportAction);
  }

  QAction* discordAction = new QAction(tr("Chat on Discord"), menu);
  connect(discordAction, SIGNAL(triggered()), this, SLOT(discordTriggered()));
  menu->addAction(discordAction);

  QAction* issueAction = new QAction(tr("Report Issue"), menu);
  connect(issueAction, SIGNAL(triggered()), this, SLOT(issueTriggered()));
  menu->addAction(issueAction);

  QMenu* tutorialMenu = new QMenu(tr("Tutorials"), menu);

  typedef std::vector<std::pair<int, QAction*>> ActionList;

  ActionList tutorials;

  QDirIterator dirIter(QApplication::applicationDirPath() + "/tutorials",
                       QStringList("*.js"), QDir::Files);
  while (dirIter.hasNext()) {
    dirIter.next();
    QString fileName = dirIter.fileName();

    QFile file(dirIter.filePath());
    if (!file.open(QIODevice::ReadOnly)) {
      log::error("Failed to open {}", fileName);
      continue;
    }
    QString firstLine = QString::fromUtf8(file.readLine());
    if (firstLine.startsWith("//TL")) {
      QStringList params = firstLine.mid(4).trimmed().split('#');
      if (params.size() != 2) {
        log::error("invalid header line for tutorial {}, expected 2 parameters",
                   fileName);
        continue;
      }
      QAction* tutAction = new QAction(tr(translate[params.at(0)]), tutorialMenu);
      tutAction->setData(fileName);
      tutorials.push_back(std::make_pair(params.at(1).toInt(), tutAction));
    }
  }

  std::sort(tutorials.begin(), tutorials.end(),
            [](const ActionList::value_type& LHS, const ActionList::value_type& RHS) {
              return LHS.first < RHS.first;
            });

  for (auto iter = tutorials.begin(); iter != tutorials.end(); ++iter) {
    connect(iter->second, SIGNAL(triggered()), this, SLOT(tutorialTriggered()));
    tutorialMenu->addAction(iter->second);
  }

  menu->addMenu(tutorialMenu);
  menu->addAction(tr("About"), this, SLOT(about()));
  menu->addAction(tr("About Qt"), qApp, SLOT(aboutQt()));
}

bool MainWindow::addProfile()
{
  QComboBox* profileBox = findChild<QComboBox*>("profileBox");
  bool okClicked        = false;

  QString name = QInputDialog::getText(this, tr("Name"),
                                       tr("Please enter a name for the new profile"),
                                       QLineEdit::Normal, QString(), &okClicked);
  if (okClicked && (name.size() > 0)) {
    try {
      profileBox->addItem(name);
      profileBox->setCurrentIndex(profileBox->count() - 1);
      return true;
    } catch (const std::exception& e) {
      reportError(tr("failed to create profile: %1").arg(e.what()));
      return false;
    }
  } else {
    return false;
  }
}

void MainWindow::hookUpWindowTutorials()
{
  QDirIterator dirIter(QApplication::applicationDirPath() + "/tutorials",
                       QStringList("*.js"), QDir::Files);
  while (dirIter.hasNext()) {
    dirIter.next();
    QString fileName = dirIter.fileName();
    QFile file(dirIter.filePath());
    if (!file.open(QIODevice::ReadOnly)) {
      log::error("Failed to open {}", fileName);
      continue;
    }
    QString firstLine = QString::fromUtf8(file.readLine());
    if (firstLine.startsWith("//WIN")) {
      QString windowName = firstLine.mid(6).trimmed();
      if (!m_OrganizerCore.settings().interface().isTutorialCompleted(windowName)) {
        TutorialManager::instance().activateTutorial(windowName, fileName);
      }
    }
  }
}

bool MainWindow::shouldStartTutorial() const
{
  if (GlobalSettings::hideTutorialQuestion()) {
    return false;
  }

  QMessageBox dlg(
      QMessageBox::Question, tr("Show tutorial?"),
      tr("You are starting Mod Organizer for the first time. "
         "Do you want to show a tutorial of its basic features? If you choose "
         "no you can always start the tutorial from the \"Help\" menu."),
      QMessageBox::Yes | QMessageBox::No);

  dlg.setCheckBox(new QCheckBox(tr("Never ask to show tutorials")));

  const auto r = dlg.exec();

  if (dlg.checkBox()->isChecked()) {
    GlobalSettings::setHideTutorialQuestion(true);
  }

  return (r == QMessageBox::Yes);
}

void MainWindow::showEvent(QShowEvent* event)
{
  QMainWindow::showEvent(event);

  if (!m_WasVisible) {
    ui->modList->refreshFilters();
    readSettings();

    // this needs to be connected here instead of in the constructor because the
    // actual changing of the stylesheet is done by MOApplication, which
    // connects its signal in runApplication() (in main.cpp), and that happens
    // _after_ the MainWindow is constructed, but _before_ it is shown
    //
    // by connecting the event here, changing the style setting will first be
    // handled by MOApplication, and then in updateStyle(), at which point the
    // stylesheet has already been set correctly
    connect(this, SIGNAL(styleChanged(QString)), this, SLOT(updateStyle(QString)));

    // only the first time the window becomes visible
    m_Tutorial.registerControl();

    hookUpWindowTutorials();

    if (m_OrganizerCore.settings().firstStart()) {
      QString firstStepsTutorial = ToQString(AppConfig::firstStepsTutorial());
      if (TutorialManager::instance().hasTutorial(firstStepsTutorial)) {
        if (shouldStartTutorial()) {
          TutorialManager::instance().activateTutorial("MainWindow",
                                                       firstStepsTutorial);
        }
      } else {
        log::error("{} missing", firstStepsTutorial);
        QPoint pos = ui->toolBar->mapToGlobal(QPoint());
        pos.rx() += ui->toolBar->width() / 2;
        pos.ry() += ui->toolBar->height();
        QWhatsThis::showText(pos,
                             QObject::tr("Please use \"Help\" from the toolbar to get "
                                         "usage instructions to all elements"));
      }

      if (!m_OrganizerCore.managedGame()->getSupportURL().isEmpty()) {
        QMessageBox::information(this, tr("Game Support Wiki"),
                                 tr("Do you know how to mod this game? Do you need to "
                                    "learn? There's a game support wiki available! "
                                    "Click OK to open the wiki. In the future, you can "
                                    "access this link from the \"Help\" menu."),
                                 QMessageBox::Ok);
        gameSupportTriggered();
      }

      QMessageBox newCatDialog;
      newCatDialog.setWindowTitle(tr("Category Setup"));
      newCatDialog.setText(
          tr("Please choose how to handle the default category setup.\n\n"
             "If you've already connected to Nexus, you can automatically import Nexus "
             "categories for this game (if applicable). Otherwise, use the old Mod "
             "Organizer default category structure, or leave the categories blank (for "
             "manual setup)."));
      QPushButton importBtn(tr("&Import Nexus Categories"));
      QPushButton defaultBtn(tr("Use &Old Category Defaults"));
      QPushButton cancelBtn(tr("Do &Nothing"));
      if (NexusInterface::instance().getAccessManager()->validated()) {
        newCatDialog.addButton(&importBtn, QMessageBox::ButtonRole::AcceptRole);
      }
      newCatDialog.addButton(&defaultBtn, QMessageBox::ButtonRole::AcceptRole);
      newCatDialog.addButton(&cancelBtn, QMessageBox::ButtonRole::RejectRole);
      newCatDialog.exec();
      if (newCatDialog.clickedButton() == &importBtn) {
        importCategories(false);
      } else if (newCatDialog.clickedButton() == &cancelBtn) {
        m_CategoryFactory.reset();
      } else if (newCatDialog.clickedButton() == &defaultBtn) {
        m_CategoryFactory.loadCategories();
      }
      m_CategoryFactory.saveCategories();

      m_OrganizerCore.settings().setFirstStart(false);
    } else {
      auto& settings = m_OrganizerCore.settings();
      if (m_LastVersion < QVersionNumber(2, 5) &&
          !GlobalSettings::hideCategoryReminder()) {
        QMessageBox migrateCatDialog;
        migrateCatDialog.setWindowTitle("Category Migration");
        migrateCatDialog.setText(
            tr("This is your first time running version 2.5 or higher with an old MO2 "
               "instance. The category system now relies on an updated system to map "
               "Nexus categories.\n\n"
               "In order to assign Nexus categories automatically, you will need to "
               "import the Nexus categories for the currently managed game and map "
               "them to your preferred category structure.\n\n"
               "You can either manually open the category editor, via the Settings "
               "dialog or the category filter sidebar, and set up the mappings as you "
               "see fit, or you can automatically import and map the categories as "
               "defined on Nexus.\n\n"
               "As a final option, you can disable Nexus category mapping altogether, "
               "which can be changed at any time in the Settings dialog."));
        QPushButton importBtn(tr("&Import Nexus Categories"));
        QPushButton openSettingsBtn(tr("&Open Categories Dialog"));
        QPushButton disableBtn(tr("&Disable Nexus Mappings"));
        QPushButton closeBtn(tr("&Close"));
        QCheckBox dontShow(tr("&Don't show this again"));
        if (NexusInterface::instance().getAccessManager()->validated()) {
          migrateCatDialog.addButton(&importBtn, QMessageBox::ButtonRole::AcceptRole);
        }
        migrateCatDialog.addButton(&openSettingsBtn,
                                   QMessageBox::ButtonRole::ActionRole);
        migrateCatDialog.addButton(&disableBtn,
                                   QMessageBox::ButtonRole::DestructiveRole);
        migrateCatDialog.addButton(&closeBtn, QMessageBox::ButtonRole::RejectRole);
        migrateCatDialog.setCheckBox(&dontShow);
        migrateCatDialog.exec();
        if (migrateCatDialog.clickedButton() == &importBtn) {
          importCategories(dontShow.isChecked());
        } else if (migrateCatDialog.clickedButton() == &openSettingsBtn) {
          this->ui->filtersEdit->click();
        } else if (migrateCatDialog.clickedButton() == &disableBtn) {
          Settings::instance().nexus().setCategoryMappings(false);
        }
        if (dontShow.isChecked()) {
          GlobalSettings::setHideCategoryReminder(true);
        }
      }
    }

    m_OrganizerCore.settings().widgets().restoreIndex(ui->groupCombo);

    m_OrganizerCore.settings().nexus().registerAsNXMHandler(false);
    m_WasVisible = true;
    updateProblemsButton();

    // notify plugins that the MO2 is ready
    m_PluginContainer.startPlugins(this);

    // forces a log list refresh to display startup logs
    //
    // since the log list is not visible until this point, the automatic
    // resize of columns seems to break the log list (since Qt 5.15.1 or
    // 5.15.2), an make the list empty on startup (in debug the list is not
    // empty because some logs are added after the log list becomes visible)
    //
    // the reset() forces a re-computation of the column size, thus properly
    // the logs that are already in the log model
    //
    ui->logList->reset();
    ui->logList->scrollToBottom();
  }
}

void MainWindow::paintEvent(QPaintEvent* event)
{
  if (m_FirstPaint) {
    allowListResize();
    m_FirstPaint = false;
  }

  QMainWindow::paintEvent(event);
}

void MainWindow::onBeforeClose()
{
  storeSettings();
}

void MainWindow::closeEvent(QCloseEvent* event)
{
  if (isVisible()) {
    // this is messy
    //
    // the main problem this is solving is when closing MO, then getting the
    // lock overlay because processes are still running, then pressing the X
    // again
    //
    // in this case, closeEvent() is _not_ called for the second event and the
    // window is immediately hidden
    //
    // this always saves the settings here; in the event where a lock overlay
    // is then shown, it might save settings multiple times, but it's harmless
    onBeforeClose();
  }

  // this happens for two reasons:
  //  1) the user requested to close the window, such as clicking the X
  //  2) close() is called in runApplication() after application.exec()
  //     returns, which happens when qApp->exit() is called
  //
  // the window must never actually close for 1), because settings haven't been
  // saved yet: the state of many widgets is saved to the ini, which relies on
  // the window still being onscreen (or else everything is considered hidden)
  //
  // for 2), the settings have been saved and the window can just close

  if (ModOrganizerCanCloseNow()) {
    // the user has confirmed if necessary and all settings have been saved,
    // just close it
    QMainWindow::closeEvent(event);
    return;
  }

  if (UILocker::instance().locked()) {
    // don't bother asking the user to confirm if the ui is already locked
    event->ignore();
    ExitModOrganizer(Exit::Force);
    return;
  }

  if (ModOrganizerExiting()) {
    // ignore repeated attempts
    event->ignore();
    return;
  }

  // never close the window because settings might need to be changed
  event->ignore();

  // start the process of exiting, which may require confirmation by calling
  // canExit(), among other things
  ExitModOrganizer();
}

bool MainWindow::canExit()
{
  if (m_OrganizerCore.downloadManager()->downloadsInProgressNoPause()) {
    if (QMessageBox::question(
            this, tr("Downloads in progress"),
            tr("There are still downloads in progress, do you really want to quit?"),
            QMessageBox::Yes | QMessageBox::Cancel) == QMessageBox::Cancel) {
      return false;
    } else {
      m_OrganizerCore.downloadManager()->pauseAll();
    }
  }

  const auto r = m_OrganizerCore.waitForAllUSVFSProcesses();
  if (r == ProcessRunner::Cancelled) {
    return false;
  }

  setCursor(Qt::WaitCursor);
  return true;
}

void MainWindow::cleanup()
{
  QWebEngineProfile::defaultProfile()->clearAllVisitedLinks();

  if (m_IntegratedBrowser) {
    m_IntegratedBrowser->close();
    m_IntegratedBrowser = {};
  }

  m_SaveMetaTimer.stop();
  m_MetaSave.waitForFinished();
}

bool MainWindow::eventFilter(QObject* object, QEvent* event)
{
  if (event->type() == QEvent::StatusTip && object != this) {
    QMainWindow::event(event);
    return true;
  }

  return false;
}

void MainWindow::registerPluginTool(IPluginTool* tool, QString name, QMenu* menu)
{
  if (!menu) {
    menu = ui->actionTool->menu();
  }

  if (name.isEmpty())
    name = tool->displayName();

  QAction* action = new QAction(tool->icon(), name, menu);
  action->setToolTip(tool->tooltip());
  tool->setParentWidget(this);
  connect(
      action, &QAction::triggered, this,
      [this, tool]() {
        try {
          tool->display();
        } catch (const std::exception& e) {
          reportError(
              tr("Plugin \"%1\" failed: %2").arg(tool->localizedName()).arg(e.what()));
        } catch (...) {
          reportError(tr("Plugin \"%1\" failed").arg(tool->localizedName()));
        }
      },
      Qt::QueuedConnection);

  menu->addAction(action);
}

void MainWindow::updateToolMenu()
{
  // Clear the menu:
  ui->actionTool->menu()->clear();

  std::vector<IPluginTool*> toolPlugins = m_PluginContainer.plugins<IPluginTool>();

  // Sort the plugins by display name
  std::sort(std::begin(toolPlugins), std::end(toolPlugins),
            [](IPluginTool* left, IPluginTool* right) {
              return left->displayName().toLower() < right->displayName().toLower();
            });

  // Remove disabled plugins:
  toolPlugins.erase(std::remove_if(std::begin(toolPlugins), std::end(toolPlugins),
                                   [&](auto* tool) {
                                     return !m_PluginContainer.isEnabled(tool);
                                   }),
                    toolPlugins.end());

  // Group the plugins into submenus
  QMap<QString, QList<QPair<QString, IPluginTool*>>> submenuMap;
  for (auto toolPlugin : toolPlugins) {
    QStringList toolName = toolPlugin->displayName().split("/");
    QString submenu      = toolName[0];
    toolName.pop_front();
    submenuMap[submenu].append(
        QPair<QString, IPluginTool*>(toolName.join("/"), toolPlugin));
  }

  // Start registering plugins
  for (auto submenuKey : submenuMap.keys()) {
    if (submenuMap[submenuKey].length() > 1) {
      QMenu* submenu = new QMenu(submenuKey, this);
      for (auto info : submenuMap[submenuKey]) {
        registerPluginTool(info.second, info.first, submenu);
      }
      ui->actionTool->menu()->addMenu(submenu);
    } else {
      registerPluginTool(submenuMap[submenuKey].front().second);
    }
  }
}

void MainWindow::registerModPage(IPluginModPage* modPage)
{
  QAction* action = new QAction(modPage->icon(), modPage->displayName(), this);
  connect(
      action, &QAction::triggered, this,
      [this, modPage]() {
        if (modPage->useIntegratedBrowser()) {

          if (!m_IntegratedBrowser) {
            m_IntegratedBrowser.reset(new BrowserDialog);

            connect(m_IntegratedBrowser.get(),
                    SIGNAL(requestDownload(QUrl, QNetworkReply*)), &m_OrganizerCore,
                    SLOT(requestDownload(QUrl, QNetworkReply*)));
          }

          m_IntegratedBrowser->setWindowTitle(modPage->displayName());
          m_IntegratedBrowser->openUrl(modPage->pageURL());
        } else {
          shell::Open(QUrl(modPage->pageURL()));
        }
      },
      Qt::QueuedConnection);

  ui->actionModPage->menu()->addAction(action);
}

bool MainWindow::registerNexusPage(const QString& gameName)
{
  // Get the plugin
  IPluginGame* plugin = m_OrganizerCore.getGame(gameName);
  if (plugin == nullptr)
    return false;

  // Get the gameURL
  QString gameURL = NexusInterface::instance().getGameURL(gameName);
  if (gameURL.isEmpty())
    return false;

  // Create an action
  QAction* action = new QAction(plugin->gameIcon(),
                                QObject::tr("Visit %1 on Nexus").arg(gameName), this);

  // Bind the action
  connect(
      action, &QAction::triggered, this,
      [this, gameURL]() {
        shell::Open(QUrl(gameURL));
      },
      Qt::QueuedConnection);

  // Add the action
  ui->actionModPage->menu()->addAction(action);

  return true;
}

void MainWindow::updateModPageMenu()
{
  // Clear the menu:
  ui->actionModPage->menu()->clear();

  // Determine the loaded mod page plugins
  std::vector<IPluginModPage*> modPagePlugins =
      m_PluginContainer.plugins<IPluginModPage>();

  // Sort the plugins by display name
  std::sort(std::begin(modPagePlugins), std::end(modPagePlugins),
            [](IPluginModPage* left, IPluginModPage* right) {
              return left->displayName().toLower() < right->displayName().toLower();
            });

  // Remove disabled plugins
  modPagePlugins.erase(std::remove_if(std::begin(modPagePlugins),
                                      std::end(modPagePlugins),
                                      [&](auto* tool) {
                                        return !m_PluginContainer.isEnabled(tool);
                                      }),
                       modPagePlugins.end());

  for (auto* modPagePlugin : modPagePlugins) {
    registerModPage(modPagePlugin);
  }

  QStringList registeredSources;

  // Add the primary game
  QString gameShortName = m_OrganizerCore.managedGame()->gameShortName();
  if (registerNexusPage(gameShortName))
    registeredSources << gameShortName;

  // Add the primary sources
  for (auto gameName : m_OrganizerCore.managedGame()->primarySources()) {
    if (!registeredSources.contains(gameName) && registerNexusPage(gameName))
      registeredSources << gameName;
  }

  // Add a separator if needed
  if (registeredSources.length() > 0)
    ui->actionModPage->menu()->addSeparator();

  // Add the secondary games (sorted)
  QStringList secondaryGames = m_OrganizerCore.managedGame()->validShortNames();
  secondaryGames.sort(Qt::CaseInsensitive);
  for (auto gameName : secondaryGames) {
    if (!registeredSources.contains(gameName) && registerNexusPage(gameName))
      registeredSources << gameName;
  }

  // No mod page plugin and the menu was visible
  bool keepOriginalAction =
      modPagePlugins.size() == 0 && registeredSources.length() <= 1;
  if (keepOriginalAction) {
    ui->toolBar->insertAction(ui->actionAdd_Profile, ui->actionNexus);
  } else {
    ui->toolBar->removeAction(ui->actionNexus);
  }
  ui->actionModPage->setVisible(!keepOriginalAction);
}

void MainWindow::startExeAction()
{
  QAction* action = qobject_cast<QAction*>(sender());

  if (action == nullptr) {
    log::error("not an action?");
    return;
  }

  const auto& list = *m_OrganizerCore.executablesList();

  const auto title = action->text();
  auto itor        = list.find(title);

  if (itor == list.end()) {
    log::warn("startExeAction(): executable '{}' not found", title);
    return;
  }

  action->setEnabled(false);
  Guard g([&] {
    action->setEnabled(true);
  });

  if (itor->minimizeToSystemTray()) {
    m_SystemTrayManager->minimizeToSystemTray();
  }

  m_OrganizerCore.processRunner()
      .setFromExecutable(*itor)
      .setWaitForCompletion(ProcessRunner::TriggerRefresh)
      .run();
}

void MainWindow::activateSelectedProfile()
{
  m_OrganizerCore.setCurrentProfile(ui->profileBox->currentText());

  m_SavesTab->refreshSaveList();
  m_OrganizerCore.refresh();
  ui->modList->updateModCount();
  ui->espList->updatePluginCount();
  ui->statusBar->updateNormalMessage(m_OrganizerCore);
}

void MainWindow::on_profileBox_currentIndexChanged(int index)
{
  if (!ui->profileBox->isEnabled()) {
    return;
  }

  int previousIndex = m_OldProfileIndex;
  m_OldProfileIndex = index;

  // select has changed, save stuff
  if ((previousIndex != -1) && (m_OrganizerCore.currentProfile() != nullptr) &&
      m_OrganizerCore.currentProfile()->exists()) {
    m_OrganizerCore.saveCurrentLists();
  }

  // Avoid doing any refresh if currentProfile is already set but previous
  // index was -1 as it means that this is happening during initialization so
  // everything has already been set.
  if (previousIndex == -1 && m_OrganizerCore.currentProfile() != nullptr &&
      m_OrganizerCore.currentProfile()->exists() &&
      ui->profileBox->currentText() == m_OrganizerCore.currentProfile()->name()) {
    return;
  }

  // ensure the new index is valid
  if (index < 0 || index >= ui->profileBox->count()) {
    log::debug("invalid profile index, using last profile");
    ui->profileBox->setCurrentIndex(ui->profileBox->count() - 1);
  }

  // handle <manage> item
  if (ui->profileBox->currentIndex() == 0) {
    // remember the profile name that was selected before, previousIndex can't
    // be used again because adding/deleting profiles will change the order
    // in the list
    const QString previousName = ui->profileBox->itemText(previousIndex);

    // show the dialog
    ProfilesDialog dlg(previousName, m_OrganizerCore, this);
    dlg.exec();

    // check if the user clicked 'select' to select another profile
    std::optional<QString> newSelection = dlg.selectedProfile();

    // refresh the profile box; this loops until there is at least one profile
    // available, which shouldn't really happen because the dialog won't allow
    // it
    //
    // the `false` to refreshProfiles() is so it doesn't try to select the
    // profile in the list because 1) it's done just below, and 2) it might be
    // wrong profile if there's something in newSelection
    while (!refreshProfiles(false)) {
      ProfilesDialog dlg(previousName, m_OrganizerCore, this);
      dlg.exec();
      newSelection = dlg.selectedProfile();
    }

    // note that setCurrentText() is recursive, it will re-execute this function
    if (newSelection) {
      ui->profileBox->setCurrentText(*newSelection);
    } else {
      ui->profileBox->setCurrentText(previousName);
    }

    // nothing else to do because setCurrentText() is recursive and will
    // have re-executed on_profileBox_currentIndexChanged() again, doing all
    // the stuff below for the new selection
    return;
  }

  activateSelectedProfile();

  auto saveGames = m_OrganizerCore.gameFeatures().gameFeature<LocalSavegames>();
  if (saveGames != nullptr) {
    if (saveGames->prepareProfile(m_OrganizerCore.currentProfile().get())) {
      m_SavesTab->refreshSaveList();
    }
  }

  auto invalidation = m_OrganizerCore.gameFeatures().gameFeature<BSAInvalidation>();
  if (invalidation != nullptr) {
    if (invalidation->prepareProfile(m_OrganizerCore.currentProfile().get())) {
      QTimer::singleShot(5, [this] {
        m_OrganizerCore.refresh();
      });
    }
  }
}

bool MainWindow::refreshProfiles(bool selectProfile, QString newProfile)
{
  QComboBox* profileBox = findChild<QComboBox*>("profileBox");

  QString currentProfileName = profileBox->currentText();

  profileBox->blockSignals(true);
  profileBox->clear();
  profileBox->addItem(QObject::tr("<Manage...>"));

  QDir profilesDir(Settings::instance().paths().profiles());
  profilesDir.setFilter(QDir::AllDirs | QDir::NoDotAndDotDot);

  QDirIterator profileIter(profilesDir);

  while (profileIter.hasNext()) {
    profileIter.next();
    try {
      profileBox->addItem(profileIter.fileName());
    } catch (const std::runtime_error& error) {
      reportError(QObject::tr("failed to parse profile %1: %2")
                      .arg(profileIter.fileName())
                      .arg(error.what()));
    }
  }

  // now select one of the profiles, preferably the one that was selected before
  profileBox->blockSignals(false);

  if (selectProfile) {
    if (profileBox->count() > 1) {
      if (newProfile.isEmpty()) {
        profileBox->setCurrentText(currentProfileName);
      } else {
        profileBox->setCurrentText(newProfile);
      }
      if (profileBox->currentIndex() == 0) {
        profileBox->setCurrentIndex(1);
      }
    }
  }
  return profileBox->count() > 1;
}

void MainWindow::refreshExecutablesList()
{
  QAbstractItemModel* model = ui->executablesListBox->model();

  auto add = [&](const QString& title, const QFileInfo& binary) {
    QIcon icon;
    if (!binary.fileName().isEmpty()) {
      icon = iconForExecutable(binary.filePath());
    }

    ui->executablesListBox->addItem(icon, title);

    const auto i = ui->executablesListBox->count() - 1;

    model->setData(model->index(i, 0),
                   QSize(0, ui->executablesListBox->iconSize().height() + 4),
                   Qt::SizeHintRole);
  };

  ui->executablesListBox->setEnabled(false);
  ui->executablesListBox->clear();

  add(tr("<Edit...>"), {});

  for (const auto& exe : *m_OrganizerCore.executablesList()) {
    if (!exe.hide()) {
      add(exe.title(), exe.binaryInfo());
    }
  }

  if (ui->executablesListBox->count() == 1) {
    // all executables are hidden, add an empty one to at least be able to
    // switch to edit
    add(tr("(no executables)"), QFileInfo(":badfile"));
  }

  ui->executablesListBox->setCurrentIndex(1);
  ui->executablesListBox->setEnabled(true);
}

static bool BySortValue(const std::pair<UINT32, QTreeWidgetItem*>& LHS,
                        const std::pair<UINT32, QTreeWidgetItem*>& RHS)
{
  return LHS.first < RHS.first;
}

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

void MainWindow::updateBSAList(const QStringList& defaultArchives,
                               const QStringList& activeArchives)
{
  m_DefaultArchives = defaultArchives;
  ui->bsaList->clear();
  ui->bsaList->header()->setSectionResizeMode(QHeaderView::ResizeToContents);
  std::vector<std::pair<UINT32, QTreeWidgetItem*>> items;

  auto invalidation = m_OrganizerCore.gameFeatures().gameFeature<BSAInvalidation>();
  std::vector<FileEntryPtr> files = m_OrganizerCore.directoryStructure()->getFiles();

  QStringList plugins =
      m_OrganizerCore.findFiles("", [](const QString& fileName) -> bool {
        return fileName.endsWith(".esp", Qt::CaseInsensitive) ||
               fileName.endsWith(".esm", Qt::CaseInsensitive) ||
               fileName.endsWith(".esl", Qt::CaseInsensitive);
      });

  QList<std::pair<QString, QString>> pluginNamePairs;
  pluginNamePairs.reserve(plugins.size());
  for (const QString& pluginName : plugins) {
    QFileInfo pluginInfo(pluginName);
    pluginNamePairs.append(
        std::make_pair(pluginInfo.completeBaseName(), pluginInfo.fileName()));
  }

  auto hasAssociatedPlugin = [&](const QString& bsaName) -> bool {
    for (const auto& [completeBaseName, fileName] : pluginNamePairs) {
      if (bsaName.startsWith(completeBaseName, Qt::CaseInsensitive) &&
          (m_OrganizerCore.pluginList()->state(fileName) ==
           IPluginList::STATE_ACTIVE)) {
        return true;
      }
    }
    return false;
  };

  for (FileEntryPtr current : files) {
    QFileInfo fileInfo(ToQString(current->getName().c_str()));

    if (fileInfo.suffix().toLower() == "bsa" || fileInfo.suffix().toLower() == "ba2") {
      int index = activeArchives.indexOf(fileInfo.fileName());
      if (index == -1) {
        index = 0xFFFF;
      } else {
        index += 2;
      }

      if ((invalidation != nullptr) &&
          invalidation->isInvalidationBSA(fileInfo.fileName())) {
        index = 1;
      }

      int originId = current->getOrigin();
      FilesOrigin& origin =
          m_OrganizerCore.directoryStructure()->getOriginByID(originId);

      QTreeWidgetItem* newItem = new QTreeWidgetItem(
          QStringList() << fileInfo.fileName() << ToQString(origin.getName()));
      newItem->setData(0, Qt::UserRole, index);
      newItem->setData(1, Qt::UserRole, originId);
      newItem->setFlags(newItem->flags() &
                        ~(Qt::ItemIsDropEnabled | Qt::ItemIsUserCheckable));
      newItem->setCheckState(0, (index != -1) ? Qt::Checked : Qt::Unchecked);
      newItem->setData(0, Qt::UserRole, false);
      if (m_OrganizerCore.settings().game().forceEnableCoreFiles() &&
          defaultArchives.contains(fileInfo.fileName())) {
        newItem->setCheckState(0, Qt::Checked);
        newItem->setDisabled(true);
        newItem->setData(0, Qt::UserRole, true);
      } else if (fileInfo.fileName().compare("update.bsa", Qt::CaseInsensitive) == 0) {
        newItem->setCheckState(0, Qt::Checked);
        newItem->setDisabled(true);
      } else if (hasAssociatedPlugin(fileInfo.fileName())) {
        newItem->setCheckState(0, Qt::Checked);
        newItem->setDisabled(true);
      } else {
        newItem->setCheckState(0, Qt::Unchecked);
        newItem->setDisabled(true);
      }
      if (index < 0)
        index = 0;

      UINT32 sortValue = ((origin.getPriority() & 0xFFFF) << 16) | (index & 0xFFFF);
      items.push_back(std::make_pair(sortValue, newItem));
    }
  }
  std::sort(items.begin(), items.end(), BySortValue);

  for (auto iter = items.begin(); iter != items.end(); ++iter) {
    int originID = iter->second->data(1, Qt::UserRole).toInt();

    const FilesOrigin& origin =
        m_OrganizerCore.directoryStructure()->getOriginByID(originID);

    QString modName;
    const unsigned int modIndex = ModInfo::getIndex(ToQString(origin.getName()));

    if (modIndex == UINT_MAX) {
      modName = UnmanagedModName();
    } else {
      ModInfo::Ptr modInfo = ModInfo::getByIndex(modIndex);
      modName              = modInfo->name();
    }

    QList<QTreeWidgetItem*> items =
        ui->bsaList->findItems(modName, Qt::MatchFixedString);
    QTreeWidgetItem* subItem = nullptr;
    if (items.length() > 0) {
      subItem = items.at(0);
    } else {
      subItem = new QTreeWidgetItem(QStringList(modName));
      subItem->setFlags(subItem->flags() & ~Qt::ItemIsDragEnabled);
      ui->bsaList->addTopLevelItem(subItem);
    }
    subItem->addChild(iter->second);
    subItem->setExpanded(true);
  }
  checkBSAList();
}

void MainWindow::checkBSAList()
{
  auto archives = m_OrganizerCore.gameFeatures().gameFeature<DataArchives>();

  if (archives != nullptr) {
    ui->bsaList->blockSignals(true);
    ON_BLOCK_EXIT([&]() {
      ui->bsaList->blockSignals(false);
    });

    QStringList defaultArchives =
        archives->archives(m_OrganizerCore.currentProfile().get());

    bool warning = false;

    for (int i = 0; i < ui->bsaList->topLevelItemCount(); ++i) {
      bool modWarning         = false;
      QTreeWidgetItem* tlItem = ui->bsaList->topLevelItem(i);
      for (int j = 0; j < tlItem->childCount(); ++j) {
        QTreeWidgetItem* item = tlItem->child(j);
        QString filename      = item->text(0);
        item->setIcon(0, QIcon());
        item->setToolTip(0, QString());

        if (item->checkState(0) == Qt::Unchecked) {
          if (defaultArchives.contains(filename)) {
            item->setIcon(0, QIcon(":/MO/gui/warning"));
            item->setToolTip(
                0, tr("This bsa is enabled in the ini file so it may be required!"));
            modWarning = true;
          }
        }
      }
      if (modWarning) {
        ui->bsaList->expandItem(ui->bsaList->topLevelItem(i));
        warning = true;
      }
    }
    if (warning) {
      ui->tabWidget->setTabIcon(1, QIcon(":/MO/gui/warning"));
    } else {
      ui->tabWidget->setTabIcon(1, QIcon());
    }
  }
}

void MainWindow::saveModMetas()
{
  if (m_MetaSave.isFinished()) {
    m_MetaSave = QtConcurrent::run([this]() {
      for (unsigned int i = 0; i < ModInfo::getNumMods(); ++i) {
        ModInfo::Ptr modInfo = ModInfo::getByIndex(i);
        modInfo->saveMeta();
      }
    });
  }
}

void MainWindow::fixCategories()
{
  for (unsigned int i = 0; i < ModInfo::getNumMods(); ++i) {
    ModInfo::Ptr modInfo     = ModInfo::getByIndex(i);
    std::set<int> categories = modInfo->getCategories();
    for (std::set<int>::iterator iter = categories.begin(); iter != categories.end();
         ++iter) {
      if (!m_CategoryFactory.categoryExists(*iter)) {
        modInfo->setCategory(*iter, false);
      }
    }
  }
}

void MainWindow::setupNetworkProxy(bool activate)
{
  QNetworkProxyFactory::setUseSystemConfiguration(activate);
}

void MainWindow::activateProxy(bool activate)
{
  QProgressDialog busyDialog(tr("Activating Network Proxy"), QString(), 0, 0,
                             parentWidget());
  busyDialog.setWindowFlags(busyDialog.windowFlags() &
                            ~Qt::WindowContextHelpButtonHint);
  busyDialog.setWindowModality(Qt::WindowModal);
  busyDialog.show();

  QFutureWatcher<void> futureWatcher;
  QEventLoop loop;
  connect(&futureWatcher, &QFutureWatcher<void>::finished, &loop, &QEventLoop::quit,
          Qt::QueuedConnection);

  futureWatcher.setFuture(QtConcurrent::run(MainWindow::setupNetworkProxy, activate));

  // wait for setupNetworkProxy while keeping ui responsive
  loop.exec();

  busyDialog.hide();
}

void MainWindow::readSettings()
{
  const auto& s = m_OrganizerCore.settings();

  if (!s.geometry().restoreGeometry(this)) {
    resize(1300, 800);
  }

  s.geometry().restoreState(this);
  s.geometry().restoreDocks(this);
  s.geometry().restoreToolbars(this);
  s.geometry().restoreState(ui->splitter);
  s.geometry().restoreState(ui->categoriesSplitter);
  s.geometry().restoreVisibility(ui->menuBar);
  s.geometry().restoreVisibility(ui->statusBar);

  FilterWidget::setOptions(s.interface().filterOptions());

  {
    // special case in case someone puts 0 in the INI
    auto v = s.widgets().index(ui->executablesListBox);
    if (!v || v == 0) {
      v = 1;
    }

    ui->executablesListBox->setCurrentIndex(*v);
  }

  s.widgets().restoreIndex(ui->tabWidget);

  ui->modList->restoreState(s);

  {
    s.geometry().restoreVisibility(ui->categoriesGroup, false);
    const auto v = ui->categoriesGroup->isVisible();
    setCategoryListVisible(v);
    ui->displayCategoriesBtn->setChecked(v);
  }

  if (s.network().useProxy()) {
    activateProxy(true);
  }
}

void MainWindow::processUpdates()
{
  auto& settings      = m_OrganizerCore.settings();
  const auto earliest = QVersionNumber::fromString("2.1.2").normalized();

  const auto lastVersion = settings.version().value_or(earliest);
  const auto currentVersion =
      QVersionNumber::fromString(m_OrganizerCore.getVersion().string()).normalized();

  m_LastVersion = lastVersion;

  settings.processUpdates(currentVersion, lastVersion);

  if (!settings.firstStart()) {
    if (lastVersion < QVersionNumber(2, 1, 6)) {
      ui->modList->header()->setSectionHidden(ModList::COL_NOTES, true);
    }

    if (lastVersion < QVersionNumber(2, 2, 1)) {
      // hide new columns by default
      for (int i = DownloadList::COL_MODNAME; i < DownloadList::COL_COUNT; ++i) {
        ui->downloadView->header()->hideSection(i);
      }
    }

    if (lastVersion < QVersionNumber(2, 3)) {
      for (int i = 1; i < ui->dataTree->header()->count(); ++i)
        ui->dataTree->setColumnWidth(i, 150);
    }
  }

  if (currentVersion < lastVersion) {
    const auto text =
        tr("Notice: Your current MO version (%1) is lower than the previously used one "
           "(%2). "
           "The GUI may not downgrade gracefully, so you may experience oddities. "
           "However, there should be no serious issues.")
            .arg(currentVersion.toString())
            .arg(lastVersion.toString());

    log::warn("{}", text);
  }
}

void MainWindow::storeSettings()
{
  auto& s = m_OrganizerCore.settings();

  s.geometry().saveState(this);
  s.geometry().saveGeometry(this);
  s.geometry().saveDocks(this);

  s.geometry().saveVisibility(ui->menuBar);
  s.geometry().saveVisibility(ui->statusBar);
  s.geometry().saveToolbars(this);
  s.geometry().saveState(ui->splitter);
  s.geometry().saveState(ui->categoriesSplitter);
  s.geometry().saveMainWindowMonitor(this);
  s.geometry().saveVisibility(ui->categoriesGroup);

  s.geometry().saveState(ui->espList->header());
  s.geometry().saveState(ui->downloadView->header());
  s.geometry().saveState(ui->savegameList->header());

  s.widgets().saveIndex(ui->executablesListBox);
  s.widgets().saveIndex(ui->tabWidget);

  m_DataTab->saveState(s);
  ui->modList->saveState(s);

  s.interface().setFilterOptions(FilterWidget::options());
}

QMainWindow* MainWindow::mainWindow()
{
  return this;
}

void MainWindow::on_tabWidget_currentChanged(int index)
{
  QWidget* currentWidget = ui->tabWidget->widget(index);
  if (currentWidget == ui->espTab) {
    m_OrganizerCore.refreshESPList();
    ui->espList->activated();
  } else if (currentWidget == ui->bsaTab) {
    m_OrganizerCore.refreshBSAList();
  } else if (currentWidget == ui->dataTab) {
    m_DataTab->activated();
  } else if (currentWidget == ui->savesTab) {
    m_SavesTab->refreshSaveList();
  }
}

void MainWindow::on_startButton_clicked()
{
  const Executable* selectedExecutable = getSelectedExecutable();
  if (!selectedExecutable) {
    return;
  }

  ui->startButton->setEnabled(false);
  Guard g([&] {
    ui->startButton->setEnabled(true);
  });

  if (selectedExecutable->minimizeToSystemTray()) {
    m_SystemTrayManager->minimizeToSystemTray();
  }

  m_OrganizerCore.processRunner()
      .setFromExecutable(*selectedExecutable)
      .setWaitForCompletion(ProcessRunner::TriggerRefresh)
      .run();
}

bool MainWindow::modifyExecutablesDialog(int selection)
{
  bool result = false;

  try {
    EditExecutablesDialog dialog(m_OrganizerCore, selection, this);

    result = (dialog.exec() == QDialog::Accepted);

    refreshExecutablesList();
    updatePinnedExecutables();
  } catch (const std::exception& e) {
    reportError(e.what());
  }

  return result;
}

void MainWindow::on_executablesListBox_currentIndexChanged(int index)
{
  if (!ui->executablesListBox->isEnabled()) {
    return;
  }

  const int previousIndex = (m_OldExecutableIndex > 0 ? m_OldExecutableIndex : 1);

  m_OldExecutableIndex = index;

  if (index == 0) {
    modifyExecutablesDialog(previousIndex - 1);
    const auto newCount = ui->executablesListBox->count();

    if (previousIndex >= 0 && previousIndex < newCount) {
      ui->executablesListBox->setCurrentIndex(previousIndex);
    } else {
      ui->executablesListBox->setCurrentIndex(newCount - 1);
    }
  }
}

void MainWindow::helpTriggered()
{
  QWhatsThis::enterWhatsThisMode();
}

void MainWindow::wikiTriggered()
{
  shell::Open(QUrl("https://modorganizer2.github.io/"));
}

void MainWindow::gameSupportTriggered()
{
  shell::Open(QUrl(m_OrganizerCore.managedGame()->getSupportURL()));
}

void MainWindow::discordTriggered()
{
  shell::Open(QUrl("https://discord.gg/ewUVAqyrQX"));
}

void MainWindow::issueTriggered()
{
  shell::Open(QUrl("https://github.com/Modorganizer2/modorganizer/issues"));
}

void MainWindow::tutorialTriggered()
{
  QAction* tutorialAction = qobject_cast<QAction*>(sender());
  if (tutorialAction != nullptr) {
    TutorialManager::instance().activateTutorial("MainWindow",
                                                 tutorialAction->data().toString());
  }
}

void MainWindow::on_actionInstallMod_triggered()
{
  ui->modList->actions().installMod();
}

void MainWindow::on_action_Refresh_triggered()
{
  refreshProfile_activated();
}

void MainWindow::on_actionAdd_Profile_triggered()
{
  for (;;) {
    ProfilesDialog profilesDialog(m_OrganizerCore.currentProfile()->name(),
                                  m_OrganizerCore, this);

    // workaround: need to disable monitoring of the saves directory, otherwise the
    // active profile directory is locked
    m_SavesTab->stopMonitorSaves();
    profilesDialog.exec();
    m_SavesTab->refreshSaveList();  // since the save list may now be outdated we have
                                    // to refresh it completely

    if (refreshProfiles(true, profilesDialog.selectedProfile().value_or("")) &&
        !profilesDialog.failed()) {
      break;
    }
  }

  auto saveGames = m_OrganizerCore.gameFeatures().gameFeature<LocalSavegames>();
  if (saveGames != nullptr) {
    if (saveGames->prepareProfile(m_OrganizerCore.currentProfile().get())) {
      m_SavesTab->refreshSaveList();
    }
  }

  auto invalidation = m_OrganizerCore.gameFeatures().gameFeature<BSAInvalidation>();
  if (invalidation != nullptr) {
    if (invalidation->prepareProfile(m_OrganizerCore.currentProfile().get())) {
      QTimer::singleShot(5, [this] {
        m_OrganizerCore.refresh();
      });
    }
  }
}

void MainWindow::on_actionModify_Executables_triggered()
{
  const auto sel = (m_OldExecutableIndex > 0 ? m_OldExecutableIndex - 1 : 0);

  if (modifyExecutablesDialog(sel)) {
    const auto newCount = ui->executablesListBox->count();
    if (m_OldExecutableIndex >= 0 && m_OldExecutableIndex < newCount) {
      ui->executablesListBox->setCurrentIndex(m_OldExecutableIndex);
    } else {
      ui->executablesListBox->setCurrentIndex(newCount - 1);
    }
  }
}

void MainWindow::refresherProgress(const DirectoryRefreshProgress* p)
{
  if (p->finished()) {
    setEnabled(true);
    ui->statusBar->setProgress(100);
  } else {
    setEnabled(false);
    ui->statusBar->setProgress(p->percentDone());
  }
}

void MainWindow::onDirectoryStructureChanged()
{
  // some problem-reports may rely on the virtual directory tree so they need to be
  // updated now
  scheduleCheckForProblems();
  m_DataTab->updateTree();
}

void MainWindow::modInstalled(const QString& modName)
{
  if (!m_OrganizerCore.settings().interface().checkUpdateAfterInstallation()) {
    return;
  }

  unsigned int index = ModInfo::getIndex(modName);

  if (index == UINT_MAX) {
    return;
  }

  // force an update to happen
  ui->modList->actions().checkModsForUpdates(
      {m_OrganizerCore.modList()->index(index, 0)});
}

void MainWindow::importCategories(bool)
{
  NexusInterface& nexus = NexusInterface::instance();
  nexus.setPluginContainer(&m_OrganizerCore.pluginContainer());
  nexus.requestGameInfo(Settings::instance().game().plugin()->gameShortName(), this,
                        QVariant(), QString());
}

void MainWindow::showMessage(const QString& message)
{
  MessageDialog::showMessage(message, this);
}

void MainWindow::showError(const QString& message)
{
  reportError(message);
}

void MainWindow::modRenamed(const QString& oldName, const QString& newName)
{
  Profile::renameModInAllProfiles(oldName, newName);

  // immediately refresh the active profile because the data in memory is invalid
  m_OrganizerCore.currentProfile()->refreshModStatus();

  // also fix the directory structure
  try {
    if (m_OrganizerCore.directoryStructure()->originExists(ToWString(oldName))) {
      FilesOrigin& origin =
          m_OrganizerCore.directoryStructure()->getOriginByName(ToWString(oldName));
      origin.setName(ToWString(newName));
    } else {
    }
  } catch (const std::exception& e) {
    reportError(tr("failed to change origin name: %1").arg(e.what()));
  }
}

void MainWindow::fileMoved(const QString& filePath, const QString& oldOriginName,
                           const QString& newOriginName)
{
  const FileEntryPtr filePtr =
      m_OrganizerCore.directoryStructure()->findFile(ToWString(filePath));
  if (filePtr.get() != nullptr) {
    try {
      if (m_OrganizerCore.directoryStructure()->originExists(
              ToWString(newOriginName))) {
        FilesOrigin& newOrigin = m_OrganizerCore.directoryStructure()->getOriginByName(
            ToWString(newOriginName));

        QString fullNewPath = ToQString(newOrigin.getPath()) + "\\" + filePath;
        WIN32_FIND_DATAW findData;
        HANDLE hFind;
        hFind = ::FindFirstFileW(ToWString(fullNewPath).c_str(), &findData);
        filePtr->addOrigin(newOrigin.getID(), findData.ftCreationTime, L"", -1);
        FindClose(hFind);
      }
      if (m_OrganizerCore.directoryStructure()->originExists(
              ToWString(oldOriginName))) {
        FilesOrigin& oldOrigin = m_OrganizerCore.directoryStructure()->getOriginByName(
            ToWString(oldOriginName));
        filePtr->removeOrigin(oldOrigin.getID());
      }
    } catch (const std::exception& e) {
      reportError(tr("failed to move \"%1\" from mod \"%2\" to \"%3\": %4")
                      .arg(filePath)
                      .arg(oldOriginName)
                      .arg(newOriginName)
                      .arg(e.what()));
    }
  } else {
    // this is probably not an error, the specified path is likely a directory
  }
}

void MainWindow::modRemoved(const QString& fileName)
{
  if (!fileName.isEmpty() && !QFileInfo(fileName).isAbsolute()) {
    m_OrganizerCore.downloadManager()->markUninstalled(fileName);
  }
}

void MainWindow::windowTutorialFinished(const QString& windowName)
{
  m_OrganizerCore.settings().interface().setTutorialCompleted(windowName);
}

void MainWindow::displayModInformation(ModInfo::Ptr modInfo, unsigned int modIndex,
                                       ModInfoTabIDs tabID)
{
  ui->modList->actions().displayModInformation(modInfo, modIndex, tabID);
}

bool MainWindow::closeWindow()
{
  return close();
}

void MainWindow::setWindowEnabled(bool enabled)
{
  setEnabled(enabled);
}

void MainWindow::refreshProfile_activated()
{
  m_OrganizerCore.refresh();
}

void MainWindow::saveArchiveList()
{
  if (m_OrganizerCore.isArchivesInit()) {
    SafeWriteFile archiveFile(m_OrganizerCore.currentProfile()->getArchivesFileName());
    for (int i = 0; i < ui->bsaList->topLevelItemCount(); ++i) {
      QTreeWidgetItem* tlItem = ui->bsaList->topLevelItem(i);
      for (int j = 0; j < tlItem->childCount(); ++j) {
        QTreeWidgetItem* item = tlItem->child(j);
        if (item->checkState(0) == Qt::Checked) {
          archiveFile->write(item->text(0).toUtf8().append("\r\n"));
        }
      }
    }
    archiveFile->commit();
  } else {
    log::debug("archive list not initialised");
  }
}

void MainWindow::openInstanceFolder()
{
  QString dataPath = qApp->property("dataPath").toString();
  shell::Explore(dataPath);
}

void MainWindow::openInstallFolder()
{
  shell::Explore(qApp->applicationDirPath());
}

void MainWindow::openPluginsFolder()
{
  QString pluginsPath =
      QCoreApplication::applicationDirPath() + "/" + ToQString(AppConfig::pluginPath());
  shell::Explore(pluginsPath);
}

void MainWindow::openStylesheetsFolder()
{
  QString ssPath = QCoreApplication::applicationDirPath() + "/" +
                   ToQString(AppConfig::stylesheetsPath());
  shell::Explore(ssPath);
}

void MainWindow::openProfileFolder()
{
  shell::Explore(m_OrganizerCore.currentProfile()->absolutePath());
}

void MainWindow::openIniFolder()
{
  if (m_OrganizerCore.currentProfile()->localSettingsEnabled()) {
    shell::Explore(m_OrganizerCore.currentProfile()->absolutePath());
  } else {
    shell::Explore(m_OrganizerCore.managedGame()->documentsDirectory());
  }
}

void MainWindow::openDownloadsFolder()
{
  shell::Explore(m_OrganizerCore.settings().paths().downloads());
}

void MainWindow::openModsFolder()
{
  shell::Explore(m_OrganizerCore.settings().paths().mods());
}

void MainWindow::openGameFolder()
{
  shell::Explore(m_OrganizerCore.managedGame()->gameDirectory());
}

void MainWindow::openMyGamesFolder()
{
  shell::Explore(m_OrganizerCore.managedGame()->documentsDirectory());
}

QMenu* MainWindow::openFolderMenu()
{
  QMenu* FolderMenu = new QMenu(this);

  // game folders that are not necessarily MO-specific
  FolderMenu->addAction(tr("Open Game folder"), this, SLOT(openGameFolder()));
  FolderMenu->addAction(tr("Open MyGames folder"), this, SLOT(openMyGamesFolder()));
  FolderMenu->addAction(tr("Open INIs folder"), this, SLOT(openIniFolder()));

  FolderMenu->addSeparator();

  // MO-specific folders that are related to modding the game
  FolderMenu->addAction(tr("Open Instance folder"), this, SLOT(openInstanceFolder()));
  FolderMenu->addAction(tr("Open Mods folder"), this, SLOT(openModsFolder()));
  FolderMenu->addAction(tr("Open Profile folder"), this, SLOT(openProfileFolder()));
  FolderMenu->addAction(tr("Open Downloads folder"), this, SLOT(openDownloadsFolder()));

  FolderMenu->addSeparator();

  // MO-specific folders that are not directly related to modding and are either
  // in the installation folder or the instance
  FolderMenu->addAction(tr("Open MO2 Install folder"), this, SLOT(openInstallFolder()));
  FolderMenu->addAction(tr("Open MO2 Plugins folder"), this, SLOT(openPluginsFolder()));
  FolderMenu->addAction(tr("Open MO2 Stylesheets folder"), this,
                        SLOT(openStylesheetsFolder()));
  FolderMenu->addAction(tr("Open MO2 Logs folder"), [=] {
    ui->logList->openLogsFolder();
  });

  return FolderMenu;
}

void MainWindow::linkToolbar()
{
  Executable* exe = getSelectedExecutable();
  if (!exe) {
    return;
  }

  exe->setShownOnToolbar(!exe->isShownOnToolbar());
  updatePinnedExecutables();
}

void MainWindow::linkDesktop()
{
  if (auto* exe = getSelectedExecutable()) {
    env::Shortcut(*exe).toggle(env::Shortcut::Desktop);
  }
}

void MainWindow::linkMenu()
{
  if (auto* exe = getSelectedExecutable()) {
    env::Shortcut(*exe).toggle(env::Shortcut::StartMenu);
  }
}

void MainWindow::on_linkButton_pressed()
{
  const Executable* exe = getSelectedExecutable();
  if (!exe) {
    return;
  }

  const QIcon addIcon(":/MO/gui/link");
  const QIcon removeIcon(":/MO/gui/remove");

  env::Shortcut shortcut(*exe);

  m_LinkToolbar->setIcon(exe->isShownOnToolbar() ? removeIcon : addIcon);

  m_LinkDesktop->setIcon(shortcut.exists(env::Shortcut::Desktop) ? removeIcon
                                                                 : addIcon);

  m_LinkStartMenu->setIcon(shortcut.exists(env::Shortcut::StartMenu) ? removeIcon
                                                                     : addIcon);
}

void MainWindow::on_actionSettings_triggered()
{
  Settings& settings = m_OrganizerCore.settings();

  QString oldModDirectory(settings.paths().mods());
  QString oldCacheDirectory(settings.paths().cache());
  QString oldProfilesDirectory(settings.paths().profiles());
  QString oldManagedGameDirectory(settings.game().directory().value_or(""));
  bool oldDisplayForeign(settings.interface().displayForeign());
  bool oldArchiveParsing(settings.archiveParsing());
  bool proxy                    = settings.network().useProxy();
  DownloadManager* dlManager    = m_OrganizerCore.downloadManager();
  const bool oldCheckForUpdates = settings.checkForUpdates();
  const int oldMaxDumps         = settings.diagnostics().maxCoreDumps();

  SettingsDialog dialog(&m_PluginContainer, settings, this);
  dialog.exec();

  auto e = dialog.exitNeeded();

  if (oldManagedGameDirectory != settings.game().directory()) {
    e |= Exit::Restart;
  }

  if (e.testFlag(Exit::Restart)) {
    const auto r =
        MOBase::TaskDialog(this)
            .title(tr("Restart Mod Organizer"))
            .main("Restart Mod Organizer")
            .content(tr("Mod Organizer must restart to finish configuration changes"))
            .icon(QMessageBox::Question)
            .button({tr("Restart"), QMessageBox::Yes})
            .button(
                {tr("Continue"), tr("Some things might be weird."), QMessageBox::No})
            .exec();

    if (r == QMessageBox::Yes) {
      ExitModOrganizer(e);
    }
  }

  InstallationManager* instManager = m_OrganizerCore.installationManager();
  instManager->setModsDirectory(settings.paths().mods());
  instManager->setDownloadDirectory(settings.paths().downloads());

  // Schedule a problem check since diagnose plugins may have been enabled / disabled.
  scheduleCheckForProblems();

  fixCategories();
  ui->modList->refreshFilters();
  ui->modList->refresh();

  m_OrganizerCore.refreshLists();

  updateSortButton();

  if (settings.paths().profiles() != oldProfilesDirectory) {
    refreshProfiles();
  }

  if (dlManager->getOutputDirectory() != settings.paths().downloads()) {
    if (dlManager->downloadsInProgress()) {
      MessageDialog::showMessage(tr("Can't change download directory while "
                                    "downloads are in progress!"),
                                 this);
    } else {
      dlManager->setOutputDirectory(settings.paths().downloads());
    }
  }

  if ((settings.paths().mods() != oldModDirectory) ||
      (settings.interface().displayForeign() != oldDisplayForeign)) {
    m_OrganizerCore.refresh();
  }

  const auto state = settings.archiveParsing();
  if (state != oldArchiveParsing) {
    if (!state) {
      ui->dataTabShowFromArchives->setCheckState(Qt::Unchecked);
      ui->dataTabShowFromArchives->setEnabled(false);
    } else {
      ui->dataTabShowFromArchives->setCheckState(Qt::Checked);
      ui->dataTabShowFromArchives->setEnabled(true);
    }
    m_OrganizerCore.refresh();
  }

  if (settings.paths().cache() != oldCacheDirectory) {
    NexusInterface::instance().setCacheDirectory(settings.paths().cache());
  }

  if (proxy != settings.network().useProxy()) {
    activateProxy(settings.network().useProxy());
  }

  ui->statusBar->checkSettings(m_OrganizerCore.settings());
  m_DownloadsTab->update();

  m_OrganizerCore.setLogLevel(settings.diagnostics().logLevel());

  if (settings.diagnostics().maxCoreDumps() != oldMaxDumps) {
    m_OrganizerCore.cycleDiagnostics();
  }

  toggleMO2EndorseState();

  if (oldCheckForUpdates != settings.checkForUpdates()) {
    toggleUpdateAction();

    if (settings.checkForUpdates()) {
      m_OrganizerCore.checkForUpdates();
    }
  }
}

void MainWindow::onPluginRegistrationChanged()
{
  updateModPageMenu();
  scheduleCheckForProblems();
  m_DownloadsTab->update();
}

void MainWindow::refreshNexusCategories(CategoriesDialog* dialog)
{
  NexusInterface& nexus = NexusInterface::instance();
  nexus.setPluginContainer(&m_PluginContainer);
  if (!Settings::instance().game().plugin()->primarySources().isEmpty()) {
    nexus.requestGameInfo(
        Settings::instance().game().plugin()->primarySources().first(), dialog,
        QVariant(), QString());
  } else {
    nexus.requestGameInfo(Settings::instance().game().plugin()->gameShortName(), dialog,
                          QVariant(), QString());
  }
}

void MainWindow::categoriesSaved()
{
  for (auto modName : m_OrganizerCore.modList()->allMods()) {
    auto mod = ModInfo::getByName(modName);
    for (auto category : mod->getCategories()) {
      if (!m_CategoryFactory.categoryExists(category))
        mod->setCategory(category, false);
    }
  }
}

void MainWindow::on_actionNexus_triggered()
{
  const IPluginGame* game = m_OrganizerCore.managedGame();
  QString gameName        = game->gameShortName();
  if (game->gameNexusName().isEmpty() && game->primarySources().count())
    gameName = game->primarySources()[0];
  shell::Open(QUrl(NexusInterface::instance().getGameURL(gameName)));
}

void MainWindow::installTranslator(const QString& name)
{
  QTranslator* translator = new QTranslator(this);
  QString fileName        = name + "_" + m_CurrentLanguage;
  if (!translator->load(fileName, qApp->applicationDirPath() + "/translations")) {
    if (m_CurrentLanguage.contains(QRegularExpression("^.*_(EN|en)(-.*)?$"))) {
      log::debug("localization file %s not found", fileName);
    }  // we don't actually expect localization files for English (en, en-us, en-uk, and
       // any variation thereof)
  }

  qApp->installTranslator(translator);
  m_Translators.push_back(translator);
}

void MainWindow::languageChange(const QString& newLanguage)
{
  for (QTranslator* trans : m_Translators) {
    qApp->removeTranslator(trans);
  }
  m_Translators.clear();

  m_CurrentLanguage = newLanguage;

  installTranslator("qt");
  installTranslator("qtbase");
  installTranslator(ToQString(AppConfig::translationPrefix()));
  installTranslator("uibase");

  // TODO: this will probably be changed once extension come out
  installTranslator("game_gamebryo");
  installTranslator("game_creation");

  for (const QString& fileName : m_PluginContainer.pluginFileNames()) {
    installTranslator(QFileInfo(fileName).baseName());
  }
  ui->retranslateUi(this);
  log::debug("loaded language {}", newLanguage);

  ui->profileBox->setItemText(0, QObject::tr("<Manage...>"));

  createHelpMenu();

  if (m_DownloadsTab) {
    m_DownloadsTab->update();
  }

  ui->listOptionsBtn->setMenu(
      new ModListGlobalContextMenu(m_OrganizerCore, ui->modList, this));
  ui->openFolderMenu->setMenu(openFolderMenu());
}

void MainWindow::originModified(int originID)
{
  FilesOrigin& origin = m_OrganizerCore.directoryStructure()->getOriginByID(originID);
  origin.enable(false);

  DirectoryStats dummy;
  QString path       = QString::fromStdWString(origin.getPath());
  QString modDataDir = m_OrganizerCore.managedGame()->modDataDirectory();
  path               = modDataDir.isEmpty() ? path : path + "/" + modDataDir;
  m_OrganizerCore.directoryStructure()->addFromOrigin(
      origin.getName(), path.toStdWString(), origin.getPriority(), dummy);

  DirectoryRefresher::cleanStructure(m_OrganizerCore.directoryStructure());
}

void MainWindow::updateAvailable()
{
  ui->actionUpdate->setEnabled(true);
  ui->actionUpdate->setToolTip(tr("Update available"));
  ui->statusBar->setUpdateAvailable(true);
}

void MainWindow::motdReceived(const QString& motd)
{
  // don't show motd after 5 seconds, may be annoying. Hopefully the user's
  // internet connection is faster next time
  if (m_StartTime.secsTo(QTime::currentTime()) < 5) {
    uint hash = qHash(motd);
    if (hash != m_OrganizerCore.settings().motdHash()) {
      MotDDialog dialog(motd);
      dialog.exec();
      m_OrganizerCore.settings().setMotdHash(hash);
    }
  }
}

void MainWindow::on_actionUpdate_triggered()
{
  m_OrganizerCore.startMOUpdate();
}

void MainWindow::on_actionExit_triggered()
{
  ExitModOrganizer();
}

void MainWindow::actionEndorseMO()
{
  // Normally this would be the managed game but MO2 is only uploaded to the Skyrim SE
  // site right now
  IPluginGame* game = m_OrganizerCore.getGame("skyrimse");
  if (!game)
    return;

  if (QMessageBox::question(
          this, tr("Endorse Mod Organizer"),
          tr("Do you want to endorse Mod Organizer on %1 now?")
              .arg(NexusInterface::instance().getGameURL(game->gameShortName())),
          QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) {
    NexusInterface::instance().requestToggleEndorsement(
        game->gameShortName(), game->nexusModOrganizerID(),
        m_OrganizerCore.getVersion().string(), true, this, QVariant(), QString());
  }
}

void MainWindow::actionWontEndorseMO()
{
  // Normally this would be the managed game but MO2 is only uploaded to the Skyrim SE
  // site right now
  IPluginGame* game = m_OrganizerCore.getGame("skyrimse");
  if (!game)
    return;

  if (QMessageBox::question(
          this, tr("Abstain from Endorsing Mod Organizer"),
          tr("Are you sure you want to abstain from endorsing Mod Organizer 2?\n"
             "You will have to visit the mod page on the %1 Nexus site to change your "
             "mind.")
              .arg(NexusInterface::instance().getGameURL(game->gameShortName())),
          QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) {
    NexusInterface::instance().requestToggleEndorsement(
        game->gameShortName(), game->nexusModOrganizerID(),
        m_OrganizerCore.getVersion().string(), false, this, QVariant(), QString());
  }
}

void MainWindow::toggleMO2EndorseState()
{
  const auto& s = m_OrganizerCore.settings();

  if (!s.nexus().endorsementIntegration()) {
    ui->actionEndorseMO->setVisible(false);
    return;
  }

  ui->actionEndorseMO->setVisible(true);

  bool enabled = false;
  QString text;

  switch (s.nexus().endorsementState()) {
  case EndorsementState::Accepted: {
    text = tr("Thank you for endorsing MO2! :)");
    break;
  }

  case EndorsementState::Refused: {
    text = tr("Please reconsider endorsing MO2 on Nexus!");
    break;
  }

  case EndorsementState::NoDecision: {
    enabled = true;
    break;
  }
  }

  ui->actionEndorseMO->menu()->setEnabled(enabled);
  ui->actionEndorseMO->setToolTip(text);
  ui->actionEndorseMO->setStatusTip(text);
}

void MainWindow::toggleUpdateAction()
{
  const auto& s = m_OrganizerCore.settings();
  ui->actionUpdate->setVisible(s.checkForUpdates());
}

void MainWindow::updateSortButton()
{
  if (m_OrganizerCore.managedGame()->sortMechanism() !=
      IPluginGame::SortMechanism::NONE) {
    ui->sortButton->setEnabled(true);
    ui->sortButton->setToolTip(tr("Sort the plugins using LOOT."));
  } else {
    ui->sortButton->setDisabled(true);
    ui->sortButton->setToolTip(tr("There is no supported sort mechanism for this game. "
                                  "You will probably have to use a third-party tool."));
  }
}

void MainWindow::nxmEndorsementsAvailable(QVariant userData, QVariant resultData, int)
{
  QVariantList data = resultData.toList();
  std::multimap<QString, std::pair<int, QString>> sorted;
  QStringList games = m_OrganizerCore.managedGame()->validShortNames();
  games += m_OrganizerCore.managedGame()->gameShortName();
  bool searchedMO2NexusGame = false;
  for (auto endorsementData : data) {
    QVariantMap endorsement      = endorsementData.toMap();
    std::pair<int, QString> data = std::make_pair<int, QString>(
        endorsement["mod_id"].toInt(), endorsement["status"].toString());
    sorted.insert(std::pair<QString, std::pair<int, QString>>(
        endorsement["domain_name"].toString(), data));
  }
  for (auto game : games) {
    IPluginGame* gamePlugin = m_OrganizerCore.getGame(game);
    if (gamePlugin != nullptr &&
        gamePlugin->gameShortName().compare("SkyrimSE", Qt::CaseInsensitive) == 0)
      searchedMO2NexusGame = true;
    auto iter = sorted.equal_range(gamePlugin->gameNexusName());
    for (auto result = iter.first; result != iter.second; ++result) {
      std::vector<ModInfo::Ptr> modsList =
          ModInfo::getByModID(result->first, result->second.first);

      for (auto mod : modsList) {
        if (mod->endorsedState() != EndorsedState::ENDORSED_NEVER) {
          if (result->second.second == "Endorsed")
            mod->setIsEndorsed(true);
          else if (result->second.second == "Abstained")
            mod->setNeverEndorse();
          else
            mod->setIsEndorsed(false);
        }
      }

      if (Settings::instance().nexus().endorsementIntegration()) {
        if (result->first == "skyrimspecialedition" &&
            result->second.first == gamePlugin->nexusModOrganizerID()) {
          m_OrganizerCore.settings().nexus().setEndorsementState(
              endorsementStateFromString(result->second.second));

          toggleMO2EndorseState();
        }
      }
    }
  }

  if (!searchedMO2NexusGame && Settings::instance().nexus().endorsementIntegration()) {
    auto gamePlugin = m_OrganizerCore.getGame("SkyrimSE");
    if (gamePlugin) {
      auto iter = sorted.equal_range(gamePlugin->gameNexusName());
      for (auto result = iter.first; result != iter.second; ++result) {
        if (result->second.first == gamePlugin->nexusModOrganizerID()) {
          m_OrganizerCore.settings().nexus().setEndorsementState(
              endorsementStateFromString(result->second.second));

          toggleMO2EndorseState();
          break;
        }
      }
    }
  }
}

void MainWindow::nxmUpdateInfoAvailable(QString gameName, QVariant userData,
                                        QVariant resultData, int)
{
  QString gameNameReal;
  for (IPluginGame* game : m_PluginContainer.plugins<IPluginGame>()) {
    if (game->gameNexusName() == gameName) {
      gameNameReal = game->gameShortName();
      break;
    }
  }
  QVariantList resultList = resultData.toList();

  auto* watcher = new QFutureWatcher<NxmUpdateInfoData>();
  QObject::connect(watcher, &QFutureWatcher<NxmUpdateInfoData>::finished,
                   [this, watcher]() {
                     finishUpdateInfo(watcher->result());
                     watcher->deleteLater();
                   });
  auto future = QtConcurrent::run([=]() {
    return NxmUpdateInfoData{
        gameNameReal,
        ModInfo::filteredMods(gameNameReal, resultList, userData.toBool(), true)};
  });
  watcher->setFuture(future);
  ui->modList->invalidateFilter();
}

void MainWindow::finishUpdateInfo(const NxmUpdateInfoData& data)
{
  if (data.finalMods.empty()) {
    log::info("{}", tr("None of your %1 mods appear to have had recent file updates.")
                        .arg(data.game));
  }

  std::set<std::pair<QString, int>> organizedGames;
  for (auto& mod : data.finalMods) {
    if (mod->canBeUpdated()) {
      organizedGames.insert(
          std::make_pair<QString, int>(mod->gameName().toLower(), mod->nexusId()));
    }
  }

  if (!data.finalMods.empty() && organizedGames.empty())
    log::warn("{}", tr("All of your mods have been checked recently. We restrict "
                       "update checks to help preserve your available API requests."));

  for (const auto& game : organizedGames) {
    NexusInterface::instance().requestUpdates(game.second, this, QVariant(), game.first,
                                              QString());
  }
}

void MainWindow::nxmUpdatesAvailable(QString gameName, int modID, QVariant userData,
                                     QVariant resultData, int requestID)
{
  QVariantMap resultInfo = resultData.toMap();
  QList files            = resultInfo["files"].toList();
  QList fileUpdates      = resultInfo["file_updates"].toList();
  QString gameNameReal;

  for (IPluginGame* game : m_PluginContainer.plugins<IPluginGame>()) {
    if (game->gameNexusName() == gameName) {
      gameNameReal = game->gameShortName();
      break;
    }
  }

  std::vector<ModInfo::Ptr> modsList = ModInfo::getByModID(gameNameReal, modID);

  bool requiresInfo = false;

  for (auto mod : modsList) {
    QString validNewVersion;
    int newModStatus      = -1;
    QString installedFile = QFileInfo(mod->installationFile()).fileName();

    if (!installedFile.isEmpty()) {
      QVariantMap foundFileData;

      // update the file status
      for (auto& file : files) {
        QVariantMap fileData = file.toMap();

        if (fileData["file_name"].toString().compare(installedFile,
                                                     Qt::CaseInsensitive) == 0) {
          foundFileData = fileData;
          newModStatus  = foundFileData["category_id"].toInt();

          if (newModStatus != NexusInterface::FileStatus::OLD_VERSION &&
              newModStatus != NexusInterface::FileStatus::REMOVED &&
              newModStatus != NexusInterface::FileStatus::ARCHIVED) {

            // since the file is still active if there are no updates for it, use this
            // as current version
            validNewVersion = foundFileData["version"].toString();
          }
          break;
        }
      }

      if (foundFileData.isEmpty()) {
        // The file was not listed, the file is likely archived and archived files are
        // being hidden on the mod
        newModStatus = NexusInterface::FileStatus::ARCHIVED_HIDDEN;
      }

      // look for updates of the file
      int currentUpdateId = -1;

      // find installed file ID from the updates list since old filenames are not
      // guaranteed to be unique
      for (auto& updateEntry : fileUpdates) {
        const QVariantMap& updateData = updateEntry.toMap();

        if (installedFile.compare(updateData["old_file_name"].toString(),
                                  Qt::CaseInsensitive) == 0) {
          currentUpdateId = updateData["old_file_id"].toInt();
          break;
        }
      }

      bool foundActiveUpdate = false;

      // there is at least one update
      if (currentUpdateId > 0) {
        bool lookForMoreUpdates = true;

        // follow the update chain until there are no more updates
        while (lookForMoreUpdates) {
          lookForMoreUpdates = false;

          for (auto& updateEntry : fileUpdates) {
            const QVariantMap& updateData = updateEntry.toMap();

            if (currentUpdateId == updateData["old_file_id"].toInt()) {
              currentUpdateId = updateData["new_file_id"].toInt();

              // check if the new file is still active
              for (auto& file : files) {
                const QVariantMap& fileData = file.toMap();

                if (currentUpdateId == fileData["file_id"].toInt()) {
                  int updateStatus = fileData["category_id"].toInt();

                  if (updateStatus != NexusInterface::FileStatus::OLD_VERSION &&
                      updateStatus != NexusInterface::FileStatus::REMOVED &&
                      updateStatus != NexusInterface::FileStatus::ARCHIVED) {

                    // new version is active, so record it
                    validNewVersion   = fileData["version"].toString();
                    foundActiveUpdate = true;
                  }
                  break;
                }
              }

              lookForMoreUpdates = true;
              break;
            }
          }
        }
      }

      // if there were no active direct file updates for the installedFile
      if (!foundActiveUpdate) {
        // get the global mod version in case the file isn't an optional
        if (newModStatus != NexusInterface::FileStatus::OPTIONAL_FILE &&
            newModStatus != NexusInterface::FileStatus::MISCELLANEOUS) {
          requiresInfo = true;
        }
      }
    } else {
      // No installedFile means we don't know what to look at for a version so
      // just get the global mod version
      requiresInfo = true;
    }

    if (newModStatus > 0) {
      mod->setNexusFileStatus(newModStatus);
    }

    if (!validNewVersion.isEmpty()) {
      mod->setNewestVersion(validNewVersion);
      mod->setLastNexusUpdate(QDateTime::currentDateTimeUtc());
    }
  }

  // invalidate the filter to display mods with an update
  ui->modList->invalidateFilter();

  if (requiresInfo) {
    NexusInterface::instance().requestModInfo(gameNameReal, modID, this, QVariant(),
                                              QString());
  }
}

void MainWindow::nxmModInfoAvailable(QString gameName, int modID, QVariant userData,
                                     QVariant resultData, int requestID)
{
  QVariantMap result = resultData.toMap();
  QString gameNameReal;
  bool foundUpdate = false;

  for (IPluginGame* game : m_PluginContainer.plugins<IPluginGame>()) {
    if (game->gameNexusName() == gameName) {
      gameNameReal = game->gameShortName();
      break;
    }
  }

  std::vector<ModInfo::Ptr> modsList = ModInfo::getByModID(gameNameReal, modID);

  for (auto mod : modsList) {
    QDateTime now          = QDateTime::currentDateTimeUtc();
    QDateTime updateTarget = mod->getExpires();

    // if file is still listed as optional or miscellaneous don't update the version as
    // often optional files are left with an older version than the main mod version.
    if (!result["version"].toString().isEmpty() &&
        mod->getNexusFileStatus() != NexusInterface::FileStatus::OPTIONAL_FILE &&
        mod->getNexusFileStatus() != NexusInterface::FileStatus::MISCELLANEOUS) {

      mod->setNewestVersion(result["version"].toString());
      foundUpdate = true;
    }

    // update the LastNexusUpdate time in any case since we did perform the check.
    mod->setLastNexusUpdate(QDateTime::currentDateTimeUtc());

    mod->setNexusDescription(result["description"].toString());

    mod->setNexusCategory(result["category_id"].toInt());

    mod->setAuthor(result["author"].toString());

    mod->setUploader(result["uploaded_by"].toString());

    mod->setUploaderUrl(result["uploaded_users_profile_url"].toString());

    if ((mod->endorsedState() != EndorsedState::ENDORSED_NEVER) &&
        (result.contains("endorsement"))) {
      QVariantMap endorsement   = result["endorsement"].toMap();
      QString endorsementStatus = endorsement["endorse_status"].toString();

      if (endorsementStatus.compare("Endorsed") == 00)
        mod->setIsEndorsed(true);
      else if (endorsementStatus.compare("Abstained") == 00)
        mod->setNeverEndorse();
      else
        mod->setIsEndorsed(false);
    }

    mod->setLastNexusQuery(QDateTime::currentDateTimeUtc());
    mod->setNexusLastModified(
        QDateTime::fromSecsSinceEpoch(result["updated_timestamp"].toInt(), Qt::UTC));

    m_OrganizerCore.modList()->notifyChange(ModInfo::getIndex(mod->name()));
  }

  if (foundUpdate) {
    // invalidate the filter to display mods with an update
    ui->modList->invalidateFilter();
  }
}

void MainWindow::nxmEndorsementToggled(QString, int, QVariant, QVariant resultData, int)
{
  const QMap results = resultData.toMap();

  auto itor = results.find("status");
  if (itor == results.end()) {
    log::error("endorsement response has no status");
    return;
  }

  const auto s = endorsementStateFromString(itor->toString());

  switch (s) {
  case EndorsementState::Accepted: {
    QMessageBox::information(this, tr("Thank you!"),
                             tr("Thank you for your endorsement!"));
    break;
  }

  case EndorsementState::Refused: {
    // don't spam message boxes if the user doesn't want to endorse
    log::info(
        "Mod Organizer will not be endorsed and will no longer ask you to endorse.");
    break;
  }

  case EndorsementState::NoDecision: {
    log::error("bad status '{}' in endorsement response", itor->toString());
    return;
  }
  }

  m_OrganizerCore.settings().nexus().setEndorsementState(s);
  toggleMO2EndorseState();

  if (!disconnect(sender(),
                  SIGNAL(nxmEndorsementToggled(QString, int, QVariant, QVariant, int)),
                  this,
                  SLOT(nxmEndorsementToggled(QString, int, QVariant, QVariant, int)))) {
    log::error("failed to disconnect endorsement slot");
  }
}

void MainWindow::nxmTrackedModsAvailable(QVariant userData, QVariant resultData, int)
{
  QMap<QString, QString> gameNames;
  for (auto game : m_PluginContainer.plugins<IPluginGame>()) {
    gameNames[game->gameNexusName()] = game->gameShortName();
  }

  for (unsigned int i = 0; i < ModInfo::getNumMods(); i++) {
    auto modInfo = ModInfo::getByIndex(i);
    if (modInfo->nexusId() <= 0)
      continue;

    bool found       = false;
    auto resultsList = resultData.toList();
    for (auto item : resultsList) {
      auto results = item.toMap();
      if ((gameNames[results["domain_name"].toString()].compare(
               modInfo->gameName(), Qt::CaseInsensitive) == 0) &&
          (results["mod_id"].toInt() == modInfo->nexusId())) {
        found = true;
        break;
      }
    }

    modInfo->setIsTracked(found);
    modInfo->saveMeta();
  }
}

void MainWindow::nxmDownloadURLs(QString, int, int, QVariant, QVariant resultData, int)
{
  auto servers = m_OrganizerCore.settings().network().servers();

  for (const QVariant& var : resultData.toList()) {
    const QVariantMap map = var.toMap();

    const auto name = map["short_name"].toString();
    const auto isPremium =
        map["name"].toString().contains("Premium", Qt::CaseInsensitive);
    const auto isCDN =
        map["short_name"].toString().contains("CDN", Qt::CaseInsensitive);

    bool found = false;

    for (auto& server : servers) {
      if (server.name() == name) {
        // already exists, update
        server.setPremium(isPremium);
        server.updateLastSeen();
        found = true;
        break;
      }
    }

    if (!found) {
      // new server
      ServerInfo server(name, isPremium, QDate::currentDate(), isCDN ? 1 : 0, {});
      servers.add(std::move(server));
    }
  }

  m_OrganizerCore.settings().network().updateServers(servers);
}

void MainWindow::nxmGameInfoAvailable(QString gameName, QVariant, QVariant resultData,
                                      int)
{
  QVariantMap result          = resultData.toMap();
  QVariantList categories     = result["categories"].toList();
  CategoryFactory& catFactory = CategoryFactory::instance();
  catFactory.reset();
  for (auto category : categories) {
    auto catMap = category.toMap();
    std::vector<CategoryFactory::NexusCategory> nexusCat;
    nexusCat.push_back(CategoryFactory::NexusCategory(catMap["name"].toString(),
                                                      catMap["category_id"].toInt()));
    catFactory.addCategory(catMap["name"].toString(), nexusCat, 0);
  }
}

void MainWindow::nxmRequestFailed(QString gameName, int modID, int, QVariant, int,
                                  int errorCode, const QString& errorString)
{
  if (errorCode == QNetworkReply::ContentAccessDenied ||
      errorCode == QNetworkReply::ContentNotFoundError) {
    log::debug("{}",
               tr("Mod ID %1 no longer seems to be available on Nexus.").arg(modID));

    // update last checked timestamp on orphaned mods as well to avoid repeating
    // requests
    QString gameNameReal;
    for (IPluginGame* game : m_PluginContainer.plugins<IPluginGame>()) {
      if (game->gameNexusName() == gameName) {
        gameNameReal = game->gameShortName();
        break;
      }
    }
    auto orphanedMods = ModInfo::getByModID(gameNameReal, modID);
    for (auto mod : orphanedMods) {
      mod->setLastNexusUpdate(QDateTime::currentDateTimeUtc());
      mod->setLastNexusQuery(QDateTime::currentDateTimeUtc());
    }
  } else {
    MessageDialog::showMessage(
        tr("Error %1: Request to Nexus failed: %2").arg(errorCode).arg(errorString),
        this);
  }
}

BSA::EErrorCode MainWindow::extractBSA(BSA::Archive& archive, BSA::Folder::Ptr folder,
                                       const QString& destination,
                                       QProgressDialog& progress)
{
  QDir().mkdir(destination);
  BSA::EErrorCode result = BSA::ERROR_NONE;
  QString errorFile;

  for (unsigned int i = 0; i < folder->getNumFiles(); ++i) {
    BSA::File::Ptr file = folder->getFile(i);
    BSA::EErrorCode res = archive.extract(file, qUtf8Printable(destination));
    if (res != BSA::ERROR_NONE) {
      reportError(tr("failed to read %1: %2").arg(file->getName().c_str()).arg(res));
      result = res;
    }
    progress.setLabelText(file->getName().c_str());
    progress.setValue(progress.value() + 1);
    QCoreApplication::processEvents();
    if (progress.wasCanceled()) {
      result = BSA::ERROR_CANCELED;
    }
  }

  if (result != BSA::ERROR_NONE) {
    if (QMessageBox::critical(
            this, tr("Error"),
            tr("failed to extract %1 (errorcode %2)").arg(errorFile).arg(result),
            QMessageBox::Ok | QMessageBox::Cancel) == QMessageBox::Cancel) {
      return result;
    }
  }

  for (unsigned int i = 0; i < folder->getNumSubFolders(); ++i) {
    BSA::Folder::Ptr subFolder = folder->getSubFolder(i);
    BSA::EErrorCode res        = extractBSA(
        archive, subFolder,
        destination.mid(0).append("/").append(subFolder->getName().c_str()), progress);
    if (res != BSA::ERROR_NONE) {
      return res;
    }
  }
  return BSA::ERROR_NONE;
}

bool MainWindow::extractProgress(QProgressDialog& progress, int percentage,
                                 std::string fileName)
{
  progress.setLabelText(fileName.c_str());
  progress.setValue(percentage);
  QCoreApplication::processEvents();
  return !progress.wasCanceled();
}

void MainWindow::extractBSATriggered(QTreeWidgetItem* item)
{
  using namespace boost::placeholders;

  QString origin;

  QString targetFolder =
      FileDialogMemory::getExistingDirectory("extractBSA", this, tr("Extract BSA"));
  QStringList archives = {};
  if (!targetFolder.isEmpty()) {
    if (!item->parent()) {
      for (int i = 0; i < item->childCount(); ++i) {
        archives.append(item->child(i)->text(0));
      }
      origin = QDir::fromNativeSeparators(
          ToQString(m_OrganizerCore.directoryStructure()
                        ->getOriginByName(ToWString(item->text(0)))
                        .getPath()));
    } else {
      origin = QDir::fromNativeSeparators(
          ToQString(m_OrganizerCore.directoryStructure()
                        ->getOriginByName(ToWString(item->text(1)))
                        .getPath()));
      archives = QStringList({item->text(0)});
    }

    for (auto archiveName : archives) {
      BSA::Archive archive;
      QString archivePath = QString("%1\\%2").arg(origin).arg(archiveName);
      BSA::EErrorCode result =
          archive.read(archivePath.toLocal8Bit().constData(), true);
      if ((result != BSA::ERROR_NONE) && (result != BSA::ERROR_INVALIDHASHES)) {
        reportError(tr("failed to read %1: %2").arg(archivePath).arg(result));
        return;
      }

      QProgressDialog progress(this);
      progress.setMaximum(100);
      progress.setValue(0);
      progress.show();
      archive.extractAll(
          QDir::toNativeSeparators(targetFolder).toLocal8Bit().constData(),
          boost::bind(&MainWindow::extractProgress, this, boost::ref(progress), _1,
                      _2));
      if (result == BSA::ERROR_INVALIDHASHES) {
        reportError(
            tr("This archive contains invalid hashes. Some files may be broken."));
      }
      archive.close();
    }
  }
}

void MainWindow::on_bsaList_customContextMenuRequested(const QPoint& pos)
{
  QMenu menu;
  menu.addAction(tr("Extract..."), [=, item = ui->bsaList->itemAt(pos)]() {
    extractBSATriggered(item);
  });

  menu.exec(ui->bsaList->viewport()->mapToGlobal(pos));
}

void MainWindow::on_bsaList_itemChanged(QTreeWidgetItem*, int)
{
  m_ArchiveListWriter.write();
  m_CheckBSATimer.start(500);
}

void MainWindow::on_actionNotifications_triggered()
{
  auto future = checkForProblemsAsync();

  future.waitForFinished();

  ProblemsDialog problems(m_PluginContainer, this);
  problems.exec();

  scheduleCheckForProblems();
}

void MainWindow::on_actionChange_Game_triggered()
{
  InstanceManagerDialog dlg(m_PluginContainer, this);
  dlg.exec();
}

void MainWindow::setCategoryListVisible(bool visible)
{
  if (visible) {
    ui->categoriesGroup->show();
    ui->displayCategoriesBtn->setText(ToQString(L"\u00ab"));
  } else {
    ui->categoriesGroup->hide();
    ui->displayCategoriesBtn->setText(ToQString(L"\u00bb"));
  }
}

void MainWindow::on_displayCategoriesBtn_toggled(bool checked)
{
  setCategoryListVisible(checked);
}

void MainWindow::removeFromToolbar(QAction* action)
{
  const auto& title = action->text();
  auto& list        = *m_OrganizerCore.executablesList();

  auto itor = list.find(title);
  if (itor == list.end()) {
    log::warn("removeFromToolbar(): executable '{}' not found", title);
    return;
  }

  itor->setShownOnToolbar(false);
  updatePinnedExecutables();
}

void MainWindow::toolBar_customContextMenuRequested(const QPoint& point)
{
  QAction* action = ui->toolBar->actionAt(point);

  if (action != nullptr) {
    if (action->objectName().startsWith("custom_")) {
      QMenu menu;
      menu.addAction(tr("Remove '%1' from the toolbar").arg(action->text()),
                     [&, action]() {
                       removeFromToolbar(action);
                     });
      menu.exec(ui->toolBar->mapToGlobal(point));
      return;
    }
  }

  // did not click a link button, show the default context menu
  auto* m = createPopupMenu();
  m->exec(ui->toolBar->mapToGlobal(point));
}

Executable* MainWindow::getSelectedExecutable()
{
  const QString name =
      ui->executablesListBox->itemText(ui->executablesListBox->currentIndex());

  try {
    return &m_OrganizerCore.executablesList()->get(name);
  } catch (std::runtime_error&) {
    return nullptr;
  }
}

void MainWindow::on_showHiddenBox_toggled(bool checked)
{
  m_OrganizerCore.downloadManager()->setShowHidden(checked);
}

const char* MainWindow::PATTERN_BACKUP_GLOB = ".????_??_??_??_??_??";
const char* MainWindow::PATTERN_BACKUP_REGEX =
    "\\.(\\d\\d\\d\\d_\\d\\d_\\d\\d_\\d\\d_\\d\\d_\\d\\d)";
const char* MainWindow::PATTERN_BACKUP_DATE = "yyyy_MM_dd_hh_mm_ss";

bool MainWindow::createBackup(const QString& filePath, const QDateTime& time)
{
  QString outPath = filePath + "." + time.toString(PATTERN_BACKUP_DATE);
  if (shellCopy(QStringList(filePath), QStringList(outPath), this)) {
    QFileInfo fileInfo(filePath);
    removeOldFiles(fileInfo.absolutePath(), fileInfo.fileName() + PATTERN_BACKUP_GLOB,
                   10, QDir::Name);
    return true;
  } else {
    return false;
  }
}

void MainWindow::on_saveButton_clicked()
{
  m_OrganizerCore.savePluginList();
  QDateTime now = QDateTime::currentDateTime();
  if (createBackup(m_OrganizerCore.currentProfile()->getPluginsFileName(), now) &&
      createBackup(m_OrganizerCore.currentProfile()->getLoadOrderFileName(), now) &&
      createBackup(m_OrganizerCore.currentProfile()->getLockedOrderFileName(), now)) {
    MessageDialog::showMessage(tr("Backup of load order created"), this);
  }
}

QString MainWindow::queryRestore(const QString& filePath)
{
  QFileInfo pluginFileInfo(filePath);
  QString pattern     = pluginFileInfo.fileName() + ".*";
  QFileInfoList files = pluginFileInfo.absoluteDir().entryInfoList(
      QStringList(pattern), QDir::Files, QDir::Name);

  SelectionDialog dialog(tr("Choose backup to restore"), this);
  QRegularExpression exp(QRegularExpression::anchoredPattern(pluginFileInfo.fileName() +
                                                             PATTERN_BACKUP_REGEX));
  // match orphaned SafeWriteFile temporaries
  QRegularExpression exp2(QRegularExpression::anchoredPattern(
      pluginFileInfo.fileName() + "\\.([A-Za-z]{6})"));
  QRegularExpression exp3(
      QRegularExpression::anchoredPattern(pluginFileInfo.fileName() + "\\.(.*)"));
  for (const QFileInfo& info : boost::adaptors::reverse(files)) {
    auto match  = exp.match(info.fileName());
    auto match2 = exp2.match(info.fileName());
    auto match3 = exp3.match(info.fileName());
    if (match.hasMatch()) {
      QDateTime time = QDateTime::fromString(match.captured(1), PATTERN_BACKUP_DATE);
      dialog.addChoice(time.toString(), "", match.captured(1));
    } else if (match2.hasMatch()) {
      dialog.addChoice(match2.captured(1),
                       tr("This file might be left over following a crash or power "
                          "loss event. Check its contents before restoring."),
                       match2.captured(1));
    } else if (match3.hasMatch()) {
      dialog.addChoice(match3.captured(1), "", match3.captured(1));
    }
  }

  if (dialog.numChoices() == 0) {
    QMessageBox::information(this, tr("No Backups"),
                             tr("There are no backups to restore"));
    return QString();
  }

  if (dialog.exec() == QDialog::Accepted) {
    return dialog.getChoiceData().toString();
  } else {
    return QString();
  }
}

void MainWindow::on_restoreButton_clicked()
{
  QString pluginName = m_OrganizerCore.currentProfile()->getPluginsFileName();
  QString choice     = queryRestore(pluginName);
  if (!choice.isEmpty()) {
    QString loadOrderName = m_OrganizerCore.currentProfile()->getLoadOrderFileName();
    QString lockedName    = m_OrganizerCore.currentProfile()->getLockedOrderFileName();
    if (!shellCopy(pluginName + "." + choice, pluginName, true, this) ||
        !shellCopy(loadOrderName + "." + choice, loadOrderName, true, this) ||
        !shellCopy(lockedName + "." + choice, lockedName, true, this)) {

      const auto e = GetLastError();

      QMessageBox::critical(this, tr("Restore failed"),
                            tr("Failed to restore the backup. Errorcode: %1")
                                .arg(QString::fromStdWString(formatSystemMessage(e))));
    }
    m_OrganizerCore.refreshESPList(true);
  }
}

void MainWindow::on_saveModsButton_clicked()
{
  m_OrganizerCore.currentProfile()->writeModlistNow(true);
  QDateTime now = QDateTime::currentDateTime();
  if (createBackup(m_OrganizerCore.currentProfile()->getModlistFileName(), now)) {
    MessageDialog::showMessage(tr("Backup of mod list created"), this);
  }
}

void MainWindow::on_restoreModsButton_clicked()
{
  QString modlistName = m_OrganizerCore.currentProfile()->getModlistFileName();
  QString choice      = queryRestore(modlistName);
  if (!choice.isEmpty()) {
    if (!shellCopy(modlistName + "." + choice, modlistName, true, this)) {
      const auto e = GetLastError();
      QMessageBox::critical(this, tr("Restore failed"),
                            tr("Failed to restore the backup. Errorcode: %1")
                                .arg(formatSystemMessage(e)));
    }
    m_OrganizerCore.refresh(false);
  }
}

void MainWindow::on_managedArchiveLabel_linkHovered(const QString&)
{
  QToolTip::showText(QCursor::pos(), ui->managedArchiveLabel->toolTip());
}

void MainWindow::dragEnterEvent(QDragEnterEvent* event)
{
  // Accept copy or move drags to the download window. Link drags are not
  // meaningful (Well, they are - we could drop a link in the download folder,
  // but you need privileges to do that).
  if (ui->downloadTab->isVisible() &&
      (event->proposedAction() == Qt::CopyAction ||
       event->proposedAction() == Qt::MoveAction) &&
      event->answerRect().intersects(ui->downloadTab->rect())) {

    // If I read the documentation right, this won't work under a motif windows
    // manager and the check needs to be done at the drop. However, that means
    // the user might be allowed to drop things which we can't sanely process
    QMimeData const* data = event->mimeData();

    if (data->hasUrls()) {
      QStringList extensions =
          m_OrganizerCore.installationManager()->getSupportedExtensions();

      // This is probably OK - scan to see if these are moderately sane archive
      // types
      QList<QUrl> urls = data->urls();
      bool ok          = true;
      for (const QUrl& url : urls) {
        if (url.isLocalFile()) {
          QString local = url.toLocalFile();
          bool fok      = false;
          for (auto ext : extensions) {
            if (local.endsWith(ext, Qt::CaseInsensitive)) {
              fok = true;
              break;
            }
          }
          if (!fok) {
            ok = false;
            break;
          }
        }
      }
      if (ok) {
        event->accept();
      }
    }
  }
}

void MainWindow::dropLocalFile(const QUrl& url, const QString& outputDir, bool move)
{
  QFileInfo file(url.toLocalFile());
  if (!file.exists()) {
    log::warn("invalid source file: {}", file.absoluteFilePath());
    return;
  }
  QString target = outputDir + "/" + file.fileName();
  if (QFile::exists(target)) {
    QMessageBox box(QMessageBox::Question, file.fileName(),
                    tr("A file with the same name has already been downloaded. "
                       "What would you like to do?"));
    box.addButton(tr("Overwrite"), QMessageBox::ActionRole);
    box.addButton(tr("Rename new file"), QMessageBox::YesRole);
    box.addButton(tr("Ignore file"), QMessageBox::RejectRole);

    box.exec();
    switch (box.buttonRole(box.clickedButton())) {
    case QMessageBox::RejectRole:
      return;
    case QMessageBox::ActionRole:
      break;
    default:
    case QMessageBox::YesRole:
      target = m_OrganizerCore.downloadManager()->getDownloadFileName(file.fileName());
      break;
    }
  }

  bool success = false;
  if (move) {
    success = shellMove(file.absoluteFilePath(), target, true, this);
  } else {
    success = shellCopy(file.absoluteFilePath(), target, true, this);
  }
  if (!success) {
    const auto e = GetLastError();
    log::error("file operation failed: {}", formatSystemMessage(e));
  }
}

void MainWindow::dropEvent(QDropEvent* event)
{
  Qt::DropAction action = event->proposedAction();
  QString outputDir     = m_OrganizerCore.downloadManager()->getOutputDirectory();
  if (action == Qt::MoveAction) {
    // Tell windows I'm taking control and will delete the source of a move.
    event->setDropAction(Qt::TargetMoveAction);
  }
  for (const QUrl& url : event->mimeData()->urls()) {
    if (url.isLocalFile()) {
      dropLocalFile(url, outputDir, action == Qt::MoveAction);
    } else {
      m_OrganizerCore.downloadManager()->startDownloadURLs(QStringList() << url.url());
    }
  }
  event->accept();
}

void MainWindow::keyReleaseEvent(QKeyEvent* event)
{
  // if the ui is locked, ignore the ALT key event
  // alt-tabbing out of a game triggers this
  auto& uilocker = UILocker::instance();
  auto& settings = Settings::instance();
  if (!uilocker.locked()) {
    // if the menubar is hidden and showMenuBarOnAlt is true,
    // pressing Alt will make it visible
    if (event->key() == Qt::Key_Alt) {
      bool showMenubarOnAlt = settings.interface().showMenubarOnAlt();
      if (showMenubarOnAlt && !ui->menuBar->isVisible()) {
        ui->menuBar->show();
      }
    }
  }

  QMainWindow::keyReleaseEvent(event);
}