File: lc_blenderpreferences.cpp

package info (click to toggle)
leocad 25.09-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 9,008 kB
  • sloc: cpp: 51,794; xml: 11,265; python: 81; sh: 52; makefile: 16
file content (3882 lines) | stat: -rw-r--r-- 153,279 bytes parent folder | download
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
#include <QFormLayout>
#include <QVBoxLayout>
#include <QGridLayout>
#include <QGroupBox>
#include <QLineEdit>
#include <QCheckBox>
#include <QPushButton>
#include <QComboBox>
#include <QDialogButtonBox>
#include <QLabel>
#include <QProgressBar>
#include <QProcess>
#include <QTimer>
#include <QJsonDocument>
#include <QJsonArray>
#include <QJsonObject>
#include <zlib.h>

#include "lc_blenderpreferences.h"
#include "lc_application.h"
#include "lc_mainwindow.h"
#include "lc_model.h"
#include "lc_colors.h"
#include "lc_colorpicker.h"
#include "lc_profile.h"
#include "lc_http.h"
#include "lc_zipfile.h"
#include "lc_file.h"
#include "lc_qutils.h"
#include "project.h"

#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
using Qt::SkipEmptyParts;
#else
const auto SkipEmptyParts = QString::SplitBehavior::SkipEmptyParts;
#endif

const QLatin1String LineEnding("\r\n");

#define LC_PRODUCTNAME_STR                 "LeoCAD"
#define LC_BLENDER_ADDON                   "ImportLDraw"
#define LC_BLENDER_ADDON_MM                "ImportLDrawMM"
#define LC_BLENDER_ADDON_FILE              "LDrawBlenderRenderAddons.zip"
#define LC_BLENDER_ADDON_INSTALL_FILE      "install_blender_ldraw_addons.py"
#define LC_BLENDER_ADDON_CONFIG_FILE       "LDrawRendererPreferences.ini"
#define LC_BLENDER_ADDON_PARAMS_FILE       "LDrawParameters.lst"

#define LC_BLENDER_ADDON_REPO_STR          "https://github.com/trevorsandy"
#define LC_BLENDER_ADDON_REPO_API_STR      "https://api.github.com/repos/trevorsandy"
#define LC_BLENDER_ADDON_STR               LC_BLENDER_ADDON_REPO_STR "/blenderldrawrender/"
#define LC_BLENDER_ADDON_API_STR           LC_BLENDER_ADDON_REPO_API_STR "/blenderldrawrender/"
#define LC_BLENDER_ADDON_LATEST_URL        LC_BLENDER_ADDON_API_STR "releases/latest"
#define LC_BLENDER_ADDON_URL               LC_BLENDER_ADDON_STR "releases/latest/download/" LC_BLENDER_ADDON_FILE
#define LC_BLENDER_ADDON_SHA_HASH_URL      LC_BLENDER_ADDON_URL ".sha256"

#define LC_THEME_DARK_PALETTE_MIDLIGHT     "#3E3E3E" //  62,  62,  62, 255
#define LC_THEME_DEFAULT_PALETTE_LIGHT     "#AEADAC" // 174, 173, 172, 255
#define LC_THEME_DARK_DECORATE_QUOTED_TEXT "#81D4FA" // 129, 212, 250, 255
#define LC_DISABLED_TEXT                   "#808080" // 128, 128, 128, 255

#define LC_RENDER_IMAGE_MAX_SIZE           32768 // pixels

static QString WhatsThisDescription = QObject::tr(
	"  Blender LDraw Addon Settings\n\n"
	"  You can configure the Blender LDraw addon settings.\n"
	"  - Blender Executable: set Blender path. On entry,\n"
	"    %1 will automatically apply the setting and\n"
	"    attempt the configure the LDraw addon.\n"
	"  - %1 Blender LDraw Addon: you can update the LDraw\n"
	"    addon which will downlod the latest addon or apply\n"
	"    the current addon if the version is the same or newer\n"
	"    than the online version.\n"
	"    You can view the standard output log for the update.\n\n"
	"  - Enabled Addon Modules: check the desired import module.\n"
	"    The LDraw Import TN import module is the long-standing\n"
	"    Blender LDraw import addon, while the LDraw Import MM\n"
	"    addon was recently introduced. The latter addon also\n"
	"    offer LDraw export functionality.\n"
	"    The %1 3D Image Render addon is mandatory but if\n"
	"    no import module is enabled, none of the modules\n"
	"    will be enabled in Blender so it will not be possible\n"
	"    to perform an LDraw model import or render.\n\n"
	"  - LDraw Import Addon Paths: addon paths are specific\n"
	"    to the enabled addon import module.\n"
	"  - LDraw Import Addon Settings: addon settings are\n"
	"    specific to the enabled addon import module.\n"
	"  - Apply: apply the addon path and setting preferences.\n"
	"  - Show/Hide Paths: show or hide the addon paths\n"
	"    display box.\n"
	"  - Reset: reset the addon path and setting preferences.\n"
	"    You can select how to reset addon settings.\n"
	"    The choice is since last apply or system default.\n\n"
	"  You can see the specific description of each setting\n"
	"  if you hover over the setting to display its tooltip.\n\n"
	"  Image Width, Image Height and Render Percentage are\n"
	"  always updated from the current step model when the\n"
	"  this dialog is opened. These settngs can be manually\n"
	"  overridden, Also, when Crop Image is checked the\n"
	"  current step cropped image width and height is\n"
	"  calculated and and used\n\n"
	"  Use the dialogue window scroll bar to access the\n"
	"  complete selection of addon settings.\n")
.arg(QLatin1String(LC_PRODUCTNAME_STR));

lcBlenderPreferences::BlenderPaths  lcBlenderPreferences::mBlenderPaths [NUM_PATHS];
lcBlenderPreferences::BlenderPaths  lcBlenderPreferences::mDefaultPaths [NUM_PATHS] =
{
	/*                             Key:                  MM Key:               Value:             Label:                                   Tooltip (Description):*/
	/* 0   PATH_BLENDER        */ {"blenderpath",        "blenderpath",        "",    QObject::tr("Blender Path"),             QObject::tr("Full file path to Blender application executable")},
	/* 1   PATH_BLENDFILE      */ {"blendfile",          "blendfile",          "",    QObject::tr("Blendfile Path"),           QObject::tr("Full file path to a supplement .blend file - specify to append additional settings")},
	/* 2   PATH_ENVIRONMENT    */ {"environmentfile",    "environmentfile",    "",    QObject::tr("Environment Texture Path"), QObject::tr("Full file path to .exr environment texture file - specify if not using default bundled in addon")},
	/* 3   PATH_LDCONFIG       */ {"customldconfigfile", "customldconfigfile", "",    QObject::tr("Custom LDConfig Path"),     QObject::tr("Full file path to custom LDConfig file - specify if not %1 alternate LDConfig file").arg(LC_PRODUCTNAME_STR)},
	/* 4   PATH_LDRAW          */ {"ldrawdirectory",     "ldrawpath",          "",    QObject::tr("LDraw Directory"),          QObject::tr("Full directory path to the LDraw parts library (download from https://library.ldraw.org)")},
	/* 5   PATH_LSYNTH         */ {"lsynthdirectory",    "",                   "",    QObject::tr("LSynth Directory"),         QObject::tr("Full directory path to LSynth primitives - specify if not using default bundled in addon")},
	/* 6   PATH_STUD_LOGO      */ {"studlogodirectory",  "",                   "",    QObject::tr("Stud Logo Directory"),      QObject::tr("Full directory path to stud logo primitives - if stud logo enabled, specify if unofficial parts not used or not using default bundled in addon")},
	/* 7   PATH_STUDIO_LDRAW   */ {"",                   "studioldrawpath",    "",    QObject::tr("Stud.io LDraw Path"),       QObject::tr("Full filepath to the Stud.io LDraw Parts Library (download from https://www.bricklink.com/v3/studio/download.page)")},
	/* 8   PATH_STUDIO_CUSTOM_PARTS */ {"",              "studiocustompartspath", "", QObject::tr("Stud.io Custom Parts Path"),QObject::tr("Full filepath to the Stud.io LDraw Custom Parts")}
};

lcBlenderPreferences::BlenderSettings  lcBlenderPreferences::mBlenderSettings [NUM_SETTINGS];
lcBlenderPreferences::BlenderSettings  lcBlenderPreferences::mDefaultSettings [NUM_SETTINGS] =
{
	/*                                   Key:                              Value:                  Label                                  Tooltip (Description)*/
	/* 0   LBL_ADD_ENVIRONMENT       */ {"addenvironment",                 "1",        QObject::tr("Add Environment"),        QObject::tr("Adds a ground plane and environment texture (affects 'Photo-realistic' look only)")},
	/* 1   LBL_ADD_GAPS              */ {"gaps",                           "0",        QObject::tr("Add Part Gap"),           QObject::tr("Add a small space between each part")},
	/* 2   LBL_BEVEL_EDGES           */ {"beveledges",                     "1",        QObject::tr("Bevel Edges"),            QObject::tr("Adds a Bevel modifier for rounding off sharp edges")},
	/* 3   LBL_BLENDFILE_TRUSTED     */ {"blendfiletrusted",               "0",        QObject::tr("Trusted Blend File"),     QObject::tr("Specify whether to treat the .blend file as being loaded from a trusted source")},
	/* 4   LBL_CROP_IMAGE            */ {"cropimage",                      "0",        QObject::tr("Crop Image"),             QObject::tr("Crop the image border at opaque content. Requires transparent background set to True")},
	/* 5   LBL_CURVED_WALLS          */ {"curvedwalls",                    "1",        QObject::tr("Curved Walls"),           QObject::tr("Makes surfaces look slightly concave, for interesting reflections")},
	/* 6   LBL_FLATTEN_HIERARCHY     */ {"flattenhierarchy",               "0",        QObject::tr("Flatten Hierarchy"),      QObject::tr("In Scene Outline, all parts are placed directly below the root - there's no tree of submodels")},
	/* 7   LBL_IMPORT_CAMERAS        */ {"importcameras",                  "1",        QObject::tr("Import Cameras"),         QObject::tr("%1 can specify camera definitions within the ldraw data. Choose to load them or ignore them.").arg(LC_PRODUCTNAME_STR)},
	/* 8   LBL_IMPORT_LIGHTS         */ {"importlights",                   "1",        QObject::tr("Import Lights"),          QObject::tr("%1 can specify point and sunlight definitions within the ldraw data. Choose to load them or ignore them.").arg(LC_PRODUCTNAME_STR)},
	/* 9   LBL_INSTANCE_STUDS        */ {"instancestuds",                  "0",        QObject::tr("Instance Studs"),         QObject::tr("Creates a Blender Object for each and every stud (WARNING: can be slow to import and edit in Blender if there are lots of studs)")},
	/*10   LBL_KEEP_ASPECT_RATIO     */ {"keepaspectratio",                "1",        QObject::tr("Keep Aspect Ratio"),      QObject::tr("Maintain the aspect ratio when resizing the output image - this attribute is not passed to Blender")},
	/*11   LBL_LINK_PARTS            */ {"linkparts",                      "1",        QObject::tr("Link Like Parts"),        QObject::tr("Identical parts (of the same type and colour) share the same mesh")},
	/*12   LBL_MINIFIG_HIERARCHY     */ {"minifighierarchy",               "1",        QObject::tr("Parent Minifigs"),        QObject::tr("Parts of minifigs are automatically parented to each other in a hierarchy")},
	/*13   LBL_NUMBER_NODES          */ {"numbernodes",                    "1",        QObject::tr("Number Objects"),         QObject::tr("Each object has a five digit prefix eg. 00001_car. This keeps the list in it's proper order")},
	/*14   LBL_OVERWRITE_IMAGE       */ {"overwriteimage",                 "1",        QObject::tr("Overwrite Image"),        QObject::tr("Specify whether to overwrite an existing rendered image file")},
	/*15   LBL_OVERWRITE_MATERIALS   */ {"overwriteexistingmaterials",     "0",        QObject::tr("Use Existing Material"),  QObject::tr("Overwrite existing material with the same name")},
	/*16   LBL_OVERWRITE_MESHES      */ {"overwriteexistingmeshes",        "0",        QObject::tr("Use Existing Mesh"),      QObject::tr("Overwrite existing mesh with the same name")},
	/*17   LBL_POSITION_CAMERA       */ {"positioncamera",                 "1",        QObject::tr("Position Camera"),        QObject::tr("Position the camera to show the whole model")},
	/*18   LBL_REMOVE_DOUBLES        */ {"removedoubles",                  "1",        QObject::tr("No Duplicate Vertices"),  QObject::tr("Remove duplicate vertices (recommended)")},
	/*19   LBL_RENDER_WINDOW         */ {"renderwindow",                   "1",        QObject::tr("Display Render Window"),  QObject::tr("Specify whether to display the render window during Blender user interface image file render")},
	/*10   LBL_USE_ARCHIVE_LIBRARY   */ {"usearchivelibrary",              "0",        QObject::tr("Use Archive Libraries"),  QObject::tr("Add any archive (zip) libraries in the LDraw file path to the library search list - impacts performance")},
	/*21   LBL_SEARCH_ADDL_PATHS     */ {"searchadditionalpaths",          "0",        QObject::tr("Search Additional Paths"),QObject::tr("Specify whether to search additional LDraw paths")},
	/*22   LBL_SMOOTH_SHADING        */ {"smoothshading",                  "1",        QObject::tr("Smooth Shading"),         QObject::tr("Smooth faces and add an edge-split modifier (recommended)")},
	/*23   LBL_TRANSPARENT_BACKGROUND*/ {"transparentbackground",          "0",        QObject::tr("Transparent Background"), QObject::tr("Specify whether to render a background (affects 'Photo-realistic look only)")},
	/*24   LBL_UNOFFICIAL_PARTS      */ {"useunofficialparts",             "1",        QObject::tr("Use Unofficial Parts"),   QObject::tr("Specify whether to use parts from the LDraw unofficial parts library path")},
	/*25   LBL_USE_LOGO_STUDS        */ {"uselogostuds",                   "1",        QObject::tr("Use Logo Studs"),         QObject::tr("Shows the LEGO logo on each stud (at the expense of some extra geometry and import time)")},
	/*26   LBL_VERBOSE               */ {"verbose",                        "1",        QObject::tr("Verbose output"),         QObject::tr("Output all messages while working, else only show warnings and errors")},

	/*27/0 LBL_BEVEL_WIDTH           */ {"bevelwidth",                     "0.5",      QObject::tr("Bevel Width"),            QObject::tr("Width of the bevelled edges")},
	/*28/1 LBL_CAMERA_BORDER_PERCENT */ {"cameraborderpercentage",         "5.0",      QObject::tr("Camera Border Percent"),  QObject::tr("When positioning the camera, include a (percentage) border leeway around the model in the rendered image")},
	/*29/2 LBL_DEFAULT_COLOUR        */ {"defaultcolour",                  "16",       QObject::tr("Default Colour"),         QObject::tr("Sets the default part colour using LDraw colour code")},
	/*20/3 LBL_GAPS_SIZE             */ {"realgapwidth",                   "0.0002",   QObject::tr("Gap Width"),              QObject::tr("Amount of space between each part (default 0.2mm)")},
	/*31/4 LBL_IMAGE_WIDTH           */ {"resolutionwidth",                "800",      QObject::tr("Image Width"),            QObject::tr("Sets the rendered image width in pixels - from current step image, label shows config setting.")},
	/*32/5 LBL_IMAGE_HEIGHT          */ {"resolutionheight",               "600",      QObject::tr("Image Height"),           QObject::tr("Sets the rendered image height in pixels - from current step image, label shows config setting.")},
	/*33/6 LBL_IMAGE_SCALE           */ {"realscale",                      "1.0",      QObject::tr("Image Scale"),            QObject::tr("Sets a scale for the model (1.0 = real life scale)")},
	/*34/6 LBL_RENDER_PERCENTAGE     */ {"renderpercentage",               "100",      QObject::tr("Render Percentage"),      QObject::tr("Sets the rendered image percentage scale for its pixel resolution - updated from current step, label shows config setting.")},

	/*35/0 LBL_COLOUR_SCHEME         */ {"usecolourscheme",                "lgeo",     QObject::tr("Colour Scheme"),          QObject::tr("Colour scheme options - Realistic (lgeo), Original (LDConfig), Alternate (LDCfgalt), Custom (User Defined)")},
	/*36/1 LBL_FLEX_PARTS_SOURCE     */ {"uselsynthparts",                 "1",        QObject::tr("Flex Parts Source"),      QObject::tr("Source used to create flexible parts - string, hoses etc. (LDCad, LSynth or both")},
	/*27/2 LBL_LOGO_STUD_VERSION     */ {"logostudversion",                "4",        QObject::tr("Logo Version"),           QObject::tr("Which version of the logo to use ('3' (flat), '4' (rounded) or '5' (subtle rounded))")},
	/*38/3 LBL_LOOK                  */ {"uselook",                        "normal",   QObject::tr("Look"),                   QObject::tr("Photo-realistic or Schematic 'Instruction' look")},
	/*39/4 LBL_POSITION_OBJECT       */ {"positionobjectongroundatorigin", "1",        QObject::tr("Position Object"),        QObject::tr("The object is centred at the origin, and on the ground plane")},
	/*40/5 LBL_RESOLUTION            */ {"resolution",                     "Standard", QObject::tr("Resolution"),             QObject::tr("Resolution of part primitives, ie. how much geometry they have")},
	/*41/6 LBL_RESOLVE_NORMALS       */ {"resolvenormals",                 "guess",    QObject::tr("Resolve Normals"),        QObject::tr("Some older LDraw parts have faces with ambiguous normals, this specifies what do do with them")}
};

lcBlenderPreferences::ComboItems  lcBlenderPreferences::mComboItems [NUM_COMBO_ITEMS] =
{
	/*    FIRST item set as default        Data                                  Item:   */
	/* 00 LBL_COLOUR_SCHEME            */ {"lgeo|ldraw|alt|custom",  QObject::tr("Realistic Colours|Original LDraw Colours|Alternate LDraw Colours|Custom Colours")},
	/* 01 LBL_FLEX_PARTS_SOURCE (t/f)  */ {"1|0|1",                  QObject::tr("LSynth|LDCad|LDCad and LSynth")},
	/* 02 LBL_LOGO_STUD_VERSION        */ {"4|3|5",                  QObject::tr("Rounded(4)|Flattened(3)|Subtle Rounded(5)")},
	/* 03 LBL_LOOK                     */ {"normal|instructions",    QObject::tr("Photo Realistic|Lego Instructions")},
	/* 04 LBL_POSITION_OBJECT (t/f)    */ {"1|0",                    QObject::tr("Centered At Origin On Ground|Centered At Origin")},
	/* 05 LBL_RESOLUTION               */ {"Standard|High|Low",      QObject::tr("Standard Primitives|High Resolution Primitives|Low Resolution Primitives")},
	/* 06 LBL_RESOLVE_NORMALS          */ {"guess|double",           QObject::tr("Recalculate Normals|Two Faces Back To Back")}
};

lcBlenderPreferences::BlenderSettings  lcBlenderPreferences::mBlenderSettingsMM [NUM_SETTINGS_MM];
lcBlenderPreferences::BlenderSettings  lcBlenderPreferences::mDefaultSettingsMM [NUM_SETTINGS_MM] =
{
	/*                                                Key:                             Value:                    Label                                    Tooltip (Description)*/
	/* 00 LBL_ADD_ENVIRONMENT_MM                  */ {"addenvironment",                "1",          QObject::tr("Add Environment"),          QObject::tr("Adds a ground plane and environment texture")},
	/* 01 LBL_BEVEL_EDGES_MM                      */ {"beveledges",                    "0",          QObject::tr("Bevel Edgest"),             QObject::tr("Bevel edges. Can cause some parts to render incorrectly")},
	/* 02 LBL_BLEND_FILE_TRUSTED_MM               */ {"blendfiletrusted",              "0",          QObject::tr("Trusted Blend File"),       QObject::tr("Specify whether to treat the .blend file as being loaded from a trusted source")},
#ifdef Q_OS_LINUX
	/* 03 LBL_CASE_SENSITIVE_FILESYSTEM           */ {"casesensitivefilesystem",       "1",          QObject::tr("Case-sensitive Filesystem"),QObject::tr("Filesystem is case sensitive. Defaults to true on Linux.")},
#else
	/* 03 LBL_CASE_SENSITIVE_FILESYSTEM           */ {"casesensitivefilesystem",       "0",          QObject::tr("Case-sensitive Filesystem"),QObject::tr("Filesystem case sensitive defaults to false Windows and MacOS. Set true if LDraw path set to case-sensitive on case-insensitive filesystem.")},
#endif
	/* 04 LBL_CROP_IMAGE_MM                       */ {"cropimage",                     "0",          QObject::tr("Crop Image"),               QObject::tr("Crop the image border at opaque content. Requires transparent background set to True")},
	/* 05 LBL_DISPLAY_LOGO                        */ {"displaylogo",                   "1",          QObject::tr("Display Logo"),             QObject::tr("Display the logo on the stud")},
	/* 06 LBL_IMPORT_CAMERAS_MM                   */ {"importcameras",                 "1",          QObject::tr("Import Cameras"),           QObject::tr("%1 can specify camera definitions within the ldraw data. Choose to load them or ignore them.").arg(LC_PRODUCTNAME_STR)},
	/* 07 LBL_IMPORT_EDGES                        */ {"importedges",                   "0",          QObject::tr("Import Edges"),             QObject::tr("Import LDraw edges as edges")},
	/* 08 LBL_IMPORT_LIGHTS_MM                    */ {"importlights",                  "1",          QObject::tr("Import Lights"),            QObject::tr("%1 can specify point and sunlight definitions within the ldraw data. Choose to load them or ignore them.").arg(LC_PRODUCTNAME_STR)},
	/* 09 LBL_KEEP_ASPECT_RATIO_MM                */ {"keepaspectratio",               "1",          QObject::tr("Keep Aspect Ratio"),        QObject::tr("Maintain the aspect ratio when resizing the output image - this attribute is not passed to Blender")},
	/* 10 LBL_MAKE_GAPS                           */ {"makegaps",                      "1",          QObject::tr("Make Gaps"),                QObject::tr("Make small gaps between bricks. A small gap is more realistic")},
	/* 11 LBL_META_BFC                            */ {"metabfc",                       "1",          QObject::tr("BFC"),                      QObject::tr("Process LDraw Back Face Culling meta commands")},
	/* 12 LBL_META_CLEAR                          */ {"metaclear",                     "0",          QObject::tr("CLEAR Command"),            QObject::tr("Hides all parts in the timeline up to where this command is encountered")},
	/* 13 LBL_META_GROUP                          */ {"metagroup",                     "1",          QObject::tr("GROUP Command"),            QObject::tr("Process GROUP meta commands")},
	/* 14 LBL_META_PAUSE                          */ {"metapause",                     "0",          QObject::tr("PAUSE Command"),            QObject::tr("Not implemented")},
	/* 15 LBL_META_PRINT_WRITE                    */ {"metaprintwrite",                "0",          QObject::tr("PRINT/WRITE Command"),      QObject::tr("Prints PRINT/WRITE META commands to the system console.")},
	/* 16 LBL_META_SAVE                           */ {"metasave",                      "0",          QObject::tr("SAVE Command"),             QObject::tr("Not implemented")},
	/* 17 LBL_META_STEP                           */ {"metastep",                      "0",          QObject::tr("STEP Command"),             QObject::tr("Adds a keyframe that shows the part at the moment in the timeline")},
	/* 18 LBL_META_STEP_GROUPS                    */ {"metastepgroups",                "0",          QObject::tr("STEP Groups"),              QObject::tr("Create collection for individual steps")},
	/* 19 LBL_META_TEXMAP                         */ {"metatexmap",                    "1",          QObject::tr("TEXMAP and DATA Command"),  QObject::tr("Process TEXMAP and DATA meta commands")},
	/* 20 LBL_NO_STUDS                            */ {"nostuds",                       "0",          QObject::tr("No Studs"),                 QObject::tr("Don't import studs")},
	/* 21 LBL_OVERWRITE_IMAGE_MM                  */ {"overwriteimage",                "1",          QObject::tr("Overwrite Image"),          QObject::tr("Specify whether to overwrite an existing rendered image file")},
	/* 22 LBL_POSITION_CAMERA_MM                  */ {"positioncamera",                "1",          QObject::tr("Position Camera"),          QObject::tr("Position the camera to show the whole model")},
	/* 23 LBL_PARENT_TO_EMPTY                     */ {"parenttoempty",                 "1",          QObject::tr("Parent To Empty"),          QObject::tr("Parent the model to an empty")},
	/* 24 LBL_PREFER_STUDIO                       */ {"preferstudio",                  "0",          QObject::tr("Prefer Stud.io Library"),   QObject::tr("Search for parts in Stud.io library first")},
	/* 25 LBL_PREFER_UNOFFICIAL                   */ {"preferunofficial",              "0",          QObject::tr("Prefer Unofficial Parts"),  QObject::tr("Search for unofficial parts first")},
	/* 26 LBL_PROFILE                             */ {"profile",                       "0",          QObject::tr("Profile"),                  QObject::tr("Profile import performance")},
	/* 27 LBL_RECALCULATE_NORMALS                 */ {"recalculatenormals",            "0",          QObject::tr("Recalculate Normals"),      QObject::tr("Recalculate normals. Not recommended if BFC processing is active")},
	/* 28 LBL_REMOVE_DOUBLES_MM                   */ {"removedoubles",                 "1",          QObject::tr("No Duplicate Vertices"),    QObject::tr("Merge vertices that are within a certain distance.")},
	/* 29 LBL_RENDER_WINDOW_MM                    */ {"renderwindow",                  "1",          QObject::tr("Display Render Window"),    QObject::tr("Specify whether to display the render window during Blender user interface image file render")},
	/* 30 LBL_SEARCH_ADDL_PATHS_MM                */ {"searchadditionalpaths",         "0",          QObject::tr("Search Additional Paths"),  QObject::tr("Specify whether to search additional LDraw paths")},
	/* 31 LBL_SETEND_FRAME                        */ {"setendframe",                   "1",          QObject::tr("Set Step End Frame"),       QObject::tr("Set the end frame to the last step")},
	/* 32 LBL_SET_TIMELINE_MARKERS                */ {"settimelinemarkers",            "0",          QObject::tr("Set Timeline Markers"),     QObject::tr("Set timeline markers for meta commands")},
	/* 33 LBL_SHADE_SMOOTH                        */ {"shadesmooth",                   "1",          QObject::tr("Shade Smooth"),             QObject::tr("Use flat or smooth shading for part faces")},
	/* 34 LBL_TRANSPARENT_BACKGROUND_MM           */ {"transparentbackground",         "0",          QObject::tr("Transparent Background"),   QObject::tr("Specify whether to render a background")},
	/* 35 LBL_TREAT_SHORTCUT_AS_MODEL             */ {"treatshortcutasmodel",          "0",          QObject::tr("Treat Shortcuts As Models"),QObject::tr("Split shortcut parts into their constituent pieces as if they were models")},
	/* 36 LBL_TRIANGULATE                         */ {"triangulate",                   "0",          QObject::tr("Triangulate Faces"),        QObject::tr("Triangulate all faces")},
	/* 37 LBL_USE_ARCHIVE_LIBRARY_MM              */ {"usearchivelibrary",             "0",          QObject::tr("Use Archive Libraries"),    QObject::tr("Add any archive (zip) libraries in the LDraw file path to the library search list - impacts performance")},
	/* 38 LBL_USE_FREESTYLE_EDGES                 */ {"usefreestyleedges",             "0",          QObject::tr("Use Freestyle Edges"),      QObject::tr("Render LDraw edges using freestyle")},
	/* 39 LBL_VERBOSE_MM                          */ {"verbose",                       "1",          QObject::tr("Verbose output"),           QObject::tr("Output all messages while working, else only show warnings and errors")},

	/* 40/00 LBL_BEVEL_SEGMENTS                   */ {"bevelsegments",                 "4",          QObject::tr("Bevel Segments"),           QObject::tr("Bevel segments")},
	/* 41/01 LBL_BEVEL_WEIGHT                     */ {"bevelweight",                   "0.03",       QObject::tr("Bevel Weight"),             QObject::tr("Bevel weight")},
	/* 42/02 LBL_BEVEL_WIDTH_MM                   */ {"bevelwidth",                    "0.3",        QObject::tr("Bevel Width"),              QObject::tr("Width of the bevelled edges")},
	/* 43/03 LBL_CAMERA_BORDER_PERCENT_MM         */ {"cameraborderpercent",           "5",          QObject::tr("Camera Border Percent"),    QObject::tr("When positioning the camera, include a (percentage) border around the model in the render")},
	/* 44/04 LBL_FRAMES_PER_STEP                  */ {"framesperstep",                 "3",          QObject::tr("Frames Per Step"),          QObject::tr("Frames per step")},
	/* 45/05 LBL_GAP_SCALE                        */ {"gapscale",                      "0.997",      QObject::tr("Gap Scale"),                QObject::tr("Scale individual parts by this much to create the gap")},
	/* 46/06 LBL_IMPORT_SCALE                     */ {"importscale",                   "0.02",       QObject::tr("Import Scale"),             QObject::tr("What scale to import at. Full scale is 1.0 and is so huge that it is unwieldy in the viewport")},
	/* 47/07 LBL_MERGE_DISTANCE                   */ {"mergedistance",                 "0.05",       QObject::tr("Merge Distance"),           QObject::tr("Maximum distance between elements to merge")},
	/* 48/08 LBL_RENDER_PERCENTAGE_MM             */ {"renderpercentage",              "100",        QObject::tr("Render Percentage"),        QObject::tr("Sets the rendered image percentage scale for its pixel resolution - updated from current step, label shows config setting.")},
	/* 49/09 LBL_RESOLUTION_WIDTH                 */ {"resolutionwidth",               "800",        QObject::tr("Image Width"),              QObject::tr("Sets the rendered image width in pixels - from current step image, label shows config setting.")},
	/* 50/10 LBL_RESOLUTION_HEIGHT                */ {"resolutionheight",              "600",        QObject::tr("Image Height"),             QObject::tr("Sets the rendered image height in pixels - from current step image, label shows config setting.")},
	/* 51/11 LBL_STARTING_STEP_FRAME              */ {"startingstepframe",             "1",          QObject::tr("Starting Step Frame"),      QObject::tr("Frame to add the first STEP meta command")},

	/* 52/00 LBL_CHOSEN_LOGO                      */ {"chosenlogo",                    "logo3",      QObject::tr("Chosen Logo"),              QObject::tr("Which logo to display. logo and logo2 aren't used and are only included for completeness")},
	/* 53/01 LBL_COLOUR_SCHEME_MM                 */ {"usecolourscheme",               "alt",        QObject::tr("Colour Scheme"),            QObject::tr("Colour scheme options - Realistic (lgeo), Original (LDConfig), Alternate (LDCfgalt), Custom (User Defined)")},
	/* 54/02 LBL_RESOLUTION_MM                    */ {"resolution",                    "Standard",   QObject::tr("Resolution"),               QObject::tr("Resolution of part primitives, ie. how much geometry they have")},
	/* 55/03 LBL_SCALE_STRATEGY                   */ {"scalestrategy",                 "mesh",       QObject::tr("How To Scale Parts"),       QObject::tr("Apply import scaling to mesh - Recommended for rendering, Apply import scaling to object - Recommended for part editing")},
	/* 56/04 LBL_SMOOTH_TYPE                      */ {"smoothtype",                    "edge_split", QObject::tr("Smooth Type"),              QObject::tr("Use either autosmooth or an edge split modifier to smooth part faces")}
};

lcBlenderPreferences::ComboItems  lcBlenderPreferences::mComboItemsMM [NUM_COMBO_ITEMS_MM] =
{
	/*    FIRST item set as default        Data                                  Item: */
	/* 00 LBL_CHOSEN_LOGO              */ {"logo3|logo4|logo5",                  QObject::tr("Raised flattened logo geometry(3)|Raised rounded logo geometry(4)|Subtle rounded logo geometry(5)")},
	/* 01 LBL_COLOUR_SCHEME_MM         */ {"lgeo|ldraw|alt|custom",              QObject::tr("Realistic Colours|Original LDraw Colours|Alternate LDraw Colours|Custom Colours")},
	/* 02 LBL_RESOLUTION_MM            */ {"Low|Standard|High",                  QObject::tr("Low Resolution Primitives|Standard Primitives|High Resolution Primitives")},
	/* 03 LBL_SCALE_STRATEGY           */ {"mesh|object",                        QObject::tr("Scale Mesh|Scale Object")},
	/* 04 LBL_SMOOTH_TYPE              */ {"edge_split|auto_smooth|bmesh_split", QObject::tr("Smooth part faces with edge split modifier|Auto-smooth part faces|Split during initial mesh processing")}
};

lcBlenderPreferences* gAddonPreferences;

enum AddonEnc
{
	ADDON_EXTRACT,
	ADDON_DOWNLOAD,
	ADDON_NO_ACTION,
	ADDON_CANCELED,
	ADDON_FAIL
};

lcBlenderPreferencesDialog::lcBlenderPreferencesDialog(int Width, int Height, double Scale, QWidget* Parent)
	: QDialog(Parent)
{
	setWindowTitle(tr("Blender LDraw Addon Settings"));

	QVBoxLayout* Layout = new QVBoxLayout(this);
	setLayout(Layout);

	QGroupBox* Box = new QGroupBox(this);
	Layout->addWidget(Box);

	mPreferences = new lcBlenderPreferences(Width,Height,Scale,Box);

	QDialogButtonBox* ButtonBox;
	ButtonBox = new QDialogButtonBox(this);
	mApplyButton = new QPushButton(tr("Apply"), ButtonBox);
	mApplyButton->setToolTip(tr("Apply addon paths and settings preferences"));
	mApplyButton->setEnabled(false);
	ButtonBox->addButton(mApplyButton, QDialogButtonBox::ActionRole);
	connect(mApplyButton,SIGNAL(clicked()), this, SLOT(accept()));

	mPathsButton = new QPushButton(tr("Hide Paths"), ButtonBox);
	mPathsButton->setToolTip(tr("Hide addon path preferences dialog"));
	ButtonBox->addButton(mPathsButton,QDialogButtonBox::ActionRole);
	connect(mPathsButton,SIGNAL(clicked()), this, SLOT(ShowPathsGroup()));

	mResetButton = new QPushButton(tr("Reset"), ButtonBox);
	mResetButton->setEnabled(false);
	mResetButton->setToolTip(tr("Reset addon paths and settings preferences"));
	ButtonBox->addButton(mResetButton,QDialogButtonBox::ActionRole);
	connect(mResetButton,SIGNAL(clicked()), this, SLOT(ResetSettings()));

	ButtonBox->addButton(QDialogButtonBox::Cancel);
	connect(ButtonBox,SIGNAL(rejected()), this, SLOT(reject()));

	if (!QFileInfo(lcGetProfileString(LC_PROFILE_BLENDER_LDRAW_CONFIG_PATH)).isReadable() && !lcGetProfileString(LC_PROFILE_BLENDER_IMPORT_MODULE).isEmpty())
		mApplyButton->setEnabled(true);

	connect(mPreferences,SIGNAL(SettingChangedSig(bool)), this, SLOT(EnableButton(bool)));

	Layout->addWidget(ButtonBox);

	setMinimumSize(Box->sizeHint().width() + 50, 500);

	setSizeGripEnabled(true);

	setModal(true);
}

lcBlenderPreferencesDialog::~lcBlenderPreferencesDialog()
{
}

bool lcBlenderPreferencesDialog::GetBlenderPreferences(int& Width, int& Height, double & Scale, QWidget* Parent)
{
	lcBlenderPreferencesDialog* Dialog = new lcBlenderPreferencesDialog(Width,Height,Scale,Parent);

	bool Ok = Dialog->exec() == QDialog::Accepted;

	if (Ok)
	{
		Dialog->mPreferences->Apply(Ok);
		Width = Dialog->mPreferences->mImageWidth;
		Height = Dialog->mPreferences->mImageHeight;
		Scale = Dialog->mPreferences->mScale;
	}

	return Ok;
}

void lcBlenderPreferencesDialog::ShowPathsGroup()
{
	const QString Display = mPathsButton->text().startsWith("Hide") ? tr("Show") : tr("Hide");
	mPathsButton->setText(tr("%1 Paths").arg(Display));
	mPathsButton->setToolTip(tr("%1 addon path preferences dialog").arg(Display));
	mPreferences->ShowPathsGroup();
}

void lcBlenderPreferencesDialog::EnableButton(bool Change)
{
	if (Change)
	{
		mApplyButton->setEnabled(true);
		mResetButton->setEnabled(true);
	}
	mPathsButton->setText(tr("Hide Paths"));
	mPathsButton->setToolTip(tr("Hide addon path preferences dialog"));
}

void lcBlenderPreferencesDialog::ResetSettings()
{
	mPreferences->ResetSettings();
	mApplyButton->setEnabled(false);
}

void lcBlenderPreferencesDialog::accept()
{
	mApplyButton->setEnabled(false);
	mPreferences->Apply(QDialog::Accepted);
	QDialog::accept();
}

void lcBlenderPreferencesDialog::reject()
{
	if (mPreferences->PromptCancel())
		QDialog::reject();
}

lcBlenderPreferences::lcBlenderPreferences(int Width, int Height, double Scale, QWidget* Parent)
	: QWidget(Parent)
{
	gAddonPreferences = this;

#ifndef QT_NO_PROCESS
	mProcess = nullptr;
#endif

	mImageWidth = Width;
	mImageHeight = Height;
	mScale = Scale;

	mDialogCancelled = false;

	QVBoxLayout* Layout = new QVBoxLayout(Parent);

	if (Parent)
	{
		Parent->setLayout(Layout);
		Parent->setWhatsThis(WhatsThisDescription);
	}
	else
	{
		setWindowTitle(tr("Blender LDraw Addon Settings"));
		setLayout(Layout);
		setWhatsThis(WhatsThisDescription);
	}

	mContent = new QWidget();

	mForm = new QFormLayout(mContent);

	mContent->setLayout(mForm);

	QPalette ReadOnlyPalette = QApplication::palette();
	const lcPreferences& Preferences = lcGetPreferences();
	if (Preferences.mColorTheme == lcColorTheme::Dark)
		ReadOnlyPalette.setColor(QPalette::Base,QColor(LC_THEME_DARK_PALETTE_MIDLIGHT));
	else
		ReadOnlyPalette.setColor(QPalette::Base,QColor(LC_THEME_DEFAULT_PALETTE_LIGHT));
	ReadOnlyPalette.setColor(QPalette::Text,QColor(LC_DISABLED_TEXT));

	QGroupBox* BlenderExeBox = new QGroupBox(tr("Blender Executable"),mContent);
	mForm->addRow(BlenderExeBox);

	mExeGridLayout = new QGridLayout(BlenderExeBox);
	BlenderExeBox->setLayout(mExeGridLayout);

	mBlenderVersionLabel = new QLabel(BlenderExeBox);
	mExeGridLayout->addWidget(mBlenderVersionLabel,0,0);

	mBlenderVersionEdit = new QLineEdit(BlenderExeBox);
	mBlenderVersionEdit->setPalette(ReadOnlyPalette);
	mBlenderVersionEdit->setReadOnly(true);
	mExeGridLayout->addWidget(mBlenderVersionEdit,0,1,1,2);

	QLabel* PathLabel = new QLabel(BlenderExeBox);
	mExeGridLayout->addWidget(PathLabel,1,0);

	QLineEdit* PathLineEdit = new QLineEdit(BlenderExeBox);
	mExeGridLayout->addWidget(PathLineEdit,1,1);
	mPathLineEditList << PathLineEdit;
	connect(PathLineEdit, SIGNAL(editingFinished()), this, SLOT(ConfigureBlenderAddon()));

	QPushButton* PathBrowseButton = new QPushButton(tr("Browse..."), BlenderExeBox);
	mExeGridLayout->addWidget(PathBrowseButton,1,2);
	mPathBrowseButtonList << PathBrowseButton;
	connect(PathBrowseButton, SIGNAL(clicked(bool)), this, SLOT(BrowseBlender(bool)));

	QGroupBox* BlenderAddonVersionBox = new QGroupBox(tr("%1 Blender LDraw Addon").arg(LC_PRODUCTNAME_STR),mContent);
	mForm->addRow(BlenderAddonVersionBox);

	mAddonGridLayout = new QGridLayout(BlenderAddonVersionBox);
	BlenderAddonVersionBox->setLayout(mAddonGridLayout);

	QCheckBox* AddonVersionCheck = new QCheckBox(tr("Prompt to download new addon version when available"), BlenderAddonVersionBox);
	AddonVersionCheck->setChecked(lcGetProfileInt(LC_PROFILE_BLENDER_ADDON_VERSION_CHECK));
	QObject::connect(AddonVersionCheck, &QCheckBox::stateChanged, [](int State)
	{
		 const bool VersionCheck = static_cast<Qt::CheckState>(State) == Qt::CheckState::Checked;
		 lcSetProfileInt(LC_PROFILE_BLENDER_ADDON_VERSION_CHECK, (int)VersionCheck);
	});
	mAddonGridLayout->addWidget(AddonVersionCheck,0,0,1,4);

	mAddonVersionLabel = new QLabel(BlenderAddonVersionBox);
	mAddonGridLayout->addWidget(mAddonVersionLabel,1,0);

	mAddonVersionEdit = new QLineEdit(BlenderAddonVersionBox);
	mAddonVersionEdit->setToolTip(tr("%1 Blender LDraw import and image renderer addon").arg(LC_PRODUCTNAME_STR));
	mAddonVersionEdit->setPalette(ReadOnlyPalette);
	mAddonVersionEdit->setReadOnly(true);
	mAddonGridLayout->addWidget(mAddonVersionEdit,1,1);
	mAddonGridLayout->setColumnStretch(1,1/*1 is greater than 0 (default)*/);

	mAddonUpdateButton = new QPushButton(tr("Update"), BlenderAddonVersionBox);
	mAddonUpdateButton->setToolTip(tr("Update %1 Blender LDraw addon").arg(LC_PRODUCTNAME_STR));
	mAddonGridLayout->addWidget(mAddonUpdateButton,1,2);
	connect(mAddonUpdateButton, SIGNAL(clicked(bool)), this, SLOT(UpdateBlenderAddon()));

	mAddonStdOutButton = new QPushButton(tr("Output..."), BlenderAddonVersionBox);
	mAddonStdOutButton->setToolTip(tr("Open the standrd output log"));
	mAddonStdOutButton->setEnabled(false);
	mAddonGridLayout->addWidget(mAddonStdOutButton,1,3);
	connect(mAddonStdOutButton, SIGNAL(clicked(bool)), this, SLOT(GetStandardOutput()));

	mModulesBox = new QGroupBox(tr("Enabled Addon Modules"),mContent);
	QHBoxLayout* ModulesLayout = new QHBoxLayout(mModulesBox);
	mModulesBox->setLayout(ModulesLayout);
	mAddonGridLayout->addWidget(mModulesBox,2,0,1,4);

	mImportActBox = new QCheckBox(tr("LDraw Import TN"),mModulesBox);
	mImportActBox->setToolTip(tr("Enable addon import module (adapted from LDraw Import by Toby Nelson) in Blender"));
	ModulesLayout->addWidget(mImportActBox);
	connect(mImportActBox, SIGNAL(clicked(bool)), this, SLOT(EnableImportModule()));

	mImportMMActBox = new QCheckBox(tr("LDraw Import MM"),mModulesBox);
	mImportMMActBox->setToolTip(tr("Enable addon import module (adapted from LDraw Import by Matthew Morrison) in Blender"));
	ModulesLayout->addWidget(mImportMMActBox);
	connect(mImportMMActBox, SIGNAL(clicked(bool)), this, SLOT(EnableImportModule()));

	mRenderActBox = new QCheckBox(tr("%1 Image Render").arg(LC_PRODUCTNAME_STR), mModulesBox);
	mRenderActBox->setToolTip(tr("Addon image render module in Blender"));
	mRenderActBox->setEnabled(false);
	ModulesLayout->addWidget(mRenderActBox);

	LoadSettings();

	mConfigured = !lcGetProfileString(LC_PROFILE_BLENDER_IMPORT_MODULE).isEmpty();

	const int CtlIdx = PATH_BLENDER;
	PathLabel->setText(mBlenderPaths[CtlIdx].label);
	PathLabel->setToolTip(mBlenderPaths[CtlIdx].tooltip);

	PathLineEdit->setText(mBlenderPaths[CtlIdx].value);
	PathLineEdit->setToolTip(mBlenderPaths[CtlIdx].tooltip);

	if (mAddonVersion.isEmpty())
	{
		mModulesBox->setEnabled(false);
		mAddonUpdateButton->setEnabled(true);
		mImportActBox->setChecked(true); // default addon module
	}
	else
	{
		mAddonVersionEdit->setText(mAddonVersion);
		mRenderActBox->setChecked(true);
		mImportActBox->setChecked(lcGetProfileString(LC_PROFILE_BLENDER_IMPORT_MODULE) == QLatin1String("TN"));
		mImportMMActBox->setChecked(lcGetProfileString(LC_PROFILE_BLENDER_IMPORT_MODULE) == QLatin1String("MM"));
	}

	QString VersionTextColour = QApplication::palette().text().color().name(),AddonTextColour;
	QString VersionText = tr("Blender"), AddonText = tr("Blender Addon");
	if (mConfigured)
	{
		AddonTextColour = VersionTextColour;
		mBlenderVersionEdit->setText(mBlenderVersion);
		mBlenderVersionEdit->setVisible(true);
	}
	else
	{
		const QString TextColour = Preferences.mColorTheme == lcColorTheme::Dark ? QLatin1String(LC_THEME_DARK_DECORATE_QUOTED_TEXT) : QLatin1String("blue");

		bool BlenderConfigured = !lcGetProfileString(LC_PROFILE_BLENDER_PATH).isEmpty();
		if (!BlenderConfigured)
		{
			VersionText = tr("Blender not configured.");
			VersionTextColour = TextColour;
		}
		else
			mBlenderVersionEdit->setText(mBlenderVersion);

		if (QFileInfo(QString("%1/Blender/%2").arg(mDataDir).arg(LC_BLENDER_ADDON_FILE)).isReadable())
		{
			mModulesBox->setEnabled(false);
			mImportActBox->setChecked(true);
			mAddonUpdateButton->setEnabled(true);
			if (BlenderConfigured)
				AddonText = tr("Addon not configured - Update.");
			else
				AddonText = tr("Addon not configured.");
			AddonTextColour = TextColour;
		}
	}

	mAddonVersionEdit->setVisible(!mAddonVersion.isEmpty());
	mBlenderVersionLabel->setStyleSheet(QString("QLabel { color : %1; }").arg(VersionTextColour));
	mAddonVersionLabel->setStyleSheet(QString("QLabel { color : %1; }").arg(AddonTextColour));
	mBlenderVersionLabel->setText(VersionText);
	mAddonVersionLabel->setText(AddonText);

	if (mImportMMActBox->isChecked())
		InitPathsAndSettingsMM();
	else
		InitPathsAndSettings();

	QScrollArea* ScrollArea = new QScrollArea(this);
	ScrollArea->setWidgetResizable(true);
	ScrollArea->setWidget(mContent);
	Layout->addWidget(ScrollArea);
}

lcBlenderPreferences::~lcBlenderPreferences()
{
	gAddonPreferences = nullptr;
}

void lcBlenderPreferences::ClearGroupBox(QGroupBox* GroupBox)
{
	int Row = -1;
	QFormLayout::ItemRole ItemRole = QFormLayout::SpanningRole;

	mForm->getWidgetPosition(GroupBox,& Row,& ItemRole);

	if(Row == -1 || ItemRole != QFormLayout::SpanningRole) return;

	QLayoutItem* GroupBoxIitem = mForm->itemAt(Row, ItemRole);

	mForm->removeItem(GroupBoxIitem);

	QWidget* WidgetItem = GroupBoxIitem->widget();
	if(WidgetItem)
	{
		if (GroupBox == mPathsBox)
		{
			delete mPathsBox;
			mPathsBox = nullptr;
		}
		else if (GroupBox == mSettingsBox)
		{
			delete mSettingsBox;
			mSettingsBox = nullptr;
		}
	}

	delete GroupBoxIitem;
}

void lcBlenderPreferences::InitPathsAndSettings()
{
	if (!NumSettings())
		LoadSettings();

	// Paths
	ClearGroupBox(mPathsBox);
	mPathsBox = new QGroupBox(mContent);
	mPathsBox->setTitle(tr("LDraw Import TN Addon Paths"));
	mPathsGridLayout = new QGridLayout(mPathsBox);
	mPathsBox->setLayout(mPathsGridLayout);
	mForm->addRow(mPathsBox);

	for (int CtlIdx = 1/*skip blender executable*/; CtlIdx < NumPaths(); ++CtlIdx)
	{
		int ColumnIdx = CtlIdx - 1; // adjust for skipping first item - blender executable
		bool IsVisible = CtlIdx != PATH_STUDIO_LDRAW;
		QLabel* PathLabel = new QLabel(mBlenderPaths[CtlIdx].label, mPathsBox);
		PathLabel->setToolTip(mBlenderPaths[CtlIdx].tooltip);
		mPathsGridLayout->addWidget(PathLabel,ColumnIdx,0);
		PathLabel->setVisible(IsVisible);

		QLineEdit* PathLineEdit = new QLineEdit(mPathsBox);
		PathLineEdit->setProperty("ControlID",QVariant(CtlIdx));
		PathLineEdit->setText(mBlenderPaths[CtlIdx].value);
		PathLineEdit->setToolTip(mBlenderPaths[CtlIdx].tooltip);
		if (mPathLineEditList.size() > CtlIdx)
			mPathLineEditList.replace(CtlIdx, PathLineEdit);
		else
			mPathLineEditList << PathLineEdit;
		mPathsGridLayout->addWidget(PathLineEdit,ColumnIdx,1);
		PathLineEdit->setVisible(IsVisible);

		QPushButton* PathBrowseButton = new QPushButton(tr("Browse..."), mPathsBox);
		if (mPathBrowseButtonList.size() > CtlIdx)
			mPathBrowseButtonList.replace(CtlIdx, PathBrowseButton);
		else
			mPathBrowseButtonList << PathBrowseButton;
		mPathsGridLayout->addWidget(PathBrowseButton,ColumnIdx,2);
		PathBrowseButton->setVisible(IsVisible);

		if (IsVisible)
		{
			connect(PathBrowseButton, SIGNAL(clicked(bool)), this, SLOT (BrowseBlender(bool)));
			connect(PathLineEdit, SIGNAL(editingFinished()), this, SLOT (PathChanged()));
		}
	}

	mPathsBox->setEnabled(mConfigured);

	// Settings
	ClearGroupBox(mSettingsBox);
	mSettingsBox = new QGroupBox(mContent);
	mSettingsSubform = new QFormLayout(mSettingsBox);
	mSettingsBox->setLayout(mSettingsSubform);
	mForm->addRow(mSettingsBox);

	mSettingsBox->setTitle(tr("LDraw Import TN Addon Settings"));
	mSettingLabelList.clear();
	mCheckBoxList.clear();
	mLineEditList.clear();
	mComboBoxList.clear();

	int ComboBoxItemsIndex = 0;

	for (int LblIdx = 0; LblIdx < NumSettings(); LblIdx++)
	{
		QLabel* Label = new QLabel(mSettingsBox);
		Label->setText(mBlenderSettings[LblIdx].label);
		Label->setToolTip(mBlenderSettings[LblIdx].tooltip);
		mSettingLabelList << Label;

		if (LblIdx < LBL_BEVEL_WIDTH)
		{   // QCheckBoxes
			QCheckBox* CheckBox = new QCheckBox(mSettingsBox);
			CheckBox->setProperty("ControlID",QVariant(LblIdx));
			CheckBox->setChecked(mBlenderSettings[LblIdx].value.toInt());
			CheckBox->setToolTip(mBlenderSettings[LblIdx].tooltip);
			if (LblIdx == LBL_CROP_IMAGE)
				connect(CheckBox, SIGNAL(toggled(bool)), this, SLOT (SetModelSize(bool)));
			else
				connect(CheckBox, SIGNAL(clicked()), this, SLOT (SettingChanged()));
			mCheckBoxList << CheckBox;
			mSettingsSubform->addRow(Label,CheckBox);
		}
		else if (LblIdx < LBL_COLOUR_SCHEME)
		{   // QLineEdits
			QLineEdit* LineEdit = new QLineEdit(mSettingsBox);
			LineEdit->setProperty("ControlID",QVariant(LblIdx));
			if (LblIdx == LBL_IMAGE_WIDTH || LblIdx == LBL_IMAGE_HEIGHT)
			{
				connect(LineEdit, SIGNAL(textChanged(const QString&)), this, SLOT (SizeChanged(const QString&)));
				LineEdit->setValidator(new QIntValidator(16, LC_RENDER_IMAGE_MAX_SIZE));
			}
			else if(LblIdx == LBL_DEFAULT_COLOUR)
			{
				LineEdit->setReadOnly(true);
				LineEdit->setStyleSheet("Text-align:left");
				mDefaultColourEditAction = LineEdit->addAction(QIcon(), QLineEdit::TrailingPosition);
				connect(mDefaultColourEditAction, SIGNAL(triggered(bool)), this, SLOT (ColorButtonClicked(bool)));
			}
			else
			{
				LineEdit->setText(mBlenderSettings[LblIdx].value);
				if (LblIdx == LBL_IMAGE_SCALE)
					LineEdit->setValidator(new QDoubleValidator(0.01,10.0,2));
				else if (LblIdx == LBL_RENDER_PERCENTAGE || LblIdx == LBL_CAMERA_BORDER_PERCENT)
					LineEdit->setValidator(new QIntValidator(1,1000));
				else
					LineEdit->setValidator(new QDoubleValidator(0.01,100.0,2));
				connect(LineEdit, SIGNAL(textEdited(const QString&)), this, SLOT (SettingChanged(const QString&)));
			}
			LineEdit->setToolTip(mBlenderSettings[LblIdx].tooltip);
			mLineEditList << LineEdit;
			if (LblIdx == LBL_DEFAULT_COLOUR)
				SetDefaultColor(lcGetColorIndex(mBlenderSettings[LBL_DEFAULT_COLOUR].value.toInt()));
			mSettingsSubform->addRow(Label,LineEdit);
		}
		else
		{   // QComboBoxes
			QComboBox* ComboBox = new QComboBox(mSettingsBox);
			ComboBox->setProperty("ControlID",QVariant(LblIdx));
			const QString Value = mBlenderSettings[LblIdx].value;
			QStringList const DataList = mComboItems[ComboBoxItemsIndex].dataList.split("|");
			QStringList const ItemList = mComboItems[ComboBoxItemsIndex].itemList.split("|");
			ComboBox->addItems(ItemList);
			for (int CtlIdx = 0; CtlIdx < ComboBox->count(); CtlIdx++)
				ComboBox->setItemData(CtlIdx, DataList.at(CtlIdx));
			ComboBox->setToolTip(mBlenderSettings[LblIdx].tooltip);
			int CurrentIndex = int(ComboBox->findData(QVariant::fromValue(Value)));
			ComboBox->setCurrentIndex(CurrentIndex);
			if (LblIdx == LBL_COLOUR_SCHEME)
				connect(ComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT (ValidateColourScheme(int)));
			else
				connect(ComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT (SettingChanged(int)));
			mComboBoxList << ComboBox;
			ComboBoxItemsIndex++;
			mSettingsSubform->addRow(Label,ComboBox);
		}
	}

	SetModelSize();

	if (!mSettingsSubform->rowCount())
		mSettingsSubform = nullptr;

	mSettingsBox->setEnabled(mConfigured);
}

void lcBlenderPreferences::InitPathsAndSettingsMM()
{
	if (!NumSettingsMM())
		LoadSettings();

	// Paths
	ClearGroupBox(mPathsBox);
	mPathsBox = new QGroupBox(mContent);
	mPathsBox->setTitle(tr("LDraw Import MM Addon Paths"));
	mPathsGridLayout = new QGridLayout(mPathsBox);
	mPathsBox->setLayout(mPathsGridLayout);
	mForm->addRow(mPathsBox);

	for (int CtlIdx = 1/*skip blender executable*/; CtlIdx < NumPaths(); ++CtlIdx)
	{
		int ColumnIdx = CtlIdx - 1; // adjust for skipping first item - blender executable
		bool IsVisible = CtlIdx != PATH_LSYNTH && CtlIdx != PATH_STUD_LOGO;
		QLabel* PathLabel = new QLabel(mBlenderPaths[CtlIdx].label, mPathsBox);
		PathLabel->setToolTip(mBlenderPaths[CtlIdx].tooltip);
		mPathsGridLayout->addWidget(PathLabel,ColumnIdx,0);
		PathLabel->setVisible(IsVisible);

		QLineEdit* PathLineEdit = new QLineEdit(mPathsBox);
		PathLineEdit->setProperty("ControlID",QVariant(CtlIdx));
		PathLineEdit->setText(mBlenderPaths[CtlIdx].value);
		PathLineEdit->setToolTip(mBlenderPaths[CtlIdx].tooltip);
		if (mPathLineEditList.size() > CtlIdx)
			mPathLineEditList.replace(CtlIdx, PathLineEdit);
		else
			mPathLineEditList << PathLineEdit;
		mPathsGridLayout->addWidget(PathLineEdit,ColumnIdx,1);
		PathLineEdit->setVisible(IsVisible);

		QPushButton* PathBrowseButton = new QPushButton(tr("Browse..."), mPathsBox);
		if (mPathBrowseButtonList.size() > CtlIdx)
			mPathBrowseButtonList.replace(CtlIdx, PathBrowseButton);
		else
			mPathBrowseButtonList << PathBrowseButton;
		mPathsGridLayout->addWidget(PathBrowseButton,ColumnIdx,2);
		PathBrowseButton->setVisible(IsVisible);

		if (IsVisible)
		{
			connect(PathBrowseButton, SIGNAL(clicked(bool)), this, SLOT (BrowseBlender(bool)));
			connect(PathLineEdit, SIGNAL(editingFinished()), this, SLOT (PathChanged()));
		}
	}

	mPathsBox->setEnabled(mConfigured);

	// Settings
	ClearGroupBox(mSettingsBox);
	mSettingsBox = new QGroupBox(mContent);
	mSettingsSubform = new QFormLayout(mSettingsBox);
	mSettingsBox->setLayout(mSettingsSubform);
	mForm->addRow(mSettingsBox);

	mSettingsBox->setTitle(tr("LDraw Import MM Addon Settings"));
	mSettingLabelList.clear();
	mCheckBoxList.clear();
	mLineEditList.clear();
	mComboBoxList.clear();

	int ComboBoxItemsIndex = 0;

	for (int LblIdx = 0; LblIdx < NumSettingsMM(); LblIdx++)
	{
		QLabel* Label = new QLabel(mSettingsBox);
		Label->setText(mBlenderSettingsMM[LblIdx].label);
		Label->setToolTip(mBlenderSettingsMM[LblIdx].tooltip);
		mSettingLabelList << Label;

		if (LblIdx < LBL_BEVEL_SEGMENTS)
		{   // QCheckBoxes
			QCheckBox* CheckBox = new QCheckBox(mSettingsBox);
			CheckBox->setProperty("ControlID",QVariant(LblIdx));
			CheckBox->setChecked(mBlenderSettingsMM[LblIdx].value.toInt());
			CheckBox->setToolTip(mBlenderSettingsMM[LblIdx].tooltip);
			if (LblIdx == LBL_CROP_IMAGE_MM)
				connect(CheckBox, SIGNAL(toggled(bool)), this, SLOT (SetModelSize(bool)));
			else
				connect(CheckBox, SIGNAL(clicked()), this, SLOT (SettingChanged()));
			mCheckBoxList << CheckBox;
			mSettingsSubform->addRow(Label,CheckBox);
		}
		else if (LblIdx < LBL_CHOSEN_LOGO)
		{   // QLineEdits
			QLineEdit* LineEdit = new QLineEdit(mSettingsBox);
			LineEdit->setProperty("ControlID",QVariant(LblIdx));
			if (LblIdx == LBL_RESOLUTION_WIDTH || LblIdx == LBL_RESOLUTION_HEIGHT)
			{
				connect(LineEdit, SIGNAL(textChanged(const QString&)), this, SLOT  (SizeChanged(const QString&)));
				LineEdit->setValidator(new QIntValidator(16, LC_RENDER_IMAGE_MAX_SIZE));
			}
			else
			{
				LineEdit->setText(mBlenderSettingsMM[LblIdx].value);
				if (LblIdx == LBL_IMPORT_SCALE)
					LineEdit->setValidator(new QDoubleValidator(0.01,10.0,2));
				else if (LblIdx == LBL_RENDER_PERCENTAGE_MM || LblIdx == LBL_CAMERA_BORDER_PERCENT_MM)
					LineEdit->setValidator(new QIntValidator(1,1000));
				else if (LblIdx == LBL_GAP_SCALE || LblIdx == LBL_MERGE_DISTANCE)
					LineEdit->setValidator(new QDoubleValidator(0.001,100.0,3));
				else if (LblIdx == LBL_BEVEL_WEIGHT || LblIdx == LBL_BEVEL_WIDTH_MM)
					LineEdit->setValidator(new QDoubleValidator(0.0,10.0,1));
				else
					LineEdit->setValidator(new QIntValidator(1, LC_RENDER_IMAGE_MAX_SIZE));
				connect(LineEdit, SIGNAL(textEdited(const QString&)), this, SLOT (SettingChanged(const QString&)));
			}
			LineEdit->setToolTip(mBlenderSettingsMM[LblIdx].tooltip);
			mLineEditList << LineEdit;
			mSettingsSubform->addRow(Label,LineEdit);
		}
		else
		{   // QComboBoxes
			QComboBox* ComboBox = new QComboBox(mSettingsBox);
			ComboBox->setProperty("ControlID",QVariant(LblIdx));
			const QString Value = mBlenderSettingsMM[LblIdx].value;
			QStringList const DataList = mComboItemsMM[ComboBoxItemsIndex].dataList.split("|");
			QStringList const ItemList = mComboItemsMM[ComboBoxItemsIndex].itemList.split("|");
			ComboBox->addItems(ItemList);
			for (int CtlIdx = 0; CtlIdx < ComboBox->count(); CtlIdx++)
				ComboBox->setItemData(CtlIdx, DataList.at(CtlIdx));
			ComboBox->setToolTip(mBlenderSettingsMM[LblIdx].tooltip);
			int CurrentIndex = int(ComboBox->findData(QVariant::fromValue(Value)));
			ComboBox->setCurrentIndex(CurrentIndex);
			if (LblIdx == LBL_COLOUR_SCHEME_MM)
				connect(ComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT (ValidateColourScheme(int)));
			else
				connect(ComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT  (SettingChanged(int)));
			mComboBoxList << ComboBox;
			ComboBoxItemsIndex++;
			mSettingsSubform->addRow(Label,ComboBox);
		}
	}

	SetModelSize();

	if (!mSettingsSubform->rowCount())
		mSettingsSubform = nullptr;

	mSettingsBox->setEnabled(mConfigured);
}

void lcBlenderPreferences::UpdateBlenderAddon()
{
	mAddonUpdateButton->setEnabled(false);

	disconnect(mPathLineEditList[PATH_BLENDER], SIGNAL(editingFinished()), this, SLOT (ConfigureBlenderAddon()));

	ConfigureBlenderAddon(sender() == mPathBrowseButtonList[PATH_BLENDER],
						  sender() == mAddonUpdateButton);

	connect(mPathLineEditList[PATH_BLENDER], SIGNAL(editingFinished()), this, SLOT (ConfigureBlenderAddon()));
}

void lcBlenderPreferences::ConfigureBlenderAddon(bool TestBlender, bool AddonUpdate, bool ModuleChange)
{
	mProgressBar = nullptr;

	const QString BlenderExe = QDir::toNativeSeparators(mPathLineEditList[PATH_BLENDER]->text());

	if (BlenderExe.isEmpty())
	{
		mBlenderVersion.clear();
		mConfigured = false;
		StatusUpdate(false, true);
		mAddonUpdateButton->setEnabled(mConfigured);
		mPathsBox->setEnabled(mConfigured);
		mSettingsBox->setEnabled(mConfigured);
		return;
	}

	if (QFileInfo(BlenderExe).isReadable())
	{
		enum ProcEnc
		{
			PR_OK, PR_FAIL, PR_WAIT, PR_INSTALL, PR_TEST
		};
		const QString BlenderDir = QDir::toNativeSeparators(QString("%1/Blender").arg(mDataDir));
		const QString BlenderConfigDir = QString("%1/setup/addon_setup/config").arg(BlenderDir);
		const QString BlenderAddonDir = QDir::toNativeSeparators(QString("%1/addons").arg(BlenderDir));
		const QString BlenderExeCompare = QDir::toNativeSeparators(lcGetProfileString(LC_PROFILE_BLENDER_PATH)).toLower();
		const QString BlenderInstallFile = QDir::toNativeSeparators(QString("%1/%2").arg(BlenderDir).arg(LC_BLENDER_ADDON_INSTALL_FILE));
		const QString BlenderTestString = QLatin1String("###TEST_BLENDER###");
		QByteArray AddonPathsAndModuleNames;
		QString Message, ShellProgram;
		QStringList Arguments;
		ProcEnc Result = PR_OK;
		QFile ScriptFile;

		bool NewBlenderExe = BlenderExeCompare != BlenderExe.toLower();

		if (mConfigured && !AddonUpdate && !ModuleChange && !NewBlenderExe)
			return;

#ifdef Q_OS_WIN
		ShellProgram = QLatin1String(LC_WINDOWS_SHELL);
#else
		ShellProgram = QLatin1String(LC_UNIX_SHELL);
#endif
		auto ProcessCommand = [&](ProcEnc Action)
		{
#ifdef Q_OS_WIN
			if (Action == PR_INSTALL)
			{
				lcRunElevatedProcess(ShellProgram.toStdWString().c_str(), QString("/C %1").arg(ScriptFile.fileName()).toStdWString().c_str(), BlenderDir.toStdWString().c_str());

				mAddonVersionLabel->clear();

				if (mProgressBar)
					mProgressBar->close();

				return PR_OK;
			}
#endif

			mProcess = new QProcess();

			QString ProcessAction = tr("addon install");
			if (Action == PR_INSTALL)
			{
				connect(mProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(ReadStdOut()));
				const QString& LdrawLibPath = QFileInfo(lcGetProfileString(LC_PROFILE_PARTS_LIBRARY)).absolutePath();
				QStringList SystemEnvironment = QProcess::systemEnvironment();
				SystemEnvironment.prepend("LDRAW_DIRECTORY=" + LdrawLibPath);
				SystemEnvironment.prepend("ADDONS_TO_LOAD=" + AddonPathsAndModuleNames);
				mProcess->setEnvironment(SystemEnvironment);
			}
			else
			{
				ProcessAction = tr("test");
				disconnect(&mUpdateTimer, SIGNAL(timeout()), this, SLOT(Update()));
			}

			mProcess->setWorkingDirectory(BlenderDir);

			mProcess->setStandardErrorFile(QString("%1/stderr-blender-addon-install").arg(BlenderDir));

			if (Action == PR_INSTALL)
			{
				mProcess->start(BlenderExe, Arguments);
			}
			else
			{
#ifdef Q_OS_WIN
				mProcess->start(ShellProgram, QStringList() << "/C" << ScriptFile.fileName());
#else
				mProcess->start(ShellProgram, QStringList() << ScriptFile.fileName());
#endif
			}

			if (!mProcess->waitForStarted())
			{
				Message = tr("Cannot start Blender %1 mProcess.\n%2").arg(ProcessAction).arg(QString(mProcess->readAllStandardError()));
				delete mProcess;
				mProcess = nullptr;
				return PR_WAIT;
			}
			else
			{
				if (mProcess->exitStatus() != QProcess::NormalExit || mProcess->exitCode() != 0)
				{
					Message = tr("Failed to execute Blender %1.\n%2").arg(ProcessAction).arg(QString(mProcess->readAllStandardError()));
					return PR_FAIL;
				}
			}

			if (Action == PR_TEST)
			{
				while (mProcess && mProcess->state() != QProcess::NotRunning)
				{
					QTime Waiting = QTime::currentTime().addMSecs(500);
					while (QTime::currentTime() < Waiting)
						QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
				}
				connect(&mUpdateTimer, SIGNAL(timeout()), this, SLOT(Update()));
				const QString StdOut = QString(mProcess->readAllStandardOutput());
				if (!StdOut.contains(BlenderTestString))
				{
					Message =  tr("A simple check to test if the selected file is Blender failed."
								 "Please create an %1 GitHub ticket if you are sure the file is Blender 2.8 or newer."
								 "The ticket should contain the full path to the Blender executable.").arg(LC_PRODUCTNAME_STR);
					return PR_FAIL;
				}
				else
				{
					QStringList Items = StdOut.split('\n',SkipEmptyParts).last().split(" ");
					if (Items.count() > 6 && Items.at(0) == QLatin1String("Blender"))
					{
						Items.takeLast();
						mBlenderVersion.clear();
						for (int LblIdx = 1; LblIdx < Items.size(); LblIdx++)
							mBlenderVersion.append(Items.at(LblIdx)+" ");
						mBlenderVersionFound = !mBlenderVersion.isEmpty();
						if (mBlenderVersionFound)
						{
							mBlenderVersion = mBlenderVersion.trimmed().prepend("v").append(")");
							mBlenderVersionEdit->setText(mBlenderVersion);
							// set default LDraw import module if not configured
							if (!mImportActBox->isChecked() && !mImportMMActBox->isChecked())
								mImportActBox->setChecked(true);
							Message = tr("Blender %1 mProcess completed. Version: %2 validated.").arg(ProcessAction).arg(mBlenderVersion);
						}
					}
				}
			}

			return PR_OK;
		};

		connect(&mUpdateTimer, SIGNAL(timeout()), this, SLOT(Update()));
		mUpdateTimer.start(500);

		QDir ConfigDir(BlenderConfigDir);
		if (!ModuleChange || !ConfigDir.exists())
		{
			mProgressBar = new QProgressBar(mContent);
			mProgressBar->setMaximum(0);
			mProgressBar->setMinimum(0);
			mProgressBar->setValue(1);

			TestBlender |= sender() == mPathLineEditList[PATH_BLENDER];
			mAddonVersionLabel->setText(tr("Installing..."));
			if (TestBlender)
			{
				mExeGridLayout->replaceWidget(mBlenderVersionEdit, mProgressBar);
				mProgressBar->show();

				Arguments << QString("--factory-startup");
				Arguments << QString("-b");
				Arguments << QString("--python-expr");
				Arguments << QString("\"import sys;print('%1');sys.stdout.flush();sys.exit()\"").arg(BlenderTestString);

				bool Error = false;

				QString ScriptName, ScriptCommand;

#ifdef Q_OS_WIN
				ScriptName =  QLatin1String("blender_test.bat");
#else
				ScriptName =  QLatin1String("blender_test.sh");
#endif
				ScriptCommand = QString("\"%1\" %2").arg(BlenderExe).arg(Arguments.join(" "));

				ScriptFile.setFileName(QString("%1/%2").arg(QDir::tempPath()).arg(ScriptName));
				if (ScriptFile.open(QIODevice::WriteOnly | QIODevice::Text))
				{
					QTextStream Stream(&ScriptFile);
#ifdef Q_OS_WIN
					Stream << QLatin1String("@ECHO OFF& SETLOCAL") << LineEnding;
#else
					Stream << QLatin1String("#!/bin/bash") << LineEnding;
#endif
					Stream << ScriptCommand << LineEnding;
					ScriptFile.close();
				}
				else
				{
					Message = tr("Error writing to file '%1':\n%2.").arg(ScriptFile.fileName(), ScriptFile.errorString());
					Error = true;
				}

				if (Error)
				{
					StatusUpdate(false);
					return;
				}

				QThread::sleep(1);

				Result = ProcessCommand(PR_TEST);
				bool TestOk = Result != PR_FAIL;
				const QString statusLabel = TestOk ? "" : tr("Blender test failed.");
				StatusUpdate(false, TestOk, statusLabel);
				if (TestOk)
				{
					lcSetProfileString(LC_PROFILE_BLENDER_VERSION, mBlenderVersion);
					lcSetProfileString(LC_PROFILE_BLENDER_PATH, BlenderExe);
				}
				else
				{
					const QString& Title = tr ("%1 Blender LDraw Addon").arg(LC_PRODUCTNAME_STR);
					const QString& Header = tr ("Blender test failed.");
					ShowMessage(this, Header, Title, Message);
					return;
				}
			} // Test Blender

			if (!mBlenderVersion.isEmpty() && !mImportMMActBox->isChecked() && !mImportActBox->isChecked())
			{
				const QString& Title = tr ("%1 Blender LDraw Addon Modules").arg(LC_PRODUCTNAME_STR);
				const QString& Header = tr ("No import module enabled. If you continue, the default import module (Import TN) will be used.<br>If you select No, all addon modules will be disabled.");
				const QString& Body = tr ("Continue with the default import module ?");
				int Exec = ShowMessage(this, Header, Title, Body, QString(), MBB_YES_NO, QMessageBox::NoIcon);
				if (Exec != QMessageBox::Yes)
				{
					mRenderActBox->setChecked(false);
					if (Exec == QMessageBox::Cancel)
						return;
				}

				mImportActBox->setChecked(true);
			}

			if (TestBlender)
			{
				const QString preferredImportModule = mImportActBox->isChecked() ? QString("TN") : mImportMMActBox->isChecked() ? QString("MM") : QString();  // disable all import modules
				lcSetProfileString(LC_PROFILE_BLENDER_IMPORT_MODULE, preferredImportModule);
			}
			else
				mBlenderVersionEdit->setVisible(AddonUpdate);

			if (mProgressBar)
			{
				mProgressBar->setMaximum(0);
				mProgressBar->setMinimum(0);
				mProgressBar->setValue(1);
				mAddonGridLayout->replaceWidget(mAddonVersionEdit, mProgressBar);
				mAddonVersionLabel->setText(tr("Downloading..."));
				mProgressBar->show();
			}

			if (!ExtractBlenderAddon(BlenderDir))
			{
				if (AddonUpdate)
				{
					mConfigured = true;
					mBlenderVersionLabel->setText(tr("Blender"));
					mBlenderVersionLabel->setStyleSheet(QString("QLabel { color : %1; }").arg(QApplication::palette().text().color().name()));
					mBlenderVersionEdit->setText(mBlenderVersion);
					mBlenderVersionEdit->setToolTip(tr("Display the Blender and %1 Render addon version").arg(LC_PRODUCTNAME_STR));
					mBlenderVersionEdit->setVisible(mConfigured);
					if (!mAddonVersion.isEmpty())
					{
						mModulesBox->setEnabled(true);
						mAddonVersionEdit->setText(mAddonVersion);
					}
					mAddonUpdateButton->setEnabled(mConfigured);
					if (mProgressBar)
					{
						mAddonGridLayout->replaceWidget(mProgressBar, mAddonVersionEdit);
						mAddonVersionLabel->setText(tr("Blender Addon"));
						mProgressBar->close();
					}
				}
				return;
			}

			if (!QFileInfo(BlenderInstallFile).exists())
			{
				ShowMessage(this, tr("Could not find addon install file: %1").arg(BlenderInstallFile));
				StatusUpdate(true, true, tr("Not found."));
				return;
			}

			StatusUpdate(true, false, tr("Installing..."));

			emit SettingChangedSig(true);
		}

		SaveSettings();

		Arguments.clear();
		Arguments << QString("--background");
		Arguments << QString("--python");
		Arguments << BlenderInstallFile;
		Arguments << "--";
		if (!mRenderActBox->isChecked() && !mImportActBox->isChecked() && !mImportMMActBox->isChecked())
			Arguments << QString("--disable_ldraw_addons");
		else if (!mImportActBox->isChecked())
			Arguments << QString("--disable_ldraw_import");
		else if (!mImportMMActBox->isChecked())
			Arguments << QString("--disable_ldraw_import_mm");
		else if (!mRenderActBox->isChecked())
			Arguments << QString("--disable_ldraw_render");
		Arguments << QString("--leocad");

		Message = tr("Blender Addon Install Arguments: %1 %2").arg(BlenderExe).arg(Arguments.join(" "));

		if (!TestBlender)
			mBlenderVersionFound = false;

		if (QDir(BlenderAddonDir).entryInfoList(QDir::Dirs|QDir::NoSymLinks).count() > 0)
		{
			QJsonArray JsonArray;
			QStringList AddonDirs = QDir(BlenderAddonDir).entryList(QDir::NoDotAndDotDot | QDir::Dirs, QDir::SortByMask);
			for (const QString& Addon : AddonDirs)
			{
				QDir Dir(QString("%1/%2").arg(BlenderAddonDir).arg(Addon));
				Dir.setFilter(QDir::Files | QDir::NoDotAndDotDot | QDir::NoSymLinks);
				QFileInfoList List = Dir.entryInfoList();
				for (int LblIdx = 0; LblIdx < List.size(); LblIdx++)
				{
					if (List.at(LblIdx).fileName() == QLatin1String("__init__.py"))
					{
						QFile File(QFileInfo(List.at(LblIdx)).absoluteFilePath());
						if (!File.open(QFile::ReadOnly | QFile::Text))
						{
							ShowMessage(this, tr("Cannot read addon file %1<br>%2").arg(List.at(LblIdx).fileName()).arg(File.errorString()));
							break;
						}
						else
						{
							bool FoundModule = false;
							QTextStream In(&File);
							while (!In.atEnd())
							{
								if (QString(In.readLine(0)).startsWith("bl_info"))
								{
									FoundModule = true;
									break;
								}
							}
							File.close();
							if (FoundModule)
							{
								QJsonObject JsonItemObj;
								JsonItemObj["load_dir"] = QDir::toNativeSeparators(Dir.absolutePath());
								JsonItemObj["module_name"] = Dir.dirName();
								JsonArray.append(JsonItemObj);
							}
						}
					}
				}
			}
			QJsonDocument JsonDoc;
			JsonDoc.setArray(JsonArray);
			AddonPathsAndModuleNames = JsonDoc.toJson(QJsonDocument::Compact);
		}

#ifdef Q_OS_WIN
		bool Error = false;

		QString ScriptName =  QLatin1String("blender_install.bat");

		ScriptFile.setFileName(QString("%1/%2").arg(QDir::tempPath()).arg(ScriptName));
		if (ScriptFile.open(QIODevice::WriteOnly | QIODevice::Text))
		{
			const QString& LdrawLibPath = QFileInfo(lcGetProfileString(LC_PROFILE_PARTS_LIBRARY)).absolutePath();
			QTextStream Stream(&ScriptFile);

			Stream << QLatin1String("@ECHO OFF& SETLOCAL") << Qt::endl;
			Stream << QLatin1String("SET LDRAW_DIRECTORY=") << LdrawLibPath << Qt::endl;
			Stream << QLatin1String("SET ADDONS_TO_LOAD=") << AddonPathsAndModuleNames << Qt::endl;
			Stream << QString("\"%1\"").arg(BlenderExe);
			for (const QString& Argument : Arguments)
				Stream << " " << QString("\"%1\"").arg(Argument);
			Stream << Qt::endl;

			ScriptFile.close();
		}
		else
		{
			Message = tr("Error writing to file '%1':\n%2.").arg(ScriptFile.fileName(), ScriptFile.errorString());
			Error = true;
		}

		if (Error)
		{
			StatusUpdate(false);
			return;
		}
#endif

		Result = ProcessCommand(PR_INSTALL);

		if (Result != PR_OK)
			StatusUpdate(true, true, tr("Install failed."));
	}
	else
		ShowMessage(this, tr("Blender executable not found at [%1]").arg(BlenderExe), tr("Addon install failed."));
}

bool lcBlenderPreferences::ExtractBlenderAddon(const QString& BlenderDir)
{
	bool Extracted = false;

	QDir Dir(BlenderDir);
	if (!Dir.exists())
		Dir.mkdir(BlenderDir);

	AddonEnc AddonAction = AddonEnc(GetBlenderAddon(BlenderDir));
	if (AddonAction == ADDON_EXTRACT)
	{
		gAddonPreferences->StatusUpdate(true, false, tr("Extracting..."));
		const QString BlenderAddonFile = QDir::toNativeSeparators(QString("%1/%2").arg(BlenderDir).arg(LC_BLENDER_ADDON_FILE));

		QString Result;
		Extracted = gAddonPreferences->ExtractAddon(BlenderAddonFile, Result);

		if (!Extracted)
		{
			QString Message = tr("Failed to extract %1 to %2").arg(LC_BLENDER_ADDON_FILE).arg(BlenderDir);
			if (Result.size())
				Message.append(" "+Result);

			ShowMessage(this, Message, tr("Extract addon"));
		}
	}
	else if (AddonAction == ADDON_NO_ACTION)
		return true;

	return Extracted;
}

int lcBlenderPreferences::GetBlenderAddon(const QString& BlenderDir)
{
	const QString BlenderAddonDir = QDir::toNativeSeparators(QString("%1/addons").arg(BlenderDir));
	const QString BlenderAddonFile = QDir::toNativeSeparators(QString("%1/%2").arg(BlenderDir).arg(LC_BLENDER_ADDON_FILE));
	const QString AddonVersionFile = QDir::toNativeSeparators(QString("%1/%2/__version__.py").arg(BlenderAddonDir).arg(LC_BLENDER_ADDON_RENDER_FOLDER));
	bool ExtractedAddon = QFileInfo(AddonVersionFile).isReadable();
	bool BlenderAddonValidated = ExtractedAddon || QFileInfo(BlenderAddonFile).isReadable();
	AddonEnc AddonAction = ADDON_DOWNLOAD;
	QString LocalVersion, OnlineVersion;

	using namespace std;
	auto VersionStringCompare = [](string V1, string V2)
	{   // Returns 1 if V2 is smaller, -1 if V1 is smaller, 0 if equal
		int Vnum1 = 0, Vnum2 = 0;
		for (quint32 i = 0, j = 0; (i < V1.length() || j < V2.length());)
		{
			while (i < V1.length() && V1[i] != '.')
			{
				Vnum1 = Vnum1 * 10 + (V1[i] - '0');
				i++;
			}
			while (j < V2.length() && V2[j] != '.')
			{
				Vnum2 = Vnum2 * 10 + (V2[j] - '0');
				j++;
			}
			if (Vnum1 > Vnum2)
				return 1;
			if (Vnum2 > Vnum1)
				return -1;
			Vnum1 = Vnum2 = 0;
			i++;
			j++;
		}

		return 0;
	};

	auto GetBlenderAddonVersionMatch = [&]()
	{
		lcHttpManager* HttpManager = new lcHttpManager(gAddonPreferences);
		connect(HttpManager, SIGNAL(DownloadFinished(lcHttpReply*)), gAddonPreferences, SLOT(DownloadFinished(lcHttpReply*)));
		gAddonPreferences->mHttpReply = HttpManager->DownloadFile(QLatin1String(LC_BLENDER_ADDON_LATEST_URL));
		while (gAddonPreferences->mHttpReply)
			QApplication::processEvents();
		if (!gAddonPreferences->mData.isEmpty())
		{
			QJsonDocument Json = QJsonDocument::fromJson(gAddonPreferences->mData);
			OnlineVersion = Json.object()["tag_name"].toString();
			gAddonPreferences->mData.clear();
		}
		else
		{
			ShowMessage(this, tr("Check latest addon version failed."), tr("Latest Addon"), QString(), QString(), MBB_OK, QMessageBox::Warning);
			return true; // Reload existing archive
		}

		QByteArray Ba;
		if (!ExtractedAddon)
		{
			const char* VersionFile = "addons/" LC_BLENDER_ADDON_RENDER_FOLDER "/__version__.py";

			lcZipFile ZipFile;

			if (!ZipFile.OpenRead(BlenderAddonFile))
			{
				ShowMessage(this, tr("Cannot open addon archive file: %1.").arg(BlenderAddonFile));
				return false;
			}

			lcMemFile File;

			if (!ZipFile.ExtractFile(VersionFile, File))
			{
				ShowMessage(this, tr("Cannot extract addon archive version file: %1.").arg(VersionFile));
				return false;
			}

			Ba = QByteArray::fromRawData((const char*)File.mBuffer, (int)File.GetLength());
			if (Ba.isEmpty())
			{
				ShowMessage(this, tr("Cannot read addon archive version file: %1.").arg(VersionFile));
				return false; // Download new archive
			}
		}
		else
		{
			QFile File(AddonVersionFile);
			if (!File.open(QIODevice::ReadOnly))
			{
				ShowMessage(this, tr("Cannot read addon version file: [%1]<br>%2.").arg(AddonVersionFile).arg(File.errorString()));
				return false; // Download new archive
			}
			Ba = File.readAll();
			File.close();
		}

		QTextStream Content(Ba.data());
		while (!Content.atEnd())
		{
			QString Token;
			Content >> Token;
			if (Token == QLatin1String("version"))
			{
				Content >> Token;
				LocalVersion = Content.readAll().trimmed().replace("(","v").replace(",",".").replace(" ","").replace(")","");
			}
		}

		if (!LocalVersion.isEmpty() && !OnlineVersion.isEmpty())
		{
			// localVersion is smaller than onlineVersion so prompt to download new archive
			if (VersionStringCompare(LocalVersion.toStdString(), OnlineVersion.toStdString()) < 0)
				return false; // Download new archive
		}

		return true; // Reload existing archive
	};

	if (BlenderAddonValidated)
	{
		if (GetBlenderAddonVersionMatch())
		{
			if (ExtractedAddon)
				AddonAction = ADDON_NO_ACTION;
			else
				AddonAction = ADDON_EXTRACT;
		}
		else if (gMainWindow)
		{
			if (lcGetProfileInt(LC_PROFILE_BLENDER_ADDON_VERSION_CHECK))
			{
				if (LocalVersion.isEmpty())
					LocalVersion = gAddonPreferences->mAddonVersion;
				const QString& Title = tr ("%1 Blender LDraw Addon").arg(LC_PRODUCTNAME_STR);
				const QString& Header = tr ("Detected %1 Blender LDraw addon %2. A newer version %3 exists.").arg(LC_PRODUCTNAME_STR).arg(LocalVersion).arg(OnlineVersion);
				const QString& Body = tr ("Do you want to download version %1 ?").arg(OnlineVersion);
				int Exec = ShowMessage(this, Header, Title, Body, QString(), MBB_YES, QMessageBox::NoIcon);
				if (Exec == QMessageBox::Cancel)
				{
					AddonAction = ADDON_CANCELED;
					gAddonPreferences->mDialogCancelled = true;
				}
				else if (Exec == QMessageBox::No)
					AddonAction = ADDON_NO_ACTION;
			}
			else
				AddonAction = ADDON_NO_ACTION;
		}

		if (AddonAction != ADDON_DOWNLOAD)
			return AddonAction;
	}

	auto RemoveOldBlenderAddon = [&] (const QString& OldBlenderAddonFile)
	{
		if (QFileInfo(BlenderAddonDir).exists())
		{
			bool Result = true;
			QDir Dir(BlenderAddonDir);
			for (QFileInfo const& FileInfo : Dir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks, QDir::DirsFirst))
			{
				if (FileInfo.isDir())
					Result &= QDir(FileInfo.absoluteFilePath()).removeRecursively();
				else
					Result &= QFile::remove(FileInfo.absoluteFilePath());
			}

			if (QFileInfo(OldBlenderAddonFile).exists())
				Result &= QFile::remove(OldBlenderAddonFile);

			Result &= Dir.rmdir(BlenderAddonDir);
			if (!Result)
				ShowMessage(this, tr("Failed to properly remove Blender addon: %1").arg(BlenderAddonDir), tr("Remove Existing Addon"), QString(), QString(), MBB_OK, QMessageBox::Warning);
		}
	};

	BlenderAddonValidated = false;
	lcHttpManager* HttpManager = new lcHttpManager(gAddonPreferences);
	connect(HttpManager, SIGNAL(DownloadFinished(lcHttpReply*)), gAddonPreferences, SLOT(DownloadFinished(lcHttpReply*)));
	gAddonPreferences->mHttpReply = HttpManager->DownloadFile(QLatin1String(LC_BLENDER_ADDON_URL));
	while (gAddonPreferences->mHttpReply)
		QApplication::processEvents();
	if (!gAddonPreferences->mData.isEmpty())
	{
		const QString OldBlenderAddonFile = QString("%1.hold").arg(BlenderAddonFile);
		if (QFileInfo(BlenderAddonFile).exists())
		{
			if (!QFile::rename(BlenderAddonFile, OldBlenderAddonFile))
				ShowMessage(this, tr("Failed to rename existing Blender addon archive %1.").arg(BlenderAddonFile));
		}

		QDir Dir(BlenderDir);
		if(!Dir.exists())
			Dir.mkpath(".");

		QString ArchiveFileName, OldArchiveFileName = QFileInfo(OldBlenderAddonFile).fileName();
		QFile File(BlenderAddonFile);
		if (File.open(QIODevice::WriteOnly))
		{
			File.write(gAddonPreferences->mData);
			File.close();
			if (File.open(QIODevice::ReadOnly))
			{
				QCryptographicHash Sha256Hash(QCryptographicHash::Sha256);
				qint64 DataSize = File.size();
				const qint64 BufferSize = Q_INT64_C(1000);
				char Buf[BufferSize];
				int BytesRead;
				int ReadSize = qMin(DataSize, BufferSize);
				while (ReadSize > 0 && (BytesRead = File.read(Buf, ReadSize)) > 0)
				{
					DataSize -= BytesRead;
					Sha256Hash.addData(Buf, BytesRead);
					ReadSize = qMin(DataSize, BufferSize);
				}
				File.close();
				const QString ShaCalculated = Sha256Hash.result().toHex();

				gAddonPreferences->mData.clear();
				gAddonPreferences->mHttpReply = HttpManager->DownloadFile(QLatin1String(LC_BLENDER_ADDON_SHA_HASH_URL));
				while (gAddonPreferences->mHttpReply)
					QApplication::processEvents();
				if (!gAddonPreferences->mData.isEmpty())
				{
					const QStringList ShaReceived = QString(gAddonPreferences->mData).trimmed().split(" ", SkipEmptyParts);
					if (ShaReceived.first() == ShaCalculated)
					{
						ArchiveFileName = QFileInfo(BlenderAddonFile).fileName();
						if (ArchiveFileName == ShaReceived.last())
						{
							RemoveOldBlenderAddon(OldBlenderAddonFile);
							BlenderAddonValidated = true;
						}
						else
							ShowMessage(this, tr("Failed to validate Blender addon file name<br>Downloaded:%1<br>Received:%2").arg(ArchiveFileName, ShaReceived.last()));
					}
					else
						ShowMessage(this, tr("Failed to validate Blender addon SHA hash <br>Calculated:%1<br>Received:%2").arg(ShaCalculated, ShaReceived.first()));
					gAddonPreferences->mData.clear();
				}
				else
					ShowMessage(this, tr("Failed to receive SHA hash for Blender addon %1.sha256").arg(LC_BLENDER_ADDON_FILE));
			}
			else
				ShowMessage(this, tr("Failed to read Blender addon archive:<br>%1:<br>%2").arg(BlenderAddonFile).arg(File.errorString()));
		}
		else
			ShowMessage(this, tr("Failed to write Blender addon archive:<br>%1:<br>%2").arg(BlenderAddonFile).arg(File.errorString()));

		if (!BlenderAddonValidated)
		{
			if (QFileInfo(BlenderAddonFile).exists())
				if (!QFile::remove(BlenderAddonFile))
					ShowMessage(this, tr("Failed to remove invalid Blender addon archive:<br>%1").arg(BlenderAddonFile));
			if (QFileInfo(OldBlenderAddonFile).exists())
				if (!QFile::rename(OldBlenderAddonFile, BlenderAddonFile))
					ShowMessage(this, tr("Failed to restore Blender addon archive:<br>%1 from %2").arg(ArchiveFileName, OldArchiveFileName));
			AddonAction = ADDON_FAIL;
		}
	}
	else
	{
		ShowMessage(this, tr("Failed to download Blender addon archive:<br>%1").arg(BlenderAddonFile));
		AddonAction = ADDON_FAIL;
	}

	if (!BlenderAddonValidated)
		gAddonPreferences->StatusUpdate(true, true, tr("Download failed."));

	if (!QDir(BlenderAddonDir).exists() && QFileInfo(BlenderAddonFile).exists())
		AddonAction = ADDON_EXTRACT;

	return AddonAction;
}

void lcBlenderPreferences::StatusUpdate(bool Addon, bool Error, const QString& Message)
{
	QString Label, Colour;
	const QString Which = Addon ? tr("Blender addon") : tr("Blender");
	if (mProgressBar)
	{
		if (Addon)
		{
			mAddonGridLayout->replaceWidget(mProgressBar, mAddonVersionEdit);
		}
		else
		{
			mExeGridLayout->replaceWidget(mProgressBar, mBlenderVersionEdit);
			mProgressBar->hide();
		}

		mAddonVersionLabel->setText(Which);
	}
	if (Error)
	{
		if (!Addon)
			mPathLineEditList[PATH_BLENDER]->text() = QString();

		lcSetProfileString(LC_PROFILE_BLENDER_IMPORT_MODULE, QString());

		const lcPreferences& Preferences = lcGetPreferences();
		Label  = ! Message.isEmpty() ? Message : tr("%1 not configured").arg(Which);
		Colour = Message.startsWith("Error:", Qt::CaseInsensitive)
						? QLatin1String("red")
						: Preferences.mColorTheme == lcColorTheme::Dark
							? QLatin1String(LC_THEME_DARK_DECORATE_QUOTED_TEXT)
							: QLatin1String("blue");

		mDialogCancelled = true;
	}
	else
	{
		Label  = !Message.isEmpty() ? Message : tr("%1 setup...").arg(Which);
		Colour = QApplication::palette().text().color().name();
	}

	if (Addon)
	{
		mAddonVersionLabel->setStyleSheet(QString("QLabel { color : %1; }").arg(Colour));
		mAddonVersionLabel->setText(Label);
		mAddonVersionEdit->setVisible(!mAddonVersion.isEmpty());
	}
	else
	{
		mBlenderVersionLabel->setStyleSheet(QString("QLabel { color : %1; }").arg(Colour));
		mBlenderVersionLabel->setText(Label);
		mBlenderVersionEdit->setVisible(!mBlenderVersion.isEmpty());
	}
}

void lcBlenderPreferences::ShowResult()
{
	QString Message;
	bool Error;
	const QString StdErrLog = ReadStdErr(Error);

	if (mProgressBar)
		mProgressBar->close();

	WriteStdOut();

	if (mProcess->exitStatus() != QProcess::NormalExit || mProcess->exitCode() != 0 || Error)
	{
		const QString BlenderDir = QString("%1/Blender").arg(mDataDir);
		Message = tr("Addon install failed. See %1/stderr-blender-addon-install for details.").arg(BlenderDir);
		StatusUpdate(true, true,tr("Error: Install failed."));
		mConfigured = false;

		const QString& Title = tr ("%1 Blender Addon Install").arg(LC_PRODUCTNAME_STR);
		const QString& Header = "<b>" + tr ("Addon install failed.") + "</b>";
		const QString& Body = tr ("LDraw addon install encountered one or more errors. See Show Details...");
		ShowMessage(this, Header, Title, Body, StdErrLog, MBB_OK, QMessageBox::Warning);
	}
	else
	{
		const QString TextColour = QString("QLabel { color : %1; }").arg(QApplication::palette().text().color().name());
		mAddonGridLayout->replaceWidget(mProgressBar, mAddonVersionEdit);
		mConfigured = true;
		mBlenderVersionLabel->setText(tr("Blender"));
		mBlenderVersionLabel->setStyleSheet(TextColour);
		mBlenderVersionEdit->setText(mBlenderVersion);
		mBlenderVersionEdit->setToolTip(tr("Display the Blender and %1 Render addon version").arg(LC_PRODUCTNAME_STR));
		mBlenderVersionEdit->setVisible(mConfigured);
		mPathsBox->setEnabled(mConfigured);
		mSettingsBox->setEnabled(mConfigured);

		if (!mAddonVersion.isEmpty())
		{
			mAddonVersionLabel->setText(tr("Blender Addon"));
			mAddonVersionLabel->setStyleSheet(TextColour);
			mAddonVersionEdit->setText(mAddonVersion);
			mAddonVersionEdit->setVisible(true);
			mModulesBox->setEnabled(true);
			mAddonUpdateButton->setEnabled(true);
			lcSetProfileString(LC_PROFILE_BLENDER_VERSION, mBlenderVersion);
			lcSetProfileString(LC_PROFILE_BLENDER_ADDON_VERSION, mAddonVersion);
			SetModelSize(true);
			SaveSettings();
			mDialogCancelled = false;
		}
		Message = tr("Blender version %1").arg(mBlenderVersion);
	}

	delete mProcess;
	mProcess = nullptr;

	if (Error)
		ShowMessage(this, Message);
}

void lcBlenderPreferences::SettingChanged(const QString& Value)
{
	bool Change = false;

	QLineEdit* LineEdit = qobject_cast<QLineEdit*>(sender());
	if (LineEdit)
	{
		int LblIdx = LineEdit->property("ControlID").toInt();
		if (mImportMMActBox->isChecked())
		{
			Change = mBlenderSettingsMM[LblIdx].value != Value;
		}
		else
		{
			Change = mBlenderSettings[LblIdx].value != Value;
		}

		Change |= SettingsModified(false);
		emit SettingChangedSig(Change);
	}
}

void lcBlenderPreferences::SettingChanged(int Index)
{
	int LblIdx = -1;
	bool Change = false;
	QString Item;

	if (Index > -1)
	{
		QComboBox* ComboBox = qobject_cast<QComboBox*>(sender());
		if (ComboBox)
		{
			LblIdx = ComboBox->property("ControlID").toInt();
			Item = ComboBox->itemData(Index).toString();
		}
	}
	else
	{
		QCheckBox* CheckBox = qobject_cast<QCheckBox*>(sender());
		if (CheckBox)
		{
			LblIdx = CheckBox->property("ControlID").toInt();
			Item = QString::number(CheckBox->isChecked());
		}
	}

	if (LblIdx > -1)
	{
		if (mImportMMActBox->isChecked())
		{
			Change = mBlenderSettingsMM[LblIdx].value != Item;
		}
		else
		{
			Change = mBlenderSettings[LblIdx].value != Item;
		}
	}

	Change |= SettingsModified(false);
	emit SettingChangedSig(Change);
}

void lcBlenderPreferences::PathChanged()
{
	QLineEdit* LineEdit = qobject_cast<QLineEdit*>(sender());
	if (LineEdit)
	{
		bool Change = false;
		const int LblIdx = LineEdit->property("ControlID").toInt();
		const QString& Path = QDir::toNativeSeparators(LineEdit->text()).toLower();

		if (LblIdx != PATH_BLENDER)
		{
			Change = QDir::toNativeSeparators(mBlenderPaths[LblIdx].value).toLower() != Path;
		}

		Change |= SettingsModified(false);
		emit SettingChangedSig(Change);
	}
}

void lcBlenderPreferences::GetStandardOutput()
{
	const QString LogFile = QString("%1/Blender/stdout-blender-addon-install").arg(mDataDir);
	QFileInfo FileInfo(LogFile);
	if (!FileInfo.exists())
	{
		ShowMessage(this, tr("Blender addon standard output file not found: %1.").arg(FileInfo.absoluteFilePath()));
		return;
	}

	if (LogFile.isEmpty())
		return;

	QDesktopServices::openUrl(QUrl("file:///"+LogFile, QUrl::TolerantMode));
}

void lcBlenderPreferences::ReadStdOut(const QString& StdOutput, QString& Errors)
{
#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
	QRegularExpression RxInfo("^INFO: ");
	QRegularExpression RxData("^DATA: ");
	QRegularExpression RxError("^(?:\\w)*ERROR: ", QRegularExpression::CaseInsensitiveOption);
	QRegularExpression RxWarning("^(?:\\w)*WARNING: ", QRegularExpression::CaseInsensitiveOption);
	QRegularExpression RxAddonVersion("^ADDON VERSION: ", QRegularExpression::CaseInsensitiveOption);
	QStringList StdOutLines = StdOutput.split(QRegularExpression("\n|\r\n|\r"));
#else
	QRegExp RxInfo("^INFO: ");
	QRegExp RxData("^DATA: ");
	QRegExp RxError("^(?:\\w)*ERROR: ", Qt::CaseInsensitive);
	QRegExp RxWarning("^(?:\\w)*WARNING: ", Qt::CaseInsensitive);
	QRegExp RxAddonVersion("^ADDON VERSION: ", Qt::CaseInsensitive);
	QStringList StdOutLines = StdOutput.split(QRegExp("\n|\r\n|\r"));
#endif

	bool ErrorEncountered = false;
	QStringList Items, ErrorList;

	const QString SaveAddonVersion = mAddonVersion;
	const QString SaveVersion = mBlenderVersion;

	int EditListItems = mPathLineEditList.size();
	for (const QString& StdOutLine : StdOutLines)
	{
		if (StdOutLine.isEmpty())
			continue;

		if (!mBlenderVersionFound)
		{
			Items = StdOutLine.split(" ");
			if (Items.count() > 6 && Items.at(0) == QLatin1String("Blender"))
			{
				Items.takeLast();
				mBlenderVersion.clear();
				for (int LblIdx = 1; LblIdx < Items.size(); LblIdx++)
					mBlenderVersion.append(Items.at(LblIdx)+" ");
				mBlenderVersionFound = !mBlenderVersion.isEmpty();
				if (mBlenderVersionFound)
				{
					mBlenderVersion = mBlenderVersion.trimmed().prepend("v").append(")");
					mBlenderVersionEdit->setText(mBlenderVersion);
					if (!mImportActBox->isChecked() && !mImportMMActBox->isChecked())
						mImportActBox->setChecked(true);
				}
			}
		}

		if (StdOutLine.contains(RxInfo))
		{
			Items = StdOutLine.split(": ");
		}
		else if (StdOutLine.contains(RxData))
		{
			Items = StdOutLine.split(": ");
			if (Items.at(1) == "ENVIRONMENT_FILE")
			{
				mBlenderPaths[PATH_ENVIRONMENT].value = Items.at(2);
				if (EditListItems > PATH_ENVIRONMENT)
					mPathLineEditList[PATH_ENVIRONMENT]->setText(Items.at(2));
			}
			else if (Items.at(1) == "LSYNTH_DIRECTORY")
			{
				mBlenderPaths[PATH_LSYNTH].value = Items.at(2);
				if (EditListItems > PATH_LSYNTH)
					mPathLineEditList[PATH_LSYNTH]->setText(Items.at(2));
			}
			else if (Items.at(1) == "STUDLOGO_DIRECTORY")
			{
				mBlenderPaths[PATH_STUD_LOGO].value = Items.at(2);
				if (EditListItems > PATH_STUD_LOGO)
					mPathLineEditList[PATH_STUD_LOGO]->setText(Items.at(2));
			}
		}
		else if (StdOutLine.contains(RxError) || StdOutLine.contains(RxWarning))
		{
			ErrorList << StdOutLine.trimmed() + "<br>";
			if (!ErrorEncountered)
				ErrorEncountered = StdOutLine.contains(RxError);
		}
		else if (StdOutLine.contains(RxAddonVersion))
		{
			Items = StdOutLine.split(":");
			mAddonVersion = tr("v%1").arg(Items.at(1).trimmed());
			mAddonVersionEdit->setText(mAddonVersion);
		}
	}
	if (ErrorList.size())
	{
		if (!mBlenderVersionFound)
		{
			if (mBlenderVersion != SaveVersion)
			{
				mConfigured = false;
				mBlenderVersion = SaveVersion;
				mBlenderVersionEdit->setText(mBlenderVersion);
			}
		}
		if (mAddonVersion != SaveAddonVersion)
		{
			mConfigured = false;
			mAddonVersion = SaveAddonVersion;
			mAddonVersionEdit->setText(mAddonVersion);
		}
		Errors = ErrorList.join(" ");
	}
}

void lcBlenderPreferences::ReadStdOut()
{
	const QString& StdOut = QString(mProcess->readAllStandardOutput());

	mStdOutList.append(StdOut);

#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
	QRegularExpression RxInfo("^INFO: ");
	QRegularExpression RxError("(?:\\w)*ERROR: ", QRegularExpression::CaseInsensitiveOption);
	QRegularExpression RxWarning("(?:\\w)*WARNING: ", QRegularExpression::CaseInsensitiveOption);
#else
	QRegExp RxInfo("^INFO: ");
	QRegExp RxError("(?:\\w)*ERROR: ", Qt::CaseInsensitive);
	QRegExp RxWarning("(?:\\w)*WARNING: ", Qt::CaseInsensitive);
#endif

	bool const Error = StdOut.contains(RxError);
	bool const Warning = StdOut.contains(RxWarning);

	if (StdOut.contains(RxInfo) && !Error)
		StatusUpdate(true, false);

	QString ErrorsAndWarnings;

	ReadStdOut(StdOut, ErrorsAndWarnings);

	if (!ErrorsAndWarnings.isEmpty())
	{
		const QString StdOutLog = QDir::toNativeSeparators(QString("<br>- See %1/Blender/stdout-blender-addon-install")
																.arg(mDataDir));

		QMessageBox::Icon Icon = QMessageBox::Warning;
		const QString& Items = Error ? tr("errors%1").arg(Warning ? tr(" and warnings") : "") : Warning ? tr("warnings") : "";

		const QString& Title = tr ("%1 Blender Addon Install").arg(LC_PRODUCTNAME_STR);
		const QString& Header = "<b>" + tr ("Addon install standard output.") + "</b>";
		const QString& Body = tr ("LDraw addon install encountered %1. See Show Details...").arg(Items);
		ShowMessage(this, Header, Title, Body, ErrorsAndWarnings.append(StdOutLog), MBB_OK, Icon);
	}
}

QString lcBlenderPreferences::ReadStdErr(bool& Error) const
{
	auto CleanLine = [](const QString& Line)
	{
		return Line.trimmed() + "<br>";
	};

	Error = false;
	QStringList ReturnLines;

	const QString BlenderDir = QString("%1/Blender").arg(mDataDir);
	QFile File(QString("%1/stderr-blender-addon-install").arg(BlenderDir));
	if (!File.open(QFile::ReadOnly | QFile::Text))
	{
		const QString Message = tr("Failed to open log file: %1:\n%2").arg(File.fileName()).arg(File.errorString());
		return Message;
	}
	QTextStream In(&File);
	while (!In.atEnd())
	{
		const QString& Line = In.readLine(0);
		ReturnLines << CleanLine(Line);
		if (!Error)
			Error = !Line.isEmpty();
	}
	return ReturnLines.join(" ");
}

void lcBlenderPreferences::WriteStdOut()
{
	const QString BlenderDir = QString("%1/Blender").arg(mDataDir);
	QFile File(QString("%1/stdout-blender-addon-install").arg(BlenderDir));
	if (File.open(QFile::WriteOnly | QIODevice::Truncate | QFile::Text))
	{
		QTextStream Out(&File);
		for (const QString& Line : mStdOutList)
			Out << Line << LineEnding;
		File.close();
		mAddonStdOutButton->setEnabled(true);
	}
	else
		ShowMessage(this, tr("Error writing to %1 file '%2':\n%3").arg("stdout").arg(File.fileName(), File.errorString()));
}

bool lcBlenderPreferences::PromptCancel()
{
#ifndef QT_NO_PROCESS
	if (mProcess)
	{
		const QString& Title = tr ("Cancel %1 Addon Install").arg(LC_PRODUCTNAME_STR);
		const QString& Header = "<b>" + tr("Are you sure you want to cancel the add on install ?") + "</b>";
		int Exec = ShowMessage(this, Header, Title, QString(), QString(), MBB_YES_NO, QMessageBox::Question);
		if (Exec == QMessageBox::Yes)
		{
			mProcess->kill();
			delete mProcess;
			mProcess = nullptr;
		}
		else
			return false;
	}
#endif

	mDialogCancelled = true;
	return true;
}

void lcBlenderPreferences::Update()
{
#ifndef QT_NO_PROCESS
	if (!mProcess)
		return;

	if (mProcess->state() == QProcess::NotRunning)
		ShowResult();
#endif
	QApplication::processEvents();
}

void lcBlenderPreferences::Apply(const int Response)
{
	if (Response == QDialog::Accepted)
	{
		if (SettingsModified())
			SaveSettings();
	}
	else if (mDialogCancelled)
	{
		if (SettingsModified())
			if (PromptAccept())
				SaveSettings();
	}
}

bool lcBlenderPreferences::SettingsModified(bool Update, const QString& Module)
{
	if  (gAddonPreferences->mDialogCancelled)
		return false;

	int& Width = gAddonPreferences->mImageWidth;
	int& Height = gAddonPreferences->mImageHeight;
	double& Scale = gAddonPreferences->mScale;

	bool ModuleMM = !Module.isEmpty()
						? Module == QLatin1String("MM")
						: gAddonPreferences->mImportMMActBox->isChecked();

	bool Ok, Modified = !QFileInfo(lcGetProfileString(LC_PROFILE_BLENDER_LDRAW_CONFIG_PATH)).isReadable();
	qreal _Width = 0.0, _Height = 0.0, _Scale = 0.0, _Value = 0.0, _OldValue = 0.0;
	QString OldValue;

	auto ItemChanged = [](qreal OldValue, qreal NewValue)
	{
		return NewValue > OldValue || NewValue < OldValue;
	};

	if (ModuleMM)
	{
		for (int LblIdx = 0; LblIdx < NumSettingsMM(); LblIdx++)
		{
			// checkboxes
			if (LblIdx < LBL_BEVEL_SEGMENTS)
			{
				for (int CtlIdx = 0; CtlIdx < gAddonPreferences->mCheckBoxList.size(); CtlIdx++)
				{
					OldValue = mBlenderSettingsMM[LblIdx].value;
					if (Update)
						mBlenderSettingsMM[LblIdx].value = QString::number(gAddonPreferences->mCheckBoxList[CtlIdx]->isChecked());
					Modified |= mBlenderSettingsMM[LblIdx].value != OldValue;
					if (LblIdx < LBL_VERBOSE_MM)
						LblIdx++;
				}
			}
			// lineedits
			else if (LblIdx < LBL_CHOSEN_LOGO)
			{
				for (int CtlIdx = 0; CtlIdx < gAddonPreferences->mLineEditList.size(); CtlIdx++)
				{
					if (CtlIdx == CTL_RESOLUTION_WIDTH_EDIT)
					{
						_OldValue = Width;
						_Width  = gAddonPreferences->mLineEditList[CtlIdx]->text().toDouble(&Ok);
						if (Ok)
						{
							if (Update)
							{
								Width = int(_Width);
								mBlenderSettingsMM[LblIdx].value = QString::number(Width);
							}
							Modified |= ItemChanged(_OldValue, _Width);
						}
					}
					else if (CtlIdx == CTL_RESOLUTION_HEIGHT_EDIT)
					{
						_OldValue = Height;
						_Height = gAddonPreferences->mLineEditList[CtlIdx]->text().toDouble(&Ok);
						if (Ok)
						{
							if (Update)
							{
								Height = int(_Height);
								mBlenderSettingsMM[LblIdx].value = QString::number(Height);
							}
							Modified |= ItemChanged(_OldValue, _Height);
						}
					}
					else if (CtlIdx == CTL_RENDER_PERCENTAGE_EDIT_MM)
					{
						_OldValue = Scale;
						_Scale = gAddonPreferences->mLineEditList[CtlIdx]->text().toInt(&Ok);
						if (Ok)
						{
							if (Update)
							{
								Scale = double(_Scale / 100);
								mBlenderSettingsMM[LblIdx].value = QString::number(_Scale);
							}
							Modified |= ItemChanged(_OldValue, Scale);
						}
					}
					else
					{
						_OldValue = mBlenderSettingsMM[LblIdx].value.toDouble();
						_Value = gAddonPreferences->mLineEditList[CtlIdx]->text().toDouble(&Ok);
						if (Ok)
						{
							if (Update)
								mBlenderSettingsMM[LblIdx].value = QString::number(_Value);
							Modified |= ItemChanged(_OldValue, _Value);
						}
					}
					if (LblIdx < LBL_STARTING_STEP_FRAME)
						LblIdx++;
				}
			}
			// comboboxes
			else
			{
				for (int CtlIdx = 0; CtlIdx < gAddonPreferences->mComboBoxList.size(); CtlIdx++)
				{
					OldValue = mBlenderSettingsMM[LblIdx].value;
					const QString Value = gAddonPreferences->mComboBoxList[CtlIdx]->itemData(gAddonPreferences->mComboBoxList[CtlIdx]->currentIndex()).toString();
					if (Update)
						mBlenderSettingsMM[LblIdx].value = Value;
					Modified |= Value != OldValue;
					LblIdx++;
				}
			}
		}
	}
	else
	{
		// settings
		for (int LblIdx = 0; LblIdx < NumSettings(); LblIdx++)
		{
			// checkboxes
			if (LblIdx < LBL_BEVEL_WIDTH)
			{
				for (int CtlIdx = 0; CtlIdx < gAddonPreferences->mCheckBoxList.size(); CtlIdx++)
				{
					OldValue = mBlenderSettings[LblIdx].value;
					if (Update)
						mBlenderSettings[LblIdx].value = QString::number(gAddonPreferences->mCheckBoxList[CtlIdx]->isChecked());
					Modified |= mBlenderSettings[LblIdx].value != OldValue;
					if (LblIdx < LBL_VERBOSE)
						LblIdx++;
				}
			}
			// lineedits
			else if (LblIdx < LBL_COLOUR_SCHEME)
			{
				for (int CtlIdx = 0; CtlIdx < gAddonPreferences->mLineEditList.size(); CtlIdx++)
				{
					if (CtlIdx == CTL_IMAGE_WIDTH_EDIT)
					{
						_OldValue = Width;
						_Width  = gAddonPreferences->mLineEditList[CtlIdx]->text().toDouble(&Ok);
						if (Ok)
						{
							if (Update)
							{
								Width = int(_Width);
								mBlenderSettings[LblIdx].value = QString::number(Width);
							}
							Modified |= ItemChanged(_OldValue, _Width);
						}
					}
					else if (CtlIdx == CTL_IMAGE_HEIGHT_EDIT)
					{
						_OldValue = Height;
						_Height = gAddonPreferences->mLineEditList[CtlIdx]->text().toDouble(&Ok);
						if (Ok)
						{
							if (Update)
							{
								Height = int(_Height);
								mBlenderSettings[LblIdx].value = QString::number(Height);
							}
							Modified |= ItemChanged(_OldValue, _Height);
						}
					}
					else if (CtlIdx == CTL_RENDER_PERCENTAGE_EDIT)
					{
						_OldValue = Scale;
						_Scale = gAddonPreferences->mLineEditList[CtlIdx]->text().toInt(&Ok);
						if (Ok)
						{
							if (Update)
							{
								Scale = double(_Scale / 100);
								mBlenderSettings[LblIdx].value = QString::number(_Scale);
							}
							Modified |= ItemChanged(_OldValue, Scale);
						}
					}
					else
					{
						if (CtlIdx == CTL_DEFAULT_COLOUR_EDIT)
						{
							_OldValue = lcGetColorIndex(mBlenderSettings[LblIdx].value.toInt());  // colour code
							_Value = gAddonPreferences->mLineEditList[CtlIdx]->property("ColorIndex").toInt(&Ok);
						}
						else
						{
							_OldValue = mBlenderSettings[LblIdx].value.toDouble();
							_Value = gAddonPreferences->mLineEditList[CtlIdx]->text().toDouble(&Ok);
						}
						if (Ok)
						{
							if (Update)
							{
								if (CtlIdx == CTL_DEFAULT_COLOUR_EDIT)
								{
									mBlenderSettings[LblIdx].value = QString::number(lcGetColorCode(qint32(_Value)));
								}
								else
								{
									mBlenderSettings[LblIdx].value = QString::number(_Value);
								}
							}
							Modified |= ItemChanged(_OldValue, _Value);
						}
					}
					if (LblIdx < LBL_RENDER_PERCENTAGE)
						LblIdx++;
				}
			}
			// comboboxes
			else
			{
				for (int CtlIdx = 0; CtlIdx < gAddonPreferences->mComboBoxList.size(); CtlIdx++)
				{
					OldValue = mBlenderSettings[LblIdx].value;
					const QString Value = gAddonPreferences->mComboBoxList[CtlIdx]->itemData(gAddonPreferences->mComboBoxList[CtlIdx]->currentIndex()).toString();
					if (Update)
						mBlenderSettings[LblIdx].value = Value;
					Modified |= Value != OldValue;
					LblIdx++;
				}
			}
		}
	}

	// paths
	for (int LblIdx = 0; LblIdx < NumPaths(); LblIdx++)
	{
		OldValue = mBlenderPaths[LblIdx].value;
		const QString Value = gAddonPreferences->mPathLineEditList[LblIdx]->text();
		if (Update)
			mBlenderPaths[LblIdx].value = Value;
		Modified |= Value != OldValue;
	}

	return Modified;
}

void lcBlenderPreferences::ResetSettings()
{
	BlenderPaths const* Paths = mBlenderPaths;
	BlenderSettings const* Settings = mBlenderSettings;
	BlenderSettings const* SettingsMM = mBlenderSettingsMM;

	QDialog* Dialog = new QDialog(this);
	Dialog->setWindowTitle(tr("Addon Reset"));
	Dialog->setWhatsThis(tr("Select how to reset settings. Choice is since last apply or system default."));
	QVBoxLayout* Layout = new QVBoxLayout(Dialog);
	QGroupBox* DlgGroup = new QGroupBox(Dialog);
	QHBoxLayout* DlgLayout = new QHBoxLayout(DlgGroup);
	QRadioButton* LastButton = new QRadioButton(tr("Last Apply"));
	DlgLayout->addWidget(LastButton);
	QRadioButton* DefaultButton = new QRadioButton(tr("System Default"));
	DlgLayout->addWidget(DefaultButton);
	DlgGroup->setLayout(DlgLayout);
	Layout->addWidget(DlgGroup);
	Dialog->setLayout(Layout);

	LastButton->setChecked(true);

	QDialogButtonBox ButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel,
							   Qt::Horizontal, Dialog);
	Layout->addWidget(&ButtonBox);
	connect(&ButtonBox, SIGNAL(accepted()), Dialog, SLOT(accept()));
	connect(&ButtonBox, SIGNAL(rejected()), Dialog, SLOT(reject()));

	if (Dialog->exec() == QDialog::Accepted)
	{
		if (DefaultButton->isChecked())
		{
			Paths = mDefaultPaths;
			Settings = mDefaultSettings;
			SettingsMM = mDefaultSettingsMM;
		}
	}

	mConfigured = !lcGetProfileString(LC_PROFILE_BLENDER_IMPORT_MODULE).isEmpty();

	mBlenderPaths[PATH_BLENDER].value = lcGetProfileString(LC_PROFILE_BLENDER_PATH);
	mBlenderVersion                   = lcGetProfileString(LC_PROFILE_BLENDER_VERSION);
	mAddonVersion                     = lcGetProfileString(LC_PROFILE_BLENDER_ADDON_VERSION);

	mBlenderVersionEdit->setText(mBlenderVersion);
	mAddonVersionEdit->setText(mAddonVersion);

	if (mImportActBox->isChecked())
	{
		disconnect(mLineEditList[CTL_IMAGE_HEIGHT_EDIT], SIGNAL(textChanged(const QString&)), this, SLOT (SizeChanged(const QString&)));
		disconnect(mLineEditList[CTL_IMAGE_WIDTH_EDIT], SIGNAL(textChanged(const QString&)), this, SLOT (SizeChanged(const QString&)));

		for (int LblIdx = 0; LblIdx < NumSettings(); LblIdx++)
		{
			if (LblIdx < LBL_BEVEL_WIDTH)
			{
				for (int CtlIdx = 0; CtlIdx < mCheckBoxList.size(); CtlIdx++)
				{
					mCheckBoxList[CtlIdx]->setChecked(Settings[LblIdx].value.toInt());
					if (LblIdx < LBL_VERBOSE)
						LblIdx++;
				}
			}
			else if (LblIdx < LBL_COLOUR_SCHEME)
			{
				for (int CtlIdx = 0; CtlIdx < mLineEditList.size(); CtlIdx++)
				{
					if (CtlIdx == CTL_IMAGE_WIDTH_EDIT)
						mLineEditList[CtlIdx]->setText(QString::number(mImageWidth));
					else if (CtlIdx == CTL_IMAGE_HEIGHT_EDIT)
						mLineEditList[CtlIdx]->setText(QString::number(mImageHeight));
					else if (CtlIdx == CTL_RENDER_PERCENTAGE_EDIT)
						mLineEditList[CtlIdx]->setText(QString::number(mScale * 100));
					else if (CtlIdx == CTL_DEFAULT_COLOUR_EDIT)
						SetDefaultColor(lcGetColorIndex(Settings[LBL_DEFAULT_COLOUR].value.toInt()));
					else
						mLineEditList[CtlIdx]->setText(Settings[LblIdx].value);
					if (LblIdx < LBL_RENDER_PERCENTAGE)
						LblIdx++;
				}
			}
			else
			{
				for (int CtlIdx = 0; CtlIdx < mComboBoxList.size(); CtlIdx++)
				{
					mComboBoxList[CtlIdx]->setCurrentIndex(int(mComboBoxList[CtlIdx]->findData(QVariant::fromValue(Settings[LblIdx].value))));
					LblIdx++;
				}
			}
		}

		for (int LblIdx = 0; LblIdx < NumPaths(); LblIdx++)
		{
			mPathLineEditList[LblIdx]->setText(Paths[LblIdx].value);
		}

		connect(mLineEditList[CTL_IMAGE_HEIGHT_EDIT],SIGNAL(textChanged(const QString&)), this, SLOT (SizeChanged(const QString&)));
		connect(mLineEditList[CTL_IMAGE_WIDTH_EDIT], SIGNAL(textChanged(const QString&)), this, SLOT (SizeChanged(const QString&)));
	}
	else if (mImportMMActBox->isChecked())
	{
		disconnect(mLineEditList[CTL_RESOLUTION_HEIGHT_EDIT], SIGNAL(textChanged(const QString&)), this, SLOT (SizeChanged(const QString&)));
		disconnect(mLineEditList[CTL_RESOLUTION_WIDTH_EDIT], SIGNAL(textChanged(const QString&)), this, SLOT (SizeChanged(const QString&)));

		for (int LblIdx = 0; LblIdx < NumSettingsMM(); LblIdx++)
		{
			if (LblIdx < LBL_BEVEL_SEGMENTS)
			{
				for (int CtlIdx = 0; CtlIdx < mCheckBoxList.size(); CtlIdx++)
				{
					mCheckBoxList[CtlIdx]->setChecked(SettingsMM[LblIdx].value.toInt());
					if (LblIdx < LBL_VERBOSE_MM)
						LblIdx++;
				}
			}
			else if (LblIdx < LBL_CHOSEN_LOGO)
			{
				for (int CtlIdx = 0; CtlIdx < mLineEditList.size(); CtlIdx++)
				{
					if (CtlIdx == CTL_RESOLUTION_WIDTH_EDIT)
						mLineEditList[CtlIdx]->setText(QString::number(mImageWidth));
					else if (CtlIdx == CTL_RESOLUTION_HEIGHT_EDIT)
						mLineEditList[CtlIdx]->setText(QString::number(mImageHeight));
					else if (CtlIdx == CTL_RENDER_PERCENTAGE_EDIT_MM)
						mLineEditList[CtlIdx]->setText(QString::number(mScale * 100));
					else
						mLineEditList[CtlIdx]->setText(SettingsMM[LblIdx].value);
					if (LblIdx < LBL_STARTING_STEP_FRAME)
						LblIdx++;
				}
			}
			else
			{
				for (int CtlIdx = 0; CtlIdx < mComboBoxList.size(); CtlIdx++)
				{
					mComboBoxList[CtlIdx]->setCurrentIndex(int(mComboBoxList[CtlIdx]->findData(QVariant::fromValue(SettingsMM[LblIdx].value))));
					LblIdx++;
				}
			}
		}

		for (int LblIdx = 0; LblIdx < NumPaths(); LblIdx++)
		{
			mPathLineEditList[LblIdx]->setText(Paths[LblIdx].value);
		}

		connect(mLineEditList[CTL_RESOLUTION_HEIGHT_EDIT], SIGNAL(textChanged(const QString&)), this, SLOT (SizeChanged(const QString&)));
		connect(mLineEditList[CTL_RESOLUTION_WIDTH_EDIT], SIGNAL(textChanged(const QString&)), this, SLOT (SizeChanged(const QString&)));
	}

	emit SettingChangedSig(true);
}

void lcBlenderPreferences::LoadSettings()
{
	QStringList const& DataPathList = QStandardPaths::standardLocations(QStandardPaths::AppLocalDataLocation);
	gAddonPreferences->mDataDir = DataPathList.first();

	if (QFileInfo(lcGetProfileString(LC_PROFILE_BLENDER_PATH)).isReadable())
	{
		if (lcGetProfileString(LC_PROFILE_BLENDER_IMPORT_MODULE).isEmpty())
			lcSetProfileString(LC_PROFILE_BLENDER_IMPORT_MODULE, QLatin1String(LC_BLENDER_ADDON_IMPORT_MODULE));
	}
	else
	{
		lcSetProfileString(LC_PROFILE_BLENDER_PATH, QString());
		lcSetProfileString(LC_PROFILE_BLENDER_IMPORT_MODULE, QString());
	}

	if (!QDir(QString("%1/Blender/addons/%2").arg(gAddonPreferences->mDataDir).arg(LC_BLENDER_ADDON_RENDER_FOLDER)).isReadable())
		lcSetProfileString(LC_PROFILE_BLENDER_IMPORT_MODULE, QString());

	bool UseArchiveLibrary = false;
	auto LDrawPartsLibrary = [&] (QString const& LDrawPath)
	{
		QString LDrawDir = LDrawPath;

		const QFileInfo FileInfo(LDrawDir);
		if (FileInfo.isFile())
			LDrawDir = FileInfo.absolutePath();

		const QString Suffix = FileInfo.suffix().toLower();
		const QFileInfo PartInfo(QString("%1/p/1-4cyli.dat").arg(LDrawDir));
		const QFileInfo LDConfigInfo(QString("%1/LDConfig.ldr").arg(LDrawDir));

		UseArchiveLibrary = (Suffix == "zip" || Suffix == "bin") && !(PartInfo.exists() && LDConfigInfo.exists());

		return QDir::toNativeSeparators(LDrawDir);
	};

	if (!NumPaths())
	{
		const QString DefaultBlendFile = QString("%1/Blender/config/%2").arg(gAddonPreferences->mDataDir).arg(LC_BLENDER_ADDON_BLEND_FILE);

		QStringList const AddonPaths = QStringList()
		/* 0  PATH_BLENDER      */        << lcGetProfileString(LC_PROFILE_BLENDER_PATH)
		/* 1  PATH_BLENDFILE    */        << (QFileInfo(DefaultBlendFile).exists() ? DefaultBlendFile : QString())
		/* 2  PATH_ENVIRONMENT  */        << QString()
		/* 3  PATH_LDCONFIG     */        << lcGetProfileString(LC_PROFILE_COLOR_CONFIG)
		/* 4  PATH_LDRAW        */        << LDrawPartsLibrary(lcGetProfileString(LC_PROFILE_PARTS_LIBRARY))
		/* 5  PATH_LSYNTH       */        << QString()
		/* 6  PATH_STUD_LOGO    */        << QString()
		/* 7  PATH_STUDIO_LDRAW */        << QString()
		/* 8  PATH_STUDIO_CUSTOM_PARTS */ << QString();
		for (int LblIdx = 0; LblIdx < NumPaths(DEFAULT_SETTINGS); LblIdx++)
		{
			mBlenderPaths[LblIdx] =
				{
					mDefaultPaths[LblIdx].key,
					mDefaultPaths[LblIdx].key_mm,
					QDir::toNativeSeparators(AddonPaths.at(LblIdx)),
					mDefaultPaths[LblIdx].label,
					mDefaultPaths[LblIdx].tooltip
				};
		}
	}

	if (!NumSettings())
	{
		for (int LblIdx = 0; LblIdx < NumSettings(DEFAULT_SETTINGS); LblIdx++)
		{
			mBlenderSettings[LblIdx] =
				{
					mDefaultSettings[LblIdx].key,
					mDefaultSettings[LblIdx].value,
					mDefaultSettings[LblIdx].label,
					mDefaultSettings[LblIdx].tooltip
				};
			if (LblIdx == LBL_USE_ARCHIVE_LIBRARY)
				mBlenderSettings[LblIdx].value = QString::number(UseArchiveLibrary);
		}
	}

	if (!NumSettingsMM())
	{
		for (int LblIdx = 0; LblIdx < NumSettingsMM(DEFAULT_SETTINGS); LblIdx++)
		{
			mBlenderSettingsMM[LblIdx] =
				{
					mDefaultSettingsMM[LblIdx].key,
					mDefaultSettingsMM[LblIdx].value,
					mDefaultSettingsMM[LblIdx].label,
					mDefaultSettingsMM[LblIdx].tooltip
				};
			if (LblIdx == LBL_USE_ARCHIVE_LIBRARY_MM)
				mBlenderSettingsMM[LblIdx].value = QString::number(UseArchiveLibrary);
		}
	}

	QFileInfo BlenderConfigFileInfo(lcGetProfileString(LC_PROFILE_BLENDER_LDRAW_CONFIG_PATH));

	if (BlenderConfigFileInfo.exists())
	{
		QSettings Settings(BlenderConfigFileInfo.absoluteFilePath(), QSettings::IniFormat);

		for (int LblIdx = 1/*skip blender executable*/; LblIdx < NumPaths(); LblIdx++)
		{
			if (LblIdx >= PATH_STUDIO_LDRAW)
				continue;
			const QString& Key = QString("%1/%2").arg(LC_BLENDER_ADDON, mBlenderPaths[LblIdx].key);
			const QString& Value = Settings.value(Key, QString()).toString();
			if (QFileInfo(Value).exists())
				mBlenderPaths[LblIdx].value = QDir::toNativeSeparators(Value);
		}

		for (int LblIdx = 1/*skip blender executable*/; LblIdx < NumPaths(); LblIdx++)
		{
			if (LblIdx == PATH_LSYNTH || LblIdx == PATH_STUD_LOGO)
				continue;
			const QString& Key = QString("%1/%2").arg(LC_BLENDER_ADDON_MM, mBlenderPaths[LblIdx].key_mm);
			const QString& Value = Settings.value(Key, QString()).toString();
			if (QFileInfo(Value).exists())
				mBlenderPaths[LblIdx].value = QDir::toNativeSeparators(Value);
		}

		for (int LblIdx = 0; LblIdx < NumSettings(); LblIdx++)
		{
			const QString& Key = QString("%1/%2").arg(LC_BLENDER_ADDON, mBlenderSettings[LblIdx].key);
			const QString& Value = Settings.value(Key, QString()).toString();
			if (!Value.isEmpty())
			{
				if (LblIdx == LBL_USE_ARCHIVE_LIBRARY && Value == "False")
					mBlenderSettings[LblIdx].value = QString::number(UseArchiveLibrary);
				else
					mBlenderSettings[LblIdx].value = Value == "True" ? "1" : Value == "False" ? "0" : Value;
			}
			if (LblIdx == LBL_IMAGE_WIDTH || LblIdx == LBL_IMAGE_HEIGHT || LblIdx == LBL_RENDER_PERCENTAGE)
			{
				const QString& Label = mDefaultSettings[LblIdx].label;
				mBlenderSettings[LblIdx].label = QString("%1 - Setting (%2)").arg(Label).arg(Value);
			}
		}

		for (int LblIdx = 0; LblIdx < NumSettingsMM(); LblIdx++)
		{
			const QString& Key = QString("%1/%2").arg(LC_BLENDER_ADDON_MM, mBlenderSettingsMM[LblIdx].key);
			const QString& Value = Settings.value(Key, QString()).toString();
			if (!Value.isEmpty())
			{
				if (LblIdx == LBL_USE_ARCHIVE_LIBRARY_MM && Value == "False")
					mDefaultSettingsMM[LblIdx].value = QString::number(UseArchiveLibrary);
				else
					mDefaultSettingsMM[LblIdx].value = Value == "True" ? "1" : Value == "False" ? "0" : Value;
			}
			if (LblIdx == LBL_RENDER_PERCENTAGE_MM || LblIdx == LBL_RESOLUTION_WIDTH || LblIdx == LBL_RESOLUTION_HEIGHT)
			{
				const QString& Label = mDefaultSettingsMM[LblIdx].label;
				mBlenderSettingsMM[LblIdx].label = QString("%1 - Setting (%2)").arg(Label).arg(Value);
			}
		}
	}
	else
	{
		const QString LogFile = QString("%1/Blender/stdout-blender-addon-install").arg(gAddonPreferences->mDataDir);
		if (QFileInfo(LogFile).isReadable())
		{
			QFile File(LogFile);
			if (File.open(QFile::ReadOnly | QFile::Text))
			{
				QByteArray Ba = File.readAll();
				File.close();
				QString Errors;
				gAddonPreferences->mProgressBar = nullptr;
				gAddonPreferences->ReadStdOut(QString(Ba), Errors);

				if (!Errors.isEmpty())
					ShowMessage(nullptr, Errors);
			}
			else
			{
				ShowMessage(nullptr, tr("Blender config file was not found. "
							   "Install log check failed:<br>%1:<br>%2")
								.arg(File.fileName())
								.arg(File.errorString()));
			}
		}
	}

	mBlenderSettings[LBL_IMAGE_WIDTH].value = QString::number(gAddonPreferences->mImageWidth);
	mBlenderSettings[LBL_IMAGE_HEIGHT].value = QString::number(gAddonPreferences->mImageHeight);
	mBlenderSettings[LBL_RENDER_PERCENTAGE].value = QString::number(gAddonPreferences->mScale * 100);

	mBlenderSettingsMM[LBL_RESOLUTION_WIDTH].value = QString::number(gAddonPreferences->mImageWidth);
	mBlenderSettingsMM[LBL_RESOLUTION_HEIGHT].value = QString::number(gAddonPreferences->mImageHeight);
	mBlenderSettingsMM[LBL_RENDER_PERCENTAGE_MM].value = QString::number(gAddonPreferences->mScale * 100);

	mBlenderPaths[PATH_BLENDER].value = lcGetProfileString(LC_PROFILE_BLENDER_PATH);
	gAddonPreferences->mBlenderVersion = lcGetProfileString(LC_PROFILE_BLENDER_VERSION);
	gAddonPreferences->mAddonVersion = lcGetProfileString(LC_PROFILE_BLENDER_ADDON_VERSION);
}

void lcBlenderPreferences::SaveSettings()
{
	if (!NumSettings() || !NumSettingsMM())
		LoadSettings();

	QString Key, Value = mBlenderPaths[PATH_BLENDER].value;
	if (Value.isEmpty())
		Value = gAddonPreferences->mPathLineEditList[PATH_BLENDER]->text();

	lcSetProfileString(LC_PROFILE_BLENDER_PATH, QDir::toNativeSeparators(Value));

	Value.clear();
	if (!gAddonPreferences->mBlenderVersion.isEmpty())
		Value = gAddonPreferences->mBlenderVersion;

	if (!gAddonPreferences->mAddonVersion.isEmpty())
	{
		gAddonPreferences->mModulesBox->setEnabled(true);
		gAddonPreferences->mAddonVersionEdit->setText(gAddonPreferences->mAddonVersion);
	}

	lcSetProfileString(LC_PROFILE_BLENDER_VERSION, Value);

	const QString BlenderConfigDir = QString("%1/Blender/addons/%2/config").arg(gAddonPreferences->mDataDir).arg(LC_BLENDER_ADDON_RENDER_FOLDER);
	
	Value = lcGetProfileString(LC_PROFILE_BLENDER_LDRAW_CONFIG_PATH);
	if (!Value.contains(LC_BLENDER_ADDON_RENDER_FOLDER))
	{
		Value = QString("%1/%2").arg(BlenderConfigDir).arg(LC_BLENDER_ADDON_CONFIG_FILE);
		lcSetProfileString(LC_PROFILE_BLENDER_LDRAW_CONFIG_PATH, QDir::toNativeSeparators(Value));
	}

	QString searchDirectoriesKey = QLatin1String("additionalSearchPaths");
	QString parameterFileKey = QLatin1String("ParameterFile");
	QString ParameterFile = QString("%1/%2").arg(BlenderConfigDir).arg(LC_BLENDER_ADDON_PARAMS_FILE);

	QSettings Settings(Value, QSettings::IniFormat);

	auto concludeSettingsGroup = [&]()
	{
		if (!QFileInfo(ParameterFile).exists())
			ExportParameterFile();
		Value = QDir::toNativeSeparators(QFileInfo(lcGetProfileString(LC_PROFILE_PROJECTS_PATH)).absolutePath());
		Settings.setValue(searchDirectoriesKey, QVariant(Value));
		Settings.endGroup();
	};

	Settings.beginGroup(LC_BLENDER_ADDON);

	for (int LblIdx = 1/*skip blender executable*/; LblIdx < NumPaths(); LblIdx++)
	{
		if (LblIdx >= PATH_STUDIO_LDRAW)
			continue;
		Key = mBlenderPaths[LblIdx].key;
		Value = QDir::toNativeSeparators(mBlenderPaths[LblIdx].value);

		if (!Key.isEmpty())
			Settings.setValue(Key, QVariant(Value));
	}

	for (int LblIdx = 0; LblIdx < NumSettings(); LblIdx++)
	{
		if (LblIdx == LBL_KEEP_ASPECT_RATIO)
		{
			continue;
		}
		else if (LblIdx < LBL_BEVEL_WIDTH)
		{
			Value = mBlenderSettings[LblIdx].value == "1" ? "True" : "False";
		}
		else if (LblIdx > LBL_VERBOSE)
		{
			if (LblIdx == LBL_FLEX_PARTS_SOURCE || LblIdx == LBL_POSITION_OBJECT)
				Value = mBlenderSettings[LblIdx].value == "1" ? "True" : "False";
			else
				Value = mBlenderSettings[LblIdx].value;
		}

		Key = mBlenderSettings[LblIdx].key;

		if (!Key.isEmpty())
			Settings.setValue(Key, QVariant(Value));
	}

	Settings.setValue(parameterFileKey, QVariant(QDir::toNativeSeparators(ParameterFile)));

	concludeSettingsGroup();

	Settings.beginGroup(LC_BLENDER_ADDON_MM);

	for (int LblIdx = 1/*skip blender executable*/; LblIdx < NumPaths(); LblIdx++)
	{
		if (LblIdx == PATH_LSYNTH || LblIdx == PATH_STUD_LOGO)
			continue;
		Key = mBlenderPaths[LblIdx].key_mm;
		Value = QDir::toNativeSeparators(mBlenderPaths[LblIdx].value);

		if (!Key.isEmpty())
			Settings.setValue(Key, QVariant(Value));
	}

	for (int LblIdx = 0; LblIdx < NumSettingsMM(); LblIdx++)
	{
		if (LblIdx == LBL_KEEP_ASPECT_RATIO_MM)
		{
			continue;
		}
		else if (LblIdx < LBL_BEVEL_SEGMENTS)
		{
			Value = mBlenderSettingsMM[LblIdx].value == "1" ? "True" : "False";
		}
		else if (LblIdx > LBL_VERBOSE_MM)
		{
			Value = mBlenderSettingsMM[LblIdx].value;
		}

		Key = mBlenderSettingsMM[LblIdx].key;

		if (!Key.isEmpty())
			Settings.setValue(Key, QVariant(Value));
	}

	concludeSettingsGroup();

	const QString preferredImportModule = gAddonPreferences->mImportActBox->isChecked() ? QString("TN") : gAddonPreferences->mImportMMActBox->isChecked() ? QString("MM") : QString();

	if (preferredImportModule != lcGetProfileString(LC_PROFILE_BLENDER_IMPORT_MODULE))
		lcSetProfileString(LC_PROFILE_BLENDER_IMPORT_MODULE, preferredImportModule);
}

void lcBlenderPreferences::EnableImportModule()
{
	QString saveImportModule, preferredImportModule;
	if (sender() == mImportActBox && mImportActBox->isChecked())
	{
		preferredImportModule = QLatin1String("TN");
		if (mImportMMActBox->isChecked())
			saveImportModule = QLatin1String("MM");
		mImportMMActBox->setChecked(false);
	}
	else if (sender() == mImportMMActBox && mImportMMActBox->isChecked())
	{
		preferredImportModule = QLatin1String("MM");
		if (mImportActBox->isChecked())
			saveImportModule = QLatin1String("TN");
		mImportActBox->setChecked(false);
	}

	if (preferredImportModule.isEmpty())
		return;

	if (SettingsModified(true, saveImportModule))
		SaveSettings();

	lcSetProfileString(LC_PROFILE_BLENDER_IMPORT_MODULE, preferredImportModule);

	if (mImportMMActBox->isChecked())
		InitPathsAndSettingsMM();
	else
		InitPathsAndSettings();

	ConfigureBlenderAddon(false, false, true);
}

int lcBlenderPreferences::NumSettings(bool DefaultSettings)
{
	int Size = 0;
	if (!mBlenderSettings[0].key.isEmpty() || DefaultSettings)
		Size = sizeof(mBlenderSettings)/sizeof(mBlenderSettings[0]);
	return Size;
}

int lcBlenderPreferences::NumSettingsMM(bool DefaultSettings)
{
	int Size = 0;
	if (!mBlenderSettingsMM[0].key.isEmpty() || DefaultSettings)
		Size = sizeof(mBlenderSettingsMM)/sizeof(mBlenderSettingsMM[0]);
	return Size;
}

int lcBlenderPreferences::NumPaths(bool DefaultSettings)
{
	int Size = 0;
	if (!mBlenderPaths[0].key.isEmpty() || DefaultSettings)
		Size = sizeof(mBlenderPaths)/sizeof(mBlenderPaths[0]);
	return Size;
}

void lcBlenderPreferences::ShowPathsGroup()
{
	if (mPathsBox->isHidden())
		mPathsBox->show();
	else
		mPathsBox->hide();

	mContent->adjustSize();
}

void lcBlenderPreferences::ColorButtonClicked(bool)
{
	int ColorIndex = mLineEditList[CTL_DEFAULT_COLOUR_EDIT]->property("ColorIndex").toInt();

	QWidget* Parent = mLineEditList[CTL_DEFAULT_COLOUR_EDIT];
	lcColorPickerPopup* Popup = new lcColorPickerPopup(Parent, ColorIndex);
	connect(Popup, SIGNAL(selected(int)), SLOT(SetDefaultColor(int)));
	Popup->setMinimumSize(300, 200);

#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
	QScreen* Screen = screen();
	const QRect DesktopGeom = Screen ? Screen->geometry() : QRect();
#else
	const QRect DesktopGeom = QApplication::desktop()->geometry();
#endif

	QPoint Pos = Parent->mapToGlobal(Parent->rect().bottomLeft());
	if (Pos.x() < DesktopGeom.left())
		Pos.setX(DesktopGeom.left());

	if (Pos.y() < DesktopGeom.top())
		Pos.setY(DesktopGeom.top());

	if ((Pos.x() + Popup->width()) > DesktopGeom.width())
		Pos.setX(DesktopGeom.width() - Popup->width());

	if ((Pos.y() + Popup->height()) > DesktopGeom.bottom())
		Pos.setY(DesktopGeom.bottom() - Popup->height());

	Popup->move(Pos);

	Popup->setFocus();
	Popup->show();
}

void lcBlenderPreferences::SetDefaultColor(int ColorIndex)
{
	QImage Image(12, 12, QImage::Format_ARGB32);
	Image.fill(0);

	lcColor* Colour =& gColorList[ColorIndex];
	QPainter Painter(&Image);
	Painter.setCompositionMode(QPainter::CompositionMode_Source);
	Painter.setPen(Qt::darkGray);
	Painter.setBrush(QColor::fromRgbF(qreal(Colour->Value[0]), qreal(Colour->Value[1]), qreal(Colour->Value[2])));
	Painter.drawRect(0, 0, Image.width() - 1, Image.height() - 1);
	Painter.end();

	int const ColourCode = lcGetColorCode(ColorIndex);
	mLineEditList[CTL_DEFAULT_COLOUR_EDIT]->setText(QString("%1 (%2)").arg(Colour->Name).arg(ColourCode));
	mLineEditList[CTL_DEFAULT_COLOUR_EDIT]->setProperty("ColorIndex", QVariant::fromValue(ColorIndex));
	mDefaultColourEditAction->setIcon(QPixmap::fromImage(Image));
	mDefaultColourEditAction->setToolTip(tr("Select Colour"));

	bool Change = mBlenderSettings[LBL_DEFAULT_COLOUR].value != QString::number(ColourCode);
	Change |= SettingsModified(false);
	emit SettingChangedSig(Change);
}

void lcBlenderPreferences::BrowseBlender(bool)
{
	for (int LblIdx = 0; LblIdx < NumPaths(); ++LblIdx)
	{
		if (sender() == mPathBrowseButtonList.at(LblIdx))
		{
			const QString BlenderPath = QDir::toNativeSeparators(mBlenderPaths[LblIdx].value).toLower();
			QFileDialog FileDialog(nullptr);
			FileDialog.setWindowTitle(tr("Locate %1").arg(mBlenderPaths[LblIdx].label));
			if (LblIdx < PATH_LDRAW)
				FileDialog.setFileMode(QFileDialog::ExistingFile);
			else
				FileDialog.setFileMode(QFileDialog::Directory);
			if (!BlenderPath.isEmpty())
				FileDialog.setDirectory(QFileInfo(BlenderPath).absolutePath());
			if (FileDialog.exec())
			{
				QStringList SelectedPathList = FileDialog.selectedFiles();
				if (SelectedPathList.size() == 1)
				{
					QFileInfo  PathInfo(SelectedPathList.at(0));
					if (PathInfo.exists())
					{
						const QString SelectedPath = QDir::toNativeSeparators(PathInfo.absoluteFilePath()).toLower();
						mPathLineEditList[LblIdx]->setText(SelectedPathList.at(0));
						if (LblIdx != PATH_BLENDER)
						{
							bool Change = false;
							if (mImportMMActBox->isChecked())
								Change = QDir::toNativeSeparators(mBlenderSettingsMM[LblIdx].value).toLower() != SelectedPath;
							else
								Change = QDir::toNativeSeparators(mBlenderSettings[LblIdx].value).toLower() != SelectedPath;
							Change |= SettingsModified(false);
							emit SettingChangedSig(Change);
						}

						if (LblIdx == PATH_BLENDER && BlenderPath != SelectedPath)
						{
							mBlenderPaths[LblIdx].value = SelectedPath;
							UpdateBlenderAddon();
						}
					}
				}
			}
		}
	}
}

void lcBlenderPreferences::SizeChanged(const QString& Value)
{
	const bool ImportMM = mImportMMActBox->isChecked();
	const int Keep_Aspect_Ratio = ImportMM ? int(CTL_KEEP_ASPECT_RATIO_BOX_MM) : int(CTL_KEEP_ASPECT_RATIO_BOX);
	const int Width_Edit = ImportMM ? int(CTL_RESOLUTION_WIDTH_EDIT) : int(CTL_IMAGE_WIDTH_EDIT);
	const int Height_Edit = ImportMM ? int(CTL_RESOLUTION_HEIGHT_EDIT) : int(CTL_IMAGE_HEIGHT_EDIT);
	BlenderSettings const* Settings = ImportMM ? mBlenderSettingsMM : mBlenderSettings;

	bool Change = false;
	int NewValue = Value.toInt();
	if (mCheckBoxList[Keep_Aspect_Ratio]->isChecked())
	{
		if (sender() == mLineEditList[Width_Edit])
		{
			disconnect(mLineEditList[Height_Edit],SIGNAL(textChanged(const QString&)), this, SLOT (SizeChanged(const QString&)));

			const QString Height = QString::number(qRound(double(mImageHeight * NewValue / mImageWidth)));
			mLineEditList[Height_Edit]->setText(Height);

			Change = Settings[Height_Edit].value != Height;

			connect(mLineEditList[Height_Edit],SIGNAL(textChanged(const QString&)), this, SLOT (SizeChanged(const QString&)));
		}
		else if (sender() == mLineEditList[Height_Edit])
		{
			disconnect(mLineEditList[Width_Edit],SIGNAL(textChanged(const QString&)), this, SLOT (SizeChanged(const QString&)));

			const QString Width = QString::number(qRound(double(NewValue * mImageWidth / mImageHeight)));
			mLineEditList[Width_Edit]->setText(Width);

			Change = Settings[Height_Edit].value != Width;

			connect(mLineEditList[Width_Edit],SIGNAL(textChanged(const QString&)), this, SLOT (SizeChanged(const QString&)));
		}

		// Change is provided here for consistency only as ImageWidth,
		// ImageHeight, and RenderPercentage are passed at the render command
		Change |= SettingsModified(false);
		emit SettingChangedSig(Change);
	}
}

void lcBlenderPreferences::SetModelSize(bool Update)
{
	const bool ImportMM = mImportMMActBox->isChecked();
	const int Crop_Image = ImportMM ? int(CTL_CROP_IMAGE_BOX_MM) : int(CTL_CROP_IMAGE_BOX);
	const int Add_Environment = ImportMM ? int(CTL_ADD_ENVIRONMENT_BOX_MM) : int(CTL_ADD_ENVIRONMENT_BOX);
	const int Trans_Background = ImportMM ? int(CTL_TRANSPARENT_BACKGROUND_BOX_MM) : int(CTL_TRANSPARENT_BACKGROUND_BOX);
	const int Keep_Aspect_Ratio = ImportMM ? int(CTL_KEEP_ASPECT_RATIO_BOX_MM) : int(CTL_KEEP_ASPECT_RATIO_BOX);
	const int Width_Edit = ImportMM ? int(CTL_RESOLUTION_WIDTH_EDIT) : int(CTL_IMAGE_WIDTH_EDIT);
	const int Height_Edit = ImportMM ? int(CTL_RESOLUTION_HEIGHT_EDIT) : int(CTL_IMAGE_HEIGHT_EDIT);
	const int Crop_Image_Label = ImportMM ? int(LBL_CROP_IMAGE_MM) : int(LBL_CROP_IMAGE);

	const QString CropImageLabel = mSettingLabelList[Crop_Image_Label]->text();

	int ImageWidth = mImageWidth;
	int ImageHeight = mImageHeight;

	const bool CropImage = mCheckBoxList[Crop_Image]->isChecked();

	lcModel* Model = lcGetActiveProject()->GetActiveModel();
	if (Model)
	{
		struct NativeImage
		{
			QImage RenderedImage;
			QRect Bounds;
		};

		std::vector<NativeImage> Images;
		Images.push_back(NativeImage());
		NativeImage& Image = Images.back();
		Image.RenderedImage = Model->GetStepImage(false, ImageWidth, ImageHeight, Model->GetCurrentStep());

		auto CalculateImageBounds = [](NativeImage& Image)
		{
			QImage& RenderedImage = Image.RenderedImage;
			int Width  = RenderedImage.width();
			int Height = RenderedImage.height();

			int MinX = Width;
			int MinY = Height;
			int MaxX = 0;
			int MaxY = 0;

			for (int x = 0; x < Width; x++)
			{
				for (int y = 0; y < Height; y++)
				{
					if (qAlpha(RenderedImage.pixel(x, y)))
					{
						MinX = qMin(x, MinX);
						MinY = qMin(y, MinY);
						MaxX = qMax(x, MaxX);
						MaxY = qMax(y, MaxY);
					}
				}
			}

			Image.Bounds = QRect(QPoint(MinX, MinY), QPoint(MaxX, MaxY));
		};

		QtConcurrent::blockingMap(Images, CalculateImageBounds);

		ImageWidth = Image.Bounds.width();
		ImageHeight = Image.Bounds.height();
	}

	mSettingLabelList[Crop_Image_Label]->setText(QString("%1 (%2 x %3)").arg(CropImageLabel).arg(ImageWidth).arg(ImageHeight));

	if (CropImage)
	{
		bool Conflict[3];

		if ((Conflict[1] = mCheckBoxList[Add_Environment]->isChecked()))
			mCheckBoxList[Add_Environment]->setChecked(!CropImage);
		if ((Conflict[2] = !mCheckBoxList[Trans_Background]->isChecked()))
			mCheckBoxList[Trans_Background]->setChecked(CropImage);
		if ((Conflict[0] = mCheckBoxList[Keep_Aspect_Ratio]->isChecked()))
			mCheckBoxList[Keep_Aspect_Ratio]->setChecked(!CropImage);

		if (Conflict[0] || Conflict[1] || Conflict[2])
		{
			const QString& Title = tr ("LDraw Render Settings Conflict");
			const QString& Header = "<b>" + tr ("Crop image configuration settings conflict were resolved.") + "</b>";
			const QString& Body = QString("%1%2%3").arg(Conflict[0] ? tr("Keep aspect ratio set to false.<br>") : "").arg(Conflict[1] ? tr("Add environment (backdrop and base plane) set to false.<br>") : "").arg(Conflict[2] ? tr("Transparent background set to true.<br>") : "");
			ShowMessage(this, Header, Title, Body, QString(), MBB_OK, QMessageBox::Information);
		}
	}

	disconnect(mLineEditList[Width_Edit],SIGNAL(textChanged(const QString&)), this, SLOT (SizeChanged(const QString&)));
	disconnect(mLineEditList[Height_Edit],SIGNAL(textChanged(const QString&)), this, SLOT (SizeChanged(const QString&)));

	const QString Width = QString::number(CropImage ? ImageWidth : mImageWidth);
	const QString Height = QString::number(CropImage ? ImageHeight : mImageHeight);

	mLineEditList[Width_Edit]->setText(Width);
	mLineEditList[Height_Edit]->setText(Height);

	if (Update)
		SettingsModified(true);

	connect(mLineEditList[Height_Edit],SIGNAL(textChanged(const QString&)), this, SLOT (SizeChanged(const QString&)));
	connect(mLineEditList[Width_Edit],SIGNAL(textChanged(const QString&)), this, SLOT (SizeChanged(const QString&)));
}

void lcBlenderPreferences::ValidateColourScheme(int Index)
{
	QComboBox* ComboBox = qobject_cast<QComboBox*>(sender());
	if (!ComboBox)
		return;

	const bool ImportMM = mImportMMActBox->isChecked();
	const int Color_Scheme = ImportMM ? int(LBL_COLOUR_SCHEME_MM) : int(LBL_COLOUR_SCHEME);
	BlenderSettings* Settings = ImportMM ? mBlenderSettingsMM : mBlenderSettings;

	if (ComboBox->itemText(Index) == "custom" && mBlenderPaths[PATH_LDCONFIG].value.isEmpty() && lcGetProfileString(LC_PROFILE_COLOR_CONFIG).isEmpty())
	{
		BlenderSettings const* defaultSettings = ImportMM ? mDefaultSettingsMM : mDefaultSettings;
		Settings[Color_Scheme].value = defaultSettings[Color_Scheme].value;

		const QString& Title = tr ("Custom LDraw Colours");
		const QString& Header = "<b>" + tr ("Colour scheme 'custom' cannot be enabled. Custom LDConfig file not found.") + "</b>";
		const QString& Body = tr ("Colour scheme 'custom' selected but no LDConfig file was specified.<br>The default colour scheme '%1' will be used.<br>").arg(Settings[Color_Scheme].value);
		ShowMessage(this, Header, Title, Body, QString(), MBB_OK, QMessageBox::Warning);
	}
	else
	{
		bool Change = Settings[Color_Scheme].value != ComboBox->itemText(Index);
		Change |= SettingsModified(false);
		emit SettingChangedSig(Change);
	}
}

bool lcBlenderPreferences::PromptAccept()
{
	 const QString& Title = tr ("Render Settings Modified");
	 const QString& Header = "<b>" + tr("Do you want to accept the modified settings before quitting ?") + "</b>";
	int Exec = ShowMessage(this, Header, Title, QString(), QString(), MBB_YES_NO, QMessageBox::Question);
	if (Exec == QMessageBox::Yes)
		return true;

	return false;
}

void lcBlenderPreferences::LoadDefaultParameters(QByteArray& Buffer, int Which)
{
	/*
	# File: BlenderLDrawParameters.lst
	#
	# This config file captures parameters for the Blender LDraw Render addon
	# Parameters must be prefixed using one of the following predefined
	# 'Item' labels:
	# - lgeo_colour
	# - sloped_brick
	# - light_brick

	# LGEO CUSTOM COLOURS
	# LGEO is a parts library for rendering LEGO using the POV-Ray
	# rendering software. This is the list of LEGO colours suitable
	# for realistic rendering extracted from the LGEO file 'lg_color.inc'.
	# When the 'Colour Scheme' option is set to 'Realistic', the standard
	# LDraw colours RGB value is overwritten with the values defined here.
	# Note: You can customize these RGB values as you want.

	#   Item-------  ID--    R--   G--   B--
	*/
	const char DefaultCustomColours[] =
		{
			"lgeo_colour,   0,    33,   33,   33\n"
			"lgeo_colour,   1,    13,  105,  171\n"
			"lgeo_colour,   2,    40,  127,   70\n"
			"lgeo_colour,   3,     0,  143,  155\n"
			"lgeo_colour,   4,   196,   40,   27\n"
			"lgeo_colour,   5,   205,   98,  152\n"
			"lgeo_colour,   6,    98,   71,   50\n"
			"lgeo_colour,   7,   161,  165,  162\n"
			"lgeo_colour,   8,   109,  110,  108\n"
			"lgeo_colour,   9,   180,  210,  227\n"
			"lgeo_colour,   10,   75,  151,   74\n"
			"lgeo_colour,   11,   85,  165,  175\n"
			"lgeo_colour,   12,  242,  112,   94\n"
			"lgeo_colour,   13,  252,  151,  172\n"
			"lgeo_colour,   14,  245,  205,   47\n"
			"lgeo_colour,   15,  242,  243,  242\n"
			"lgeo_colour,   17,  194,  218,  184\n"
			"lgeo_colour,   18,  249,  233,  153\n"
			"lgeo_colour,   19,  215,  197,  153\n"
			"lgeo_colour,   20,  193,  202,  222\n"
			"lgeo_colour,   21,  224,  255,  176\n"
			"lgeo_colour,   22,  107,   50,  123\n"
			"lgeo_colour,   23,   35,   71,  139\n"
			"lgeo_colour,   25,  218,  133,   64\n"
			"lgeo_colour,   26,  146,   57,  120\n"
			"lgeo_colour,   27,  164,  189,   70\n"
			"lgeo_colour,   28,  149,  138,  115\n"
			"lgeo_colour,   29,  228,  173,  200\n"
			"lgeo_colour,   30,  172,  120,  186\n"
			"lgeo_colour,   31,  225,  213,  237\n"
			"lgeo_colour,   32,    0,   20,   20\n"
			"lgeo_colour,   33,  123,  182,  232\n"
			"lgeo_colour,   34,  132,  182,  141\n"
			"lgeo_colour,   35,  217,  228,  167\n"
			"lgeo_colour,   36,  205,   84,   75\n"
			"lgeo_colour,   37,  228,  173,  200\n"
			"lgeo_colour,   38,  255,   43,    0\n"
			"lgeo_colour,   40,  166,  145,  130\n"
			"lgeo_colour,   41,  170,  229,  255\n"
			"lgeo_colour,   42,  198,  255,    0\n"
			"lgeo_colour,   43,  193,  223,  240\n"
			"lgeo_colour,   44,  150,  112,  159\n"
			"lgeo_colour,   46,  247,  241,  141\n"
			"lgeo_colour,   47,  252,  252,  252\n"
			"lgeo_colour,   52,  156,  149,  199\n"
			"lgeo_colour,   54,  255,  246,  123\n"
			"lgeo_colour,   57,  226,  176,   96\n"
			"lgeo_colour,   65,  236,  201,   53\n"
			"lgeo_colour,   66,  202,  176,    0\n"
			"lgeo_colour,   67,  255,  255,  255\n"
			"lgeo_colour,   68,  243,  207,  155\n"
			"lgeo_colour,   69,  142,   66,  133\n"
			"lgeo_colour,   70,  105,   64,   39\n"
			"lgeo_colour,   71,  163,  162,  164\n"
			"lgeo_colour,   72,   99,   95,   97\n"
			"lgeo_colour,   73,  110,  153,  201\n"
			"lgeo_colour,   74,  161,  196,  139\n"
			"lgeo_colour,   77,  220,  144,  149\n"
			"lgeo_colour,   78,  246,  215,  179\n"
			"lgeo_colour,   79,  255,  255,  255\n"
			"lgeo_colour,   80,  140,  140,  140\n"
			"lgeo_colour,   82,  219,  172,   52\n"
			"lgeo_colour,   84,  170,  125,   85\n"
			"lgeo_colour,   85,   52,   43,  117\n"
			"lgeo_colour,   86,  124,   92,   69\n"
			"lgeo_colour,   89,  155,  178,  239\n"
			"lgeo_colour,   92,  204,  142,  104\n"
			"lgeo_colour,  100,  238,  196,  182\n"
			"lgeo_colour,  115,  199,  210,   60\n"
			"lgeo_colour,  134,  174,  122,   89\n"
			"lgeo_colour,  135,  171,  173,  172\n"
			"lgeo_colour,  137,  106,  122,  150\n"
			"lgeo_colour,  142,  220,  188,  129\n"
			"lgeo_colour,  148,   62,   60,   57\n"
			"lgeo_colour,  151,   14,   94,   77\n"
			"lgeo_colour,  179,  160,  160,  160\n"
			"lgeo_colour,  183,  242,  243,  242\n"
			"lgeo_colour,  191,  248,  187,   61\n"
			"lgeo_colour,  212,  159,  195,  233\n"
			"lgeo_colour,  216,  143,   76,   42\n"
			"lgeo_colour,  226,  253,  234,  140\n"
			"lgeo_colour,  232,  125,  187,  221\n"
			"lgeo_colour,  256,   33,   33,   33\n"
			"lgeo_colour,  272,   32,   58,   86\n"
			"lgeo_colour,  273,   13,  105,  171\n"
			"lgeo_colour,  288,   39,   70,   44\n"
			"lgeo_colour,  294,  189,  198,  173\n"
			"lgeo_colour,  297,  170,  127,   46\n"
			"lgeo_colour,  308,   53,   33,    0\n"
			"lgeo_colour,  313,  171,  217,  255\n"
			"lgeo_colour,  320,  123,   46,   47\n"
			"lgeo_colour,  321,   70,  155,  195\n"
			"lgeo_colour,  322,  104,  195,  226\n"
			"lgeo_colour,  323,  211,  242,  234\n"
			"lgeo_colour,  324,  196,    0,   38\n"
			"lgeo_colour,  326,  226,  249,  154\n"
			"lgeo_colour,  330,  119,  119,   78\n"
			"lgeo_colour,  334,  187,  165,   61\n"
			"lgeo_colour,  335,  149,  121,  118\n"
			"lgeo_colour,  366,  209,  131,    4\n"
			"lgeo_colour,  373,  135,  124,  144\n"
			"lgeo_colour,  375,  193,  194,  193\n"
			"lgeo_colour,  378,  120,  144,  129\n"
			"lgeo_colour,  379,   94,  116,  140\n"
			"lgeo_colour,  383,  224,  224,  224\n"
			"lgeo_colour,  406,    0,   29,  104\n"
			"lgeo_colour,  449,  129,    0,  123\n"
			"lgeo_colour,  450,  203,  132,   66\n"
			"lgeo_colour,  462,  226,  155,   63\n"
			"lgeo_colour,  484,  160,   95,   52\n"
			"lgeo_colour,  490,  215,  240,    0\n"
			"lgeo_colour,  493,  101,  103,   97\n"
			"lgeo_colour,  494,  208,  208,  208\n"
			"lgeo_colour,  496,  163,  162,  164\n"
			"lgeo_colour,  503,  199,  193,  183\n"
			"lgeo_colour,  504,  137,  135,  136\n"
			"lgeo_colour,  511,  250,  250,  250\n"
		};

	/*
	# SLOPED BRICKS
	# Dictionary with part number (without any extension for decorations), as key,
	# of pieces that have grainy slopes, and, as values, a set containing the angles (in
	# degrees) of the face's normal to the horizontal plane. Use a | delimited tuple to
	# represent a range within which the angle must lie.

	#   Item--------  PartID-  Angle/Angle Range (in degrees)
	*/
	const char DefaultSlopedBricks[] =
		{
			"sloped_brick,     962,  45\n"
			"sloped_brick,    2341, -45\n"
			"sloped_brick,    2449, -16\n"
			"sloped_brick,    2875,  45\n"
			"sloped_brick,    2876,  40|63\n"
			"sloped_brick,    3037,  45\n"
			"sloped_brick,    3038,  45\n"
			"sloped_brick,    3039,  45\n"
			"sloped_brick,    3040,  45\n"
			"sloped_brick,    3041,  45\n"
			"sloped_brick,    3042,  45\n"
			"sloped_brick,    3043,  45\n"
			"sloped_brick,    3044,  45\n"
			"sloped_brick,    3045,  45\n"
			"sloped_brick,    3046,  45\n"
			"sloped_brick,    3048,  45\n"
			"sloped_brick,    3049,  45\n"
			"sloped_brick,    3135,  45\n"
			"sloped_brick,    3297,  63\n"
			"sloped_brick,    3298,  63\n"
			"sloped_brick,    3299,  63\n"
			"sloped_brick,    3300,  63\n"
			"sloped_brick,    3660, -45\n"
			"sloped_brick,    3665, -45\n"
			"sloped_brick,    3675,  63\n"
			"sloped_brick,    3676, -45\n"
			"sloped_brick,   3678b,  24\n"
			"sloped_brick,    3684,  15\n"
			"sloped_brick,    3685,  16\n"
			"sloped_brick,    3688,  15\n"
			"sloped_brick,    3747, -63\n"
			"sloped_brick,    4089, -63\n"
			"sloped_brick,    4161,  63\n"
			"sloped_brick,    4286,  63\n"
			"sloped_brick,    4287, -63\n"
			"sloped_brick,    4445,  45\n"
			"sloped_brick,    4460,  16\n"
			"sloped_brick,    4509,  63\n"
			"sloped_brick,    4854, -45\n"
			"sloped_brick,    4856, -60|-70, -45\n"
			"sloped_brick,    4857,  45\n"
			"sloped_brick,    4858,  72\n"
			"sloped_brick,    4861,  45,      63\n"
			"sloped_brick,    4871, -45\n"
			"sloped_brick,    4885,  72\n"
			"sloped_brick,    6069,  72,      45\n"
			"sloped_brick,    6153,  60|70,   26|4\n"
			"sloped_brick,    6227,  45\n"
			"sloped_brick,    6270,  45\n"
			"sloped_brick,   13269,  40|63\n"
			"sloped_brick,   13548,  45\n"
			"sloped_brick,   15571,  45\n"
			"sloped_brick,   18759, -45\n"
			"sloped_brick,   22390,  40|55\n"
			"sloped_brick,   22391,  40|55\n"
			"sloped_brick,   22889, -45\n"
			"sloped_brick,   28192,  45\n"
			"sloped_brick,   30180,  47\n"
			"sloped_brick,   30182,  45\n"
			"sloped_brick,   30183, -45\n"
			"sloped_brick,   30249,  35\n"
			"sloped_brick,   30283, -45\n"
			"sloped_brick,   30363,  72\n"
			"sloped_brick,   30373, -24\n"
			"sloped_brick,   30382,  11,      45\n"
			"sloped_brick,   30390, -45\n"
			"sloped_brick,   30499,  16\n"
			"sloped_brick,   32083,  45\n"
			"sloped_brick,   43708,  72\n"
			"sloped_brick,   43710,  72,      45\n"
			"sloped_brick,   43711,  72,      45\n"
			"sloped_brick,   47759,  40|63\n"
			"sloped_brick,   52501, -45\n"
			"sloped_brick,   60219, -45\n"
			"sloped_brick,   60477,  72\n"
			"sloped_brick,   60481,  24\n"
			"sloped_brick,   63341,  45\n"
			"sloped_brick,   72454, -45\n"
			"sloped_brick,   92946,  45\n"
			"sloped_brick,   93348,  72\n"
			"sloped_brick,   95188,  65\n"
			"sloped_brick,   99301,  63\n"
			"sloped_brick,  303923,  45\n"
			"sloped_brick,  303926,  45\n"
			"sloped_brick,  304826,  45\n"
			"sloped_brick,  329826,  64\n"
			"sloped_brick,  374726, -64\n"
			"sloped_brick,  428621,  64\n"
			"sloped_brick, 4162628,  17\n"
			"sloped_brick, 4195004,  45\n"
		};

	/*
	# LIGHTED BRICKS
	# Dictionary with part number (with extension), as key,
	# of lighted bricks, light emission colour and intensity, as values.

	#    Item---------  PartID---  Light--------------  Intensity
	*/
	const char DefaultLightedBricks[] =
		{
			"lighted_brick, 62930.dat, 1.000, 0.373, 0.059, 1.0\n"
			"lighted_brick, 54869.dat, 1.000, 0.052, 0.017, 1.0\n"
		};

	Buffer.clear();
	if (Which == PARAMS_CUSTOM_COLOURS)
		Buffer.append(DefaultCustomColours, sizeof(DefaultCustomColours));
	else if (Which == PARAMS_SLOPED_BRICKS)
		Buffer.append(DefaultSlopedBricks, sizeof(DefaultSlopedBricks));
	else if (Which == PARAMS_LIGHTED_BRICKS)
		Buffer.append(DefaultLightedBricks, sizeof(DefaultLightedBricks));
}

bool lcBlenderPreferences::ExportParameterFile()
{
	const QString BlenderConfigDir = QString("%1/Blender/addons/%2/config").arg(gAddonPreferences->mDataDir).arg(LC_BLENDER_ADDON_RENDER_FOLDER);
	const QString ParameterFile = QString("%1/%2").arg(BlenderConfigDir).arg(LC_BLENDER_ADDON_PARAMS_FILE);
	QDir ConfigDir(BlenderConfigDir);
	if(!ConfigDir.exists())
		ConfigDir.mkpath(".");
	QFile File(ParameterFile);

	if (!OverwriteFile(File.fileName()))
		return true;

	QString Message;
	if(File.open(QIODevice::WriteOnly | QIODevice::Text))
	{
		int Counter = 1;
		QByteArray Buffer;
		QTextStream Stream(&File);
		Stream << "# File: " << QFileInfo(ParameterFile).fileName() << LineEnding;
		Stream << "" << LineEnding;
		Stream << "# This config file captures parameters for the Blender LDraw Render addon" << LineEnding;
		Stream << "# Parameters must be prefixed using one of the following predefined" << LineEnding;
		Stream << "# 'Item' labels:" << LineEnding;
		Stream << "# - lgeo_colour" << LineEnding;
		Stream << "# - sloped_brick" << LineEnding;
		Stream << "# - light_brick" << LineEnding;
		Stream << "" << LineEnding;
		Stream << "# All items must use a comma',' delimiter as the primary delimiter." << LineEnding;
		Stream << "# For sloped_brick items, a pipe'|' delimiter must be used to specify" << LineEnding;
		Stream << "# a range (min|max) within which the angle must lie when appropriate." << LineEnding;
		Stream << "# Spaces between item attributes are not required and are used to" << LineEnding;
		Stream << "# facilitate human readability." << LineEnding;
		Stream << "" << LineEnding;
		Stream << "" << LineEnding;
		Stream << "# LGEO CUSTOM COLOURS" << LineEnding;
		Stream << "# LGEO is a parts library for rendering LEGO using the POV-Ray" << LineEnding;
		Stream << "# rendering software. This is the list of LEGO colours suitable" << LineEnding;
		Stream << "# for realistic rendering extracted from the LGEO file 'lg_color.inc'." << LineEnding;
		Stream << "# When the 'Colour Scheme' option is set to 'Realistic', the standard" << LineEnding;
		Stream << "# LDraw colours RGB value is overwritten with the values defined here." << LineEnding;
		Stream << "# Note: You can customize these RGB values as you want." << LineEnding;
		Stream << "" << LineEnding;
		Stream << "# Item-----  ID-    R--   G--   B--" << LineEnding;

		LoadDefaultParameters(Buffer, PARAMS_CUSTOM_COLOURS);
		QTextStream colourstream(Buffer);
		for (QString Line = colourstream.readLine(); !Line.isNull(); Line = colourstream.readLine())
		{
			Stream << Line << LineEnding;
			Counter++;
		}

		Stream << "" << LineEnding;
		Stream << "# SLOPED BRICKS" << LineEnding;
		Stream << "# Dictionary with part number (without any extension for decorations), as key," << LineEnding;
		Stream << "# of pieces that have grainy slopes, and, as values, a set containing the angles (in" << LineEnding;
		Stream << "# degrees) of the face's normal to the horizontal plane. Use a | delimited tuple to" << LineEnding;
		Stream << "# represent a range within which the angle must lie." << LineEnding;
		Stream << "" << LineEnding;
		Stream << "# Item------  PartID-  Angle/Angle Range (in degrees)" << LineEnding;

		LoadDefaultParameters(Buffer, PARAMS_SLOPED_BRICKS);
		QTextStream SlopedStream(Buffer);
		for (QString Line = SlopedStream.readLine(); !Line.isNull(); Line = SlopedStream.readLine())
		{
			Stream << Line << LineEnding;
			Counter++;
		}

		Stream << "" << LineEnding;
		Stream << "# LIGHTED BRICKS" << LineEnding;
		Stream << "# Dictionary with part number (with extension), as key," << LineEnding;
		Stream << "# of lighted bricks, light emission colour and intensity, as values." << LineEnding;
		Stream << "" << LineEnding;
		Stream << "# Item-------  PartID---  Light--------------  Intensity" << LineEnding;

		LoadDefaultParameters(Buffer, PARAMS_LIGHTED_BRICKS);
		QTextStream lightedstream(Buffer);
		for (QString Line = lightedstream.readLine(); !Line.isNull(); Line = lightedstream.readLine())
		{
			Stream << Line << LineEnding;
			Counter++;
		}

		Stream << "" << LineEnding;
		Stream << "# end of parameters" << LineEnding;

		File.close();
		Message = tr("Finished writing Blender parameter entries. Processed %1 lines in file [%2].")
					  .arg(Counter)
					  .arg(File.fileName());
	}
	else
	{
		Message = tr("Failed to open Blender parameter file: %1:<br>%2")
					  .arg(File.fileName())
					  .arg(File.errorString());
		ShowMessage(nullptr, Message);
		return false;
	}
	return true;
}

bool lcBlenderPreferences::OverwriteFile(const QString& File)
{
	QFileInfo fileInfo(File);

	if (!fileInfo.exists())
		return true;

	const QString& Title = tr ("Replace Existing File");
	const QString Header = "<b>" + QMessageBox::tr ("Existing file %1 detected.").arg(fileInfo.fileName()) + "</b>";
	const QString Body = QMessageBox::tr ("\"%1\"<br>This file already exists.<br>Replace existing file?").arg(fileInfo.fileName());
	int Exec = ShowMessage(nullptr, Header, Title, Body, QString(), MBB_YES, QMessageBox::NoIcon);

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

int lcBlenderPreferences::ShowMessage(QWidget* Parent, const QString& Header,  const QString& Title,  const QString& Body, const QString& Detail, int const Buttons, int const Icon)
{
	if (!gMainWindow)
		return QMessageBox::Ok;

	QMessageBox Box(Parent);
	Box.setWindowIcon(QIcon());
	if (!Icon)
	{
		QPixmap Pixmap = QPixmap(":/resources/leocad.png");
		Box.setIconPixmap (Pixmap);
	}
	else
		Box.setIcon (static_cast<QMessageBox::Icon>(Icon));

	Box.setTextFormat (Qt::RichText);
	Box.setWindowFlags (Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowTitleHint);
	if (!Title.isEmpty())
		Box.setWindowTitle(Title);
	else
		Box.setWindowTitle(tr("%1 Blender LDraw Addon").arg(LC_PRODUCTNAME_STR));

	Box.setText (Header);
	if (!Body.isEmpty())
		Box.setInformativeText (Body);

	if (!Detail.isEmpty())
		Box.setDetailedText(QString(Detail).replace("<br>", "\n"));

	switch (Buttons)
	{
	case MBB_YES:
		Box.setStandardButtons (QMessageBox::Yes | QMessageBox::Cancel);
		Box.setDefaultButton   (QMessageBox::Yes);
		break;
	case MBB_YES_NO:
		Box.setStandardButtons (QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel);
		Box.setDefaultButton   (QMessageBox::Yes);
		break;
	default:
		Box.setStandardButtons (QMessageBox::Ok);
		break;
	}

	int MinimumWidth = 400;
	int FontWidth = QFontMetrics(Box.font()).averageCharWidth();
	int FixedTextLength = (MinimumWidth / FontWidth);
	if (Header.length() < Body.length() && Header.length() < FixedTextLength)
	{
		QGridLayout* BoxLayout = (QGridLayout*)Box.layout();
		QLayoutItem* BoxLayoutItem = BoxLayout->itemAtPosition(0, 2);
		QWidget* TextWidget = BoxLayoutItem->widget();
		if (TextWidget)
		{
			int FixedWidth = Body.length() * FontWidth;
			if (FixedWidth == MinimumWidth)
			{
				int Index = (MinimumWidth / FontWidth) - 1;
				if (!Body.mid(Index,1).isEmpty())
					FixedWidth = Body.indexOf(" ", Index);
			}
			else if (FixedWidth < MinimumWidth)
				FixedWidth = MinimumWidth;
			TextWidget->setFixedWidth(FixedWidth);
		}
	}

	const bool DownloadRequest = Body.startsWith(tr("Do you want to download version "));

	if (DownloadRequest)
	{
		QCheckBox* AddonVersionCheck = new QCheckBox(tr("Do not show download new addon version message again."));
		Box.setCheckBox(AddonVersionCheck);
		QObject::connect(AddonVersionCheck, &QCheckBox::stateChanged, [](int State)
		{
			bool VersionCheck = true;
			if (static_cast<Qt::CheckState>(State) == Qt::CheckState::Checked)
				VersionCheck = false;
			lcSetProfileInt(LC_PROFILE_BLENDER_ADDON_VERSION_CHECK, (int)VersionCheck);
		});
	}

	return Box.exec();
}

void lcBlenderPreferences::DownloadFinished(lcHttpReply* Reply)
{
	if (!Reply->error())
		mData = Reply->readAll();
	else
		ShowMessage(this, tr("Addon download failed."));

	mHttpReply = nullptr;

	Reply->deleteLater();
}

namespace WindowsFileAttributes
{
enum
{
	Dir        = 0x10, // FILE_ATTRIBUTE_DIRECTORY
	File       = 0x80, // FILE_ATTRIBUTE_NORMAL
	TypeMask   = 0x90,
	ReadOnly   = 0x01, // FILE_ATTRIBUTE_READONLY
	PermMask   = 0x01
};
}

namespace UnixFileAttributes
{
enum
{
	Dir        = 0040000, // __S_IFDIR
	File       = 0100000, // __S_IFREG
	SymLink    = 0120000, // __S_IFLNK
	TypeMask   = 0170000, // __S_IFMT
	ReadUser   = 0400,    // __S_IRUSR
	WriteUser  = 0200,    // __S_IWUSR
	ExeUser    = 0100,    // __S_IXUSR
	ReadGroup  = 0040,    // __S_IRGRP
	WriteGroup = 0020,    // __S_IWGRP
	ExeGroup   = 0010,    // __S_IXGRP
	ReadOther  = 0004,    // __S_IROTH
	WriteOther = 0002,    // __S_IWOTH
	ExeOther   = 0001,    // __S_IXOTH
	PermMask   = 0777
};
}

bool lcBlenderPreferences::ExtractAddon(const QString FileName, QString& Result)
{
	enum ZipHostOS
	{
		HostFAT      = 0,
		HostUnix     = 3,
		HostHPFS     = 6,  // filesystem used by OS/2 (and NT 3.x)
		HostNTFS     = 11, // filesystem used by Windows NT
		HostVFAT     = 14, // filesystem used by Windows 95, NT
		HostOSX      = 19
	};

	struct ZipFileInfo
	{
		ZipFileInfo(lcZipFileInfo& FileInfo) noexcept
			: ZipInfo(FileInfo), isDir(false), isFile(false), isSymLink(false)
		{
		}
		bool IsValid() const noexcept { return isDir || isFile || isSymLink; }
		lcZipFileInfo& ZipInfo;
		QString filePath;
		uint isDir : 1;
		uint isFile : 1;
		uint isSymLink : 1;
		QFile::Permissions permissions;
	};

	auto ModeToPermissions = [](quint32 Mode)
	{
		QFile::Permissions Permissions;
		if (Mode&  UnixFileAttributes::ReadUser)
			Permissions |= QFile::ReadOwner | QFile::ReadUser;
		if (Mode&  UnixFileAttributes::WriteUser)
			Permissions |= QFile::WriteOwner | QFile::WriteUser;
		if (Mode&  UnixFileAttributes::ExeUser)
			Permissions |= QFile::ExeOwner | QFile::ExeUser;
		if (Mode&  UnixFileAttributes::ReadGroup)
			Permissions |= QFile::ReadGroup;
		if (Mode&  UnixFileAttributes::WriteGroup)
			Permissions |= QFile::WriteGroup;
		if (Mode&  UnixFileAttributes::ExeGroup)
			Permissions |= QFile::ExeGroup;
		if (Mode&  UnixFileAttributes::ReadOther)
			Permissions |= QFile::ReadOther;
		if (Mode&  UnixFileAttributes::WriteOther)
			Permissions |= QFile::WriteOther;
		if (Mode&  UnixFileAttributes::ExeOther)
			Permissions |= QFile::ExeOther;
		return Permissions;
	};

	lcZipFile ZipFile;

	if (!ZipFile.OpenRead(FileName))
		return false;

	const QString DestinationDir = QFileInfo(FileName).absolutePath();

	bool Ok = true;

	int Extracted = 0;

	for (quint32 FileIdx = 0; FileIdx < ZipFile.mFiles.size(); FileIdx++)
	{
		ZipFileInfo FileInfo(ZipFile.mFiles[FileIdx]);
		quint32 Mode = FileInfo.ZipInfo.external_fa;
		const ZipHostOS HostOS = ZipHostOS(FileInfo.ZipInfo.version >> 8);
		switch (HostOS)
		{
		case HostOSX:
		case HostUnix:
			Mode = (Mode >> 16)&  0xffff;
			switch (Mode&  UnixFileAttributes::TypeMask)
			{
			case UnixFileAttributes::SymLink:
				FileInfo.isSymLink = true;
				break;
			case UnixFileAttributes::Dir:
				FileInfo.isDir = true;
				break;
			case UnixFileAttributes::File:
			default:
				FileInfo.isFile = true;
				break;
			}
			FileInfo.permissions = ModeToPermissions(Mode);
			break;
		case HostFAT:
		case HostNTFS:
		case HostHPFS:
		case HostVFAT:
			switch (Mode&  WindowsFileAttributes::TypeMask)
			{
			case WindowsFileAttributes::Dir:
				FileInfo.isDir = true;
				break;
			case WindowsFileAttributes::File:
			default:
				FileInfo.isFile = true;
				break;
			}
			FileInfo.permissions |= QFile::ReadOwner | QFile::ReadUser | QFile::ReadGroup | QFile::ReadOther;
			if ((Mode&  WindowsFileAttributes::ReadOnly) == 0)
				FileInfo.permissions |= QFile::WriteOwner | QFile::WriteUser | QFile::WriteGroup | QFile::WriteOther;
			if (FileInfo.isDir)
				FileInfo.permissions |= QFile::ExeOwner | QFile::ExeUser | QFile::ExeGroup | QFile::ExeOther;
			break;
		default:
			ShowMessage(this, tr("ZipFile entry format (HostOS %1) at index %2 is not supported. Extract terminated.").arg(HostOS).arg(FileIdx), tr("Extract Addon"), QString(), QString(), MBB_OK, QMessageBox::Warning);
			Ok = false;
		}

		if (!Ok || !(Ok = FileInfo.IsValid()))
			break;

		// Check the file path - if broken, convert separators, eat leading and trailing ones
		FileInfo.filePath = QDir::fromNativeSeparators(FileInfo.ZipInfo.file_name);
		QString FilePathRef(FileInfo.filePath);
		while (FilePathRef.startsWith(QLatin1Char('.')) || FilePathRef.startsWith(QLatin1Char('/')))
			FilePathRef = FilePathRef.mid(1);
		while (FilePathRef.endsWith(QLatin1Char('/')))
			FilePathRef.chop(1);
		FileInfo.filePath = FilePathRef;

		const QString AbsPath = QDir::fromNativeSeparators(DestinationDir + QDir::separator() + FileInfo.filePath);

		// directories
		if (FileInfo.isDir)
		{
			QDir BaseDir(DestinationDir);
			if (!(Ok = BaseDir.mkpath(FileInfo.filePath)))
				break;
			if (!(Ok = QFile::setPermissions(AbsPath, FileInfo.permissions)))
				break;
			Extracted++;
			continue;
		}

		lcMemFile MemFile;

		ZipFile.ExtractFile(FileIdx, MemFile);

		QByteArray const& ByteArray = QByteArray::fromRawData((const char*)MemFile.mBuffer, (int)MemFile.GetLength());

		// symlinks
		if (FileInfo.isSymLink)
		{
			QString Destination = QFile::decodeName(ByteArray);
			if (!(Ok = !Destination.isEmpty()))
				break;
			QFileInfo LinkFileInfo(AbsPath);
			if (!QFile::exists(LinkFileInfo.absolutePath()))
				QDir::root().mkpath(LinkFileInfo.absolutePath());
			if (!(Ok = QFile::link(Destination, AbsPath)))
				break;
			Extracted++;
			continue;
		}

		// files
		if (FileInfo.isFile)
		{
			QFile File(AbsPath);
			if(!(Ok = File.open(QIODevice::WriteOnly)))
				break;
			File.write(ByteArray);
			File.setPermissions(FileInfo.permissions);
			File.close();
			Extracted++;
		}
	}

	if (!Ok)
		Result = tr("%1 of %2 files extracted.").arg(Extracted).arg(ZipFile.mFiles.size());

	return Ok;
}