aboutsummaryrefslogtreecommitdiffstats
path: root/QtVsTools.Core/QtProject.cs
blob: b842584564de1a39350b62eb040537b5e315b3db (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
/****************************************************************************
**
** Copyright (C) 2022 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the Qt VS Tools.
**
** $QT_BEGIN_LICENSE:GPL-EXCEPT$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.VCProjectEngine;
using EnvDTE;

namespace QtVsTools.Core
{
    using QtMsBuild;

    /// <summary>
    /// QtProject holds the Qt specific properties for a Visual Studio project.
    /// There exists at most one QtProject per EnvDTE.Project.
    /// Use QtProject.Create to get the QtProject for a Project or VCProject.
    /// </summary>
    public class QtProject
    {
        private DTE dte;
        private Project envPro;
        private VCProject vcPro;
        private MocCmdChecker mocCmdChecker;
        private static readonly Dictionary<Project, QtProject> instances = new Dictionary<Project, QtProject>();
        private readonly QtMsBuildContainer qtMsBuild;

        public static QtVsTools.VisualStudio.IProjectTracker ProjectTracker { get; set; }

        public static QtProject Create(VCProject vcProject)
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            return Create((Project)vcProject.Object);
        }

        public static QtProject Create(Project project)
        {
            QtProject qtProject = null;
            if (project != null && !instances.TryGetValue(project, out qtProject)) {
                qtProject = new QtProject(project);
                instances.Add(project, qtProject);
            }
            return qtProject;
        }

        public static void ClearInstances()
        {
            instances.Clear();
        }

        private QtProject(Project project)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            if (project == null)
                throw new QtVSException("Cannot construct a QtProject object without a valid project.");
            envPro = project;
            dte = envPro.DTE;
            vcPro = envPro.Object as VCProject;
            qtMsBuild = new QtMsBuildContainer(new VCPropertyStorageProvider());
        }

        public VCProject VCProject => vcPro;

        public Project Project => envPro;

        public static string GetRuleName(VCConfiguration config, string itemType)
        {
            if (config == null)
                return string.Empty;
            try {
                return config.GetEvaluatedPropertyValue(itemType + "RuleName");
            } catch (Exception exception) {
                exception.Log();
                return string.Empty;
            }
        }

        public static bool IsQtMsBuildEnabled(VCProject project)
        {
            try {
                if (project?.Configurations is IVCCollection configs) {
                    if (configs.Count == 0)
                        return false;
                    var firstConfig = configs.Item(1) as VCConfiguration;
                    var ruleName = GetRuleName(firstConfig, QtMoc.ItemTypeName);
                    return firstConfig?.Rules.Item(ruleName) is IVCRulePropertyStorage;
                }
            } catch (Exception) {
                return false;
            }
            return false;
        }

        public static bool IsQtMsBuildEnabled(Project project)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            if (project == null)
                return false;
            return IsQtMsBuildEnabled(project.Object as VCProject);
        }

        private bool? isQtMsBuildEnabled = null;
        public bool IsQtMsBuildEnabled()
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            if (!isQtMsBuildEnabled.HasValue) {
                if (vcPro != null)
                    isQtMsBuildEnabled = IsQtMsBuildEnabled(vcPro);
                else if (envPro != null)
                    isQtMsBuildEnabled = IsQtMsBuildEnabled(envPro);
                else
                    return false;
            }
            return isQtMsBuildEnabled.Value;
        }

        /// <summary>
        /// Returns the moc-generated file name for the given source or header file.
        /// </summary>
        /// <param name="file">header or source file in the project</param>
        /// <returns></returns>
        private static string GetMocFileName(string file)
        {
            var fi = new FileInfo(file);

            var name = fi.Name;
            if (HelperFunctions.IsHeaderFile(fi.Name))
                return "moc_" + name.Substring(0, name.LastIndexOf('.')) + ".cpp";
            if (HelperFunctions.IsSourceFile(fi.Name))
                return name.Substring(0, name.LastIndexOf('.')) + ".moc";
            return null;
        }

        /// <summary>
        /// Returns the file name of the generated moc file relative to the
        /// project directory.
        /// </summary>
        /// The directory of the moc file depends on the file configuration.
        /// Every appearance of "$(ConfigurationName)" in the path will be
        /// replaced by the value of configName.
        /// <param name="file">full file name of either the header or the source file</param>
        /// <returns></returns>
        private string GetRelativeMocFilePath(string file, string configName = null,
                                              string platformName = null)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            var fileName = GetMocFileName(file);
            if (fileName == null)
                return null;
            var mocDir = QtVSIPSettings.GetMocDirectory(envPro, configName, platformName, file)
                + Path.DirectorySeparatorChar + fileName;
            if (HelperFunctions.IsAbsoluteFilePath(mocDir))
                mocDir = HelperFunctions.GetRelativePath(vcPro.ProjectDirectory, mocDir);
            return mocDir;
        }

        public static int GetFormatVersion(VCProject vcPro)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            if (vcPro == null)
                return 0;

            if (vcPro.keyword.StartsWith(Resources.qtProjectKeyword, StringComparison.Ordinal))
                return Convert.ToInt32(vcPro.keyword.Substring(6));

            if (vcPro.keyword.StartsWith(Resources.qtProjectV2Keyword, StringComparison.Ordinal)) {
                var envPro = vcPro.Object as Project;
                if (envPro.Globals != null && envPro.Globals.VariableNames != null) {
                    foreach (var global in envPro.Globals.VariableNames as string[]) {
                        if (global.StartsWith("Qt5Version", StringComparison.Ordinal)
                            && envPro.Globals.get_VariablePersists(global)) {
                            return 200;
                        }
                    }
                }
                return 100;
            }
            return 0;
        }

        public static int GetFormatVersion(Project pro)
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            return GetFormatVersion(pro?.Object as VCProject);
        }

        public int FormatVersion
        {
            get
            {
                ThreadHelper.ThrowIfNotOnUIThread();
                return GetFormatVersion(Project);
            }
        }

        public static string GetPropertyValue(
            EnvDTE.Project dteProject,
            string propName)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            var activeConfig = dteProject.ConfigurationManager?.ActiveConfiguration;
            if (activeConfig == null)
                return null;
            return GetPropertyValue(
                dteProject, activeConfig, propName);
        }

        public static string GetPropertyValue(
            EnvDTE.Project dteProject,
            EnvDTE.Configuration dteConfig,
            string propName)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            if (dteProject == null || dteConfig == null)
                return null;
            return GetPropertyValue(
                dteProject.Object as VCProject,
                dteConfig.ConfigurationName,
                dteConfig.PlatformName,
                propName);
        }

        public static string GetPropertyValue(
            VCProject vcProject,
            string configName,
            string platformName,
            string propName)
        {
            if (vcProject.Configurations is IVCCollection vcConfigs) {
                var configId = $"{configName}|{platformName}";
                if (vcConfigs.Item(configId) is VCConfiguration vcConfig)
                    return GetPropertyValue(vcConfig, propName);
            }
            return null;
        }

        public static string GetPropertyValue(
            VCConfiguration vcConfig,
            string propName)
        {
            return vcConfig.GetEvaluatedPropertyValue(propName);
        }

        /// <summary>
        /// This function adds a uic4 build step to a given file.
        /// </summary>
        /// <param name="file">file</param>
        public void AddUic4BuildStep(VCFile file)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            if (GetFormatVersion(vcPro) >= Resources.qtMinFormatVersion_Settings) {
                file.ItemType = QtUic.ItemTypeName;
            } else {
                // TODO: It would be nice if we can inform the user he's on an old project.
                //if (QtVsToolsPackage.Instance.Options.UpdateProjectFormat)
                //    Notifications.UpdateProjectFormat.Show();
            }
        }

        /// <summary>
        /// Surrounds the argument by double quotes.
        /// Makes sure, that the trailing double quote is not escaped by a backslash.
        /// Escapes all quotation mark characters in the argument
        ///
        /// This must follow the format recognized by CommandLineToArgvW:
        /// (https://docs.microsoft.com/en-us/windows/desktop/api/shellapi/nf-shellapi-commandlinetoargvw)
        ///
        /// CommandLineToArgvW has a special interpretation of backslash characters when they are
        /// followed by a quotation mark character ("). This interpretation assumes that any
        /// preceding argument is a valid file system path, or else it may behave unpredictably.
        ///
        /// This special interpretation controls the "in quotes" mode tracked by the parser. When
        /// this mode is off, whitespace terminates the current argument. When on, whitespace is
        /// added to the argument like all other characters.
        ///
        ///   * 2n backslashes followed by a quotation mark produce n backslashes followed by
        ///     begin/end quote. This does not become part of the parsed argument, but toggles the
        ///     "in quotes" mode.
        ///
        ///   * (2n) + 1 backslashes followed by a quotation mark again produce n backslashes
        ///     followed by a quotation mark literal ("). This does not toggle the "in quotes" mode.
        ///
        ///   * n backslashes not followed by a quotation mark simply produce n backslashes.
        ///
        /// </summary>
        private static string SafelyQuoteCommandLineArgument(string arg)
        {
            var quotedArg = new StringBuilder();
            quotedArg.Append("\"");

            // Split argument by quotation mark characters
            // All argument parts except the last are followed by a quotation mark character
            var argParts = arg.Split(new char[] { '\"' });
            for (int i = 0; i < argParts.Length; ++i) {
                var part = argParts[i];
                quotedArg.Append(part);

                // Duplicate backslashes immediately preceding quotation mark character
                if (part.EndsWith("\\")) {
                    quotedArg.Append(part.Reverse().TakeWhile(c => c == Path.DirectorySeparatorChar)
                        .ToArray());
                }
                // Escape all quotation mark characters in argument
                if (i < argParts.Length - 1)
                    quotedArg.Append("\\\"");
            }

            quotedArg.Append("\"");
            return quotedArg.ToString();
        }

        public string GetDefines(VCFileConfiguration conf)
        {
            var defines = string.Empty;
            if (conf.Tool is IVCRulePropertyStorage propsFile) {
                try {
                    defines = propsFile.GetUnevaluatedPropertyValue("PreprocessorDefinitions");
                } catch { }
            }

            var projectConfig = conf.ProjectConfiguration as VCConfiguration;
            if (string.IsNullOrEmpty(defines)
                && projectConfig?.Rules.Item("CL") is IVCRulePropertyStorage propsProject) {
                try {
                    defines = propsProject.GetUnevaluatedPropertyValue("PreprocessorDefinitions");
                } catch { }
            }

            if (string.IsNullOrEmpty(defines))
                return string.Empty;

            var defineList = defines.Split(
                new char[] { ';' },
                StringSplitOptions.RemoveEmptyEntries)
                .ToList();

            var preprocessorDefines = string.Empty;
            var alreadyAdded = new List<string>();
            var rxp = new Regex(@"\s|(\$\()");
            foreach (var define in defineList) {
                if (!alreadyAdded.Contains(define)) {
                    var mustSurroundByDoubleQuotes = rxp.IsMatch(define);
                    // Yes, a preprocessor definition can contain spaces or a macro name.
                    // Example: PROJECTDIR=$(InputDir)

                    if (mustSurroundByDoubleQuotes) {
                        preprocessorDefines += " ";
                        preprocessorDefines += SafelyQuoteCommandLineArgument("-D" + define);
                    } else {
                        preprocessorDefines += " -D" + define;
                    }
                    alreadyAdded.Add(define);
                }
            }
            return preprocessorDefines;
        }

        private string GetIncludes(VCFileConfiguration conf)
        {
            var includeList = GetIncludesFromCompilerTool(CompilerToolWrapper.Create(conf));

            var projectConfig = conf.ProjectConfiguration as VCConfiguration;
            includeList.AddRange(GetIncludesFromCompilerTool(CompilerToolWrapper.Create(projectConfig)));

            if (projectConfig.PropertySheets is IVCCollection propertySheets) {
                foreach (VCPropertySheet sheet in propertySheets)
                    includeList.AddRange(GetIncludesFromPropertySheet(sheet));
            }

            var includes = string.Empty;
            var alreadyAdded = new List<string>();
            foreach (var include in includeList) {
                if (!alreadyAdded.Contains(include)) {
                    var incl = HelperFunctions.NormalizeRelativeFilePath(include);
                    if (incl.Length > 0)
                        includes += " " + SafelyQuoteCommandLineArgument("-I" + incl);
                    alreadyAdded.Add(include);
                }
            }
            return includes;
        }

        private List<string> GetIncludesFromPropertySheet(VCPropertySheet sheet)
        {
            var includeList = GetIncludesFromCompilerTool(CompilerToolWrapper.Create(sheet));
            if (sheet.PropertySheets is IVCCollection propertySheets) {
                foreach (VCPropertySheet subSheet in propertySheets)
                    includeList.AddRange(GetIncludesFromPropertySheet(subSheet));
            }
            return includeList;
        }

        private static List<string> GetIncludesFromCompilerTool(CompilerToolWrapper compiler)
        {
            try {
                if (!string.IsNullOrEmpty(compiler.GetAdditionalIncludeDirectories())) {
                    var includes = compiler.GetAdditionalIncludeDirectoriesList();
                    return new List<string>(includes);
                }
            } catch { }
            return new List<string>();
        }

        private string GetPCHMocOptions(VCFile file, CompilerToolWrapper compiler)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            // As .moc files are included, we should not add anything there
            if (!HelperFunctions.IsHeaderFile(file.Name))
                return string.Empty;

            var additionalMocOptions = "\"-f" + HelperFunctions.FromNativeSeparators(compiler
                .GetPrecompiledHeaderThrough()) + "\" ";
            //Get mocDir without .\\ at the beginning of it
            var mocDir = QtVSIPSettings.GetMocDirectory(envPro);
            if (mocDir.StartsWith(".\\", StringComparison.Ordinal))
                mocDir = mocDir.Substring(2);

            //Get the absolute path
            mocDir = vcPro.ProjectDirectory + mocDir;
            var fullPathGeneric = Path.Combine(
                Path.GetDirectoryName(file.FullPath), "%(Filename)%(Extension)");
            var relPathToFile = HelperFunctions.FromNativeSeparators(HelperFunctions
                .GetRelativePath(mocDir, fullPathGeneric));
            additionalMocOptions += "\"-f" + relPathToFile + "\"";
            return additionalMocOptions;
        }

        /// <summary>
        /// Adds a moc step to a given file for this project.
        /// </summary>
        /// <param name="file">file</param>
        public void AddMocStep(VCFile file)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            if (GetFormatVersion(vcPro) >= Resources.qtMinFormatVersion_Settings) {
                file.ItemType = QtMoc.ItemTypeName;
                if (!HelperFunctions.IsSourceFile(file.FullPath))
                    return;
                foreach (VCFileConfiguration config in (IVCCollection)file.FileConfigurations) {
                    qtMsBuild.SetItemProperty(config, QtMoc.Property.DynamicSource, "input");
                    qtMsBuild.SetItemPropertyByName(config, "QtMocFileName", "%(Filename).moc");
                }
            } else {
                // TODO: It would be nice if we can inform the user he's on an old project.
                //if (QtVsToolsPackage.Instance.Options.UpdateProjectFormat)
                //    Notifications.UpdateProjectFormat.Show();
            }
        }

        /// <summary>
        /// Parses the given file to find an occurrence of a moc.exe generated file include. If
        /// the given file is a header file, the function tries to find the corresponding source
        /// file to use it instead of the header file. Helper function for AddMocStep.
        /// </summary>
        /// <param name="vcFile">Header or source file name.</param>
        /// <returns>
        /// Returns true if the file contains an include of the corresponding moc_xxx.cpp file;
        /// otherwise returns false.
        /// </returns>
        public bool IsMoccedFileIncluded(VCFile vcFile)
        {
            var fullPath = vcFile.FullPath;
            if (HelperFunctions.IsHeaderFile(fullPath))
                fullPath = Path.ChangeExtension(fullPath, ".cpp");

            if (HelperFunctions.IsSourceFile(fullPath)) {
                vcFile = GetFileFromProject(fullPath);
                if (vcFile == null)
                    return false;

                fullPath = vcFile.FullPath;
                var mocFile = "moc_" + Path.GetFileNameWithoutExtension(fullPath) + ".cpp";

#if TODO
                // TODO: Newly created projects need a manual solution rescan if we access the
                // code model too early, right now it fails to properly parse the created files.

                // Try reusing the vc file code model,
                var projectItem = vcFile.Object as ProjectItem;
                if (projectItem != null) {
                    var vcFileCodeModel = projectItem.FileCodeModel as VCFileCodeModel;
                    if (vcFileCodeModel != null) {
                        foreach (VCCodeInclude include in vcFileCodeModel.Includes) {
                            if (include.FullName == mocFile)
                                return true;
                        }
                        return false;
                    }
                }

                // if we fail, we parse the file on our own...
#endif
                CxxStreamReader cxxStream = null;
                try {
                    var line = string.Empty;
                    cxxStream = new CxxStreamReader(fullPath);
                    while ((line = cxxStream.ReadLine()) != null) {
                        if (Regex.IsMatch(line, "#include *(<|\")" + mocFile + "(\"|>)"))
                            return true;
                    }
                } catch { } finally {
                    if (cxxStream != null)
                        cxxStream.Dispose();
                }
            }
            return false;
        }

        public bool HasMocStep(VCFile file)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            if (file.ItemType == QtMoc.ItemTypeName)
                return true;

            if (HelperFunctions.IsHeaderFile(file.Name))
                return CheckForCommand(file, "moc.exe");

            if (HelperFunctions.IsSourceFile(file.Name)) {
                return (HasCppMocFiles(file));
            }
            return false;
        }

        public static bool HasUicStep(VCFile file)
        {
            if (file.ItemType == QtUic.ItemTypeName)
                return true;
            return CheckForCommand(file, Resources.uic4Command);
        }

        private static bool CheckForCommand(VCFile file, string cmd)
        {
            if (file == null)
                return false;
            foreach (VCFileConfiguration config in (IVCCollection)file.FileConfigurations) {
                var tool = HelperFunctions.GetCustomBuildTool(config);
                if (tool == null)
                    return false;
                if (tool.CommandLine != null && tool.CommandLine.Contains(cmd))
                    return true;
            }
            return false;
        }

        public void UpdateRccStep(VCFile qrcFile)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            if (GetFormatVersion(vcPro) >= Resources.qtMinFormatVersion_Settings) {
                qrcFile.ItemType = QtRcc.ItemTypeName;
            } else {
                // TODO: It would be nice if we can inform the user he's on an old project.
                //if (QtVsToolsPackage.Instance.Options.UpdateProjectFormat)
                //    Notifications.UpdateProjectFormat.Show();
            }
        }

        public static void ExcludeFromAllBuilds(VCFile file)
        {
            if (file == null)
                return;
            foreach (VCFileConfiguration conf in (IVCCollection)file.FileConfigurations) {
                if (!conf.ExcludedFromBuild)
                    conf.ExcludedFromBuild = true;
            }
        }

        bool IsCppMocFileCustomBuild(VCFile vcFile, VCFile cppFile)
        {
            var mocFilePath = vcFile.FullPath;
            var cppFilePath = cppFile.FullPath;
            if (Path.GetDirectoryName(mocFilePath)
                != Path.GetDirectoryName(cppFilePath)) {
                return false;
            }

            if (Path.GetFileNameWithoutExtension(mocFilePath)
                != Path.GetFileNameWithoutExtension(cppFilePath)) {
                return false;
            }

            if (!string.Equals(Path.GetExtension(mocFilePath), ".cbt",
                StringComparison.InvariantCultureIgnoreCase)) {
                return false;
            }

            return true;
        }

        List<VCFile> GetCppMocOutputs(List<VCFile> mocFiles)
        {
            List<VCFile> outputFiles = new List<VCFile>();
            foreach (var mocFile in mocFiles) {
                foreach (VCFileConfiguration mocConfig
                    in (IVCCollection)mocFile.FileConfigurations) {

                    var cbtTool = HelperFunctions.GetCustomBuildTool(mocConfig);
                    if (cbtTool == null)
                        continue;
                    foreach (var output in cbtTool.Outputs.Split(new char[] { ';' })) {
                        string outputExpanded = output;
                        if (!HelperFunctions.ExpandString(ref outputExpanded, mocConfig))
                            continue;
                        string outputFullPath = "";
                        try {
                            outputFullPath = Path.GetFullPath(Path.Combine(
                                Path.GetDirectoryName(mocFile.FullPath),
                                outputExpanded));
                        } catch {
                            continue;
                        }
                        var vcFile = GetFileFromProject(outputFullPath);
                        if (vcFile != null)
                            outputFiles.Add(vcFile);
                    }
                }
            }
            return outputFiles;
        }

        List<VCFile> GetCppMocFiles(VCFile cppFile)
        {
            List<VCFile> mocFiles = new List<VCFile>();
            if (cppFile.project is VCProject vcProj) {
                mocFiles.AddRange(from VCFile vcFile
                                  in (IVCCollection)vcProj.Files
                                  where vcFile.ItemType == "CustomBuild"
                                  && IsCppMocFileCustomBuild(vcFile, cppFile)
                                  select vcFile);
                mocFiles.AddRange(GetCppMocOutputs(mocFiles));
            }
            return mocFiles;
        }

        bool IsCppMocFileQtMsBuild(VCFile vcFile, VCFile cppFile)
        {
            foreach (VCFileConfiguration fileConfig in (IVCCollection)vcFile.FileConfigurations) {
                string inputFile = qtMsBuild.GetPropertyValue(fileConfig, QtMoc.Property.InputFile);
                HelperFunctions.ExpandString(ref inputFile, fileConfig);
                if (HelperFunctions.PathIsRelativeTo(inputFile, cppFile.ItemName))
                    return true;
            }
            return false;
        }

        bool HasCppMocFiles(VCFile cppFile)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            if (!IsQtMsBuildEnabled())
                return File.Exists(Path.ChangeExtension(cppFile.FullPath, ".cbt"));

            if (cppFile.project is VCProject vcProj) {
                foreach (VCFile vcFile in (IVCCollection)vcProj.Files) {
                    if (vcFile.ItemType == "CustomBuild") {
                        if (IsCppMocFileCustomBuild(vcFile, cppFile))
                            return true;
                    } else if (vcFile.ItemType == QtMoc.ItemTypeName) {
                        if (IsCppMocFileQtMsBuild(vcFile, cppFile))
                            return true;
                    }
                }
            }
            return false;
        }

        public void RemoveMocStep(VCFile file)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            if (file.ItemType == QtMoc.ItemTypeName) {
                RemoveMocStepQtMsBuild(file);
            } else if (HelperFunctions.IsHeaderFile(file.Name)) {
                if (file.ItemType == "CustomBuild")
                    RemoveMocStepCustomBuild(file);
            } else {
                foreach (VCFile vcFile in (IVCCollection)vcPro.Files) {
                    if (vcFile.ItemType == QtMoc.ItemTypeName) {
                        if (IsCppMocFileQtMsBuild(vcFile, file)) {
                            RemoveMocStepQtMsBuild(vcFile);
                        }
                    } else if (vcFile.ItemType == "CustomBuild") {
                        if (IsCppMocFileCustomBuild(vcFile, file)) {
                            RemoveMocStepCustomBuild(file);
                            return;
                        }
                    }
                }
            }
        }

        public void RemoveMocStepQtMsBuild(VCFile file)
        {
            if (HelperFunctions.IsHeaderFile(file.Name)) {
                file.ItemType = "ClInclude";
            } else if (HelperFunctions.IsSourceFile(file.Name)) {
                file.ItemType = "ClCompile";
            } else {
                file.ItemType = "None";
            }
        }

        /// <summary>
        /// Removes the custom build step of a given file.
        /// </summary>
        /// <param name="file">file</param>
        public void RemoveMocStepCustomBuild(VCFile file)
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            try {
                if (!HasMocStep(file))
                    return;

                if (HelperFunctions.IsHeaderFile(file.Name)) {
                    foreach (VCFileConfiguration config in (IVCCollection)file.FileConfigurations) {
                        var tool = HelperFunctions.GetCustomBuildTool(config);
                        if (tool == null)
                            continue;

                        var cmdLine = tool.CommandLine;
                        if (cmdLine.Length > 0) {
                            var rex = new Regex(@"(\S*moc.exe|""\S+:\\\.*moc.exe"")");
                            while (true) {
                                var m = rex.Match(cmdLine);
                                if (!m.Success)
                                    break;

                                var start = m.Index;
                                var end = cmdLine.IndexOf("&&", start, StringComparison.Ordinal);
                                var a = cmdLine.IndexOf("\r\n", start, StringComparison.Ordinal);
                                if ((a > -1 && a < end) || (end < 0 && a > -1))
                                    end = a;
                                if (end < 0)
                                    end = cmdLine.Length;

                                cmdLine = cmdLine.Remove(start, end - start).Trim();
                                if (cmdLine.StartsWith("&&", StringComparison.Ordinal))
                                    cmdLine = cmdLine.Remove(0, 2).Trim();
                            }
                            tool.CommandLine = cmdLine;
                        }

                        var reg = new Regex("Moc'ing .+\\.\\.\\.");
                        var addDepends = tool.AdditionalDependencies;
                        addDepends = Regex.Replace(addDepends,
                            @"(\S*moc.exe|""\S+:\\\.*moc.exe"")", string.Empty);
                        addDepends = addDepends.Replace(file.RelativePath, string.Empty);
                        tool.AdditionalDependencies = string.Empty;
                        tool.Description = reg.Replace(tool.Description, string.Empty);
                        tool.Description = tool.Description.Replace("MOC " + file.Name, string.Empty);
                        var baseFileName = file.Name.Remove(file.Name.LastIndexOf('.'));
                        var pattern = "(\"(.*\\\\" + GetMocFileName(file.FullPath)
                            + ")\"|(\\S*" + GetMocFileName(file.FullPath) + "))";
                        string outputMocFile = null;
                        var regExp = new Regex(pattern);
                        tool.Outputs = tool.Outputs.Replace(ProjectMacros.Name, baseFileName);
                        var matchList = regExp.Matches(tool.Outputs);
                        if (matchList.Count > 0) {
                            if (matchList[0].Length > 0)
                                outputMocFile = matchList[0].ToString();
                            else if (matchList[1].Length > 1)
                                outputMocFile = matchList[1].ToString();
                        }
                        tool.Outputs = Regex.Replace(tool.Outputs,
                            pattern, string.Empty, RegexOptions.Multiline | RegexOptions.IgnoreCase);
                        tool.Outputs = Regex.Replace(tool.Outputs,
                            @"\s*;\s*;\s*", ";", RegexOptions.Multiline);
                        tool.Outputs = Regex.Replace(tool.Outputs,
                            @"(^\s*;|\s*;\s*$)", string.Empty, RegexOptions.Multiline);

                        if (outputMocFile != null) {
                            if (outputMocFile.StartsWith("\"", StringComparison.Ordinal))
                                outputMocFile = outputMocFile.Substring(1);
                            if (outputMocFile.EndsWith("\"", StringComparison.Ordinal))
                                outputMocFile = outputMocFile.Substring(0, outputMocFile.Length - 1);
                            HelperFunctions.ExpandString(ref outputMocFile, config);
                        }
                        var mocFile = GetFileFromProject(outputMocFile);
                        if (mocFile != null)
                            RemoveFileFromFilter(mocFile, Filters.GeneratedFiles());
                    }
                } else {
                    foreach (var mocFile in GetCppMocFiles(file)) {
                        RemoveFileFromFilter(mocFile, Filters.GeneratedFiles());
                    }
                }
            } catch {
                throw new QtVSException($"Cannot remove a moc step from file {file.FullPath}");
            }
        }

        /// <summary>
        /// Returns the file (VCFile) specified by the file name from a given
        /// project.
        /// </summary>
        /// <param name="fileName">file name (relative path)</param>
        /// <returns></returns>
        public VCFile GetFileFromProject(string fileName)
        {
            fileName = HelperFunctions.NormalizeRelativeFilePath(fileName);
            if (!HelperFunctions.IsAbsoluteFilePath(fileName)) {
                fileName = HelperFunctions.NormalizeFilePath(vcPro.ProjectDirectory
                    + Path.DirectorySeparatorChar + fileName);
            }
            foreach (VCFile f in (IVCCollection)vcPro.Files) {
                if (f.FullPath.Equals(fileName, StringComparison.OrdinalIgnoreCase))
                    return f;
            }
            return null;
        }

        /// <summary>
        /// Returns the files specified by the file name from a given project as list of VCFile
        /// objects.
        /// </summary>
        /// <param name="fileName">file name (relative path)</param>
        /// <returns></returns>
        public IEnumerable<VCFile> GetFilesFromProject(string fileName)
        {
            var fi = new FileInfo(HelperFunctions.NormalizeRelativeFilePath(fileName));
            foreach (VCFile f in (IVCCollection)vcPro.Files) {
                if (f.Name.Equals(fi.Name, StringComparison.OrdinalIgnoreCase))
                    yield return f;
            }
        }

        /// <summary>
        /// Removes a file from the filter.
        /// This file will be deleted!
        /// </summary>
        /// <param name="file">file</param>
        public void RemoveFileFromFilter(VCFile file, FakeFilter filter)
        {
            try {
                var vfilt = FindFilterFromGuid(filter.UniqueIdentifier);

                if (vfilt == null)
                    vfilt = FindFilterFromName(filter.Name);

                if (vfilt == null)
                    return;

                RemoveFileFromFilter(file, vfilt);
            } catch {
                throw new QtVSException($"Cannot remove file {file.Name} from filter.");
            }
        }

        /// <summary>
        /// Removes a file from the filter.
        /// This file will be deleted!
        /// </summary>
        /// <param name="file">file</param>
        public void RemoveFileFromFilter(VCFile file, VCFilter filter)
        {
            try {
                filter.RemoveFile(file);
                var fi = new FileInfo(file.FullPath);
                if (fi.Exists)
                    fi.Delete();
            } catch {
            }

            var subfilters = (IVCCollection)filter.Filters;
            for (var i = subfilters.Count; i > 0; i--) {
                try {
                    var subfilter = (VCFilter)subfilters.Item(i);
                    RemoveFileFromFilter(file, subfilter);
                } catch {
                }
            }
        }

        public VCFilter FindFilterFromName(string filtername)
        {
            try {
                foreach (VCFilter vcfilt in (IVCCollection)vcPro.Filters) {
                    if (vcfilt.Name.ToLower() == filtername.ToLower())
                        return vcfilt;
                }
                return null;
            } catch {
                throw new QtVSException("Cannot find filter.");
            }
        }

        public VCFilter FindFilterFromGuid(string filterguid)
        {
            try {
                foreach (VCFilter vcfilt in (IVCCollection)vcPro.Filters) {
                    if (vcfilt.UniqueIdentifier != null
                        && vcfilt.UniqueIdentifier.ToLower() == filterguid.ToLower()) {
                        return vcfilt;
                    }
                }
                return null;
            } catch {
                throw new QtVSException("Cannot find filter.");
            }
        }

        public static void MarkAsQtPlugin(Core.QtProject qtPro)
        {
            foreach (VCConfiguration config in qtPro.VCProject.Configurations as IVCCollection) {
                (config.Rules.Item("QtRule10_Settings") as IVCRulePropertyStorage)
                    .SetPropertyValue("QtPlugin", "true");
            }
        }

        /// <summary>
        /// adjusts the whitespaces, tabs in the given file according to VS settings
        /// </summary>
        /// <param name="file"></param>
        public static void AdjustWhitespace(DTE dte, string file)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            if (!File.Exists(file))
                return;

            // only replace whitespaces in known types
            if (!HelperFunctions.IsSourceFile(file) && !HelperFunctions.IsHeaderFile(file)
                && !HelperFunctions.IsUicFile(file)) {
                return;
            }

            try {
                var prop = dte.get_Properties("TextEditor", "C/C++");
                var tabSize = Convert.ToInt64(prop.Item("TabSize").Value);
                var insertTabs = Convert.ToBoolean(prop.Item("InsertTabs").Value);

                var oldValue = insertTabs ? "    " : "\t";
                var newValue = insertTabs ? "\t" : GetWhitespaces(tabSize);

                var list = new List<string>();
                var reader = new StreamReader(file);
                var line = reader.ReadLine();
                while (line != null) {
                    if (line.StartsWith(oldValue, StringComparison.Ordinal))
                        line = line.Replace(oldValue, newValue);
                    list.Add(line);
                    line = reader.ReadLine();
                }
                reader.Close();

                var writer = new StreamWriter(file);
                foreach (var l in list)
                    writer.WriteLine(l);
                writer.Close();
            } catch (Exception e) {
                Messages.Print("Cannot adjust whitespace or tabs in file (write)."
                    + Environment.NewLine + $"({e})");
            }
        }

        private static string GetWhitespaces(long size)
        {
            var whitespaces = string.Empty;
            for (long i = 0; i < size; ++i)
                whitespaces += " ";
            return whitespaces;
        }

        public void AddActiveQtBuildStep(string version, string defFile = null)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            if (FormatVersion < Resources.qtMinFormatVersion_ClProperties)
                return;

            foreach (VCConfiguration config in (IVCCollection)vcPro.Configurations) {
                var idlFile = "\"$(IntDir)/" + envPro.Name + ".idl\"";
                var tblFile = "\"$(IntDir)/" + envPro.Name + ".tlb\"";

                var tool = (VCPostBuildEventTool)((IVCCollection)config.Tools).Item("VCPostBuildEventTool");
                var idc = "$(QTDIR)\\bin\\idc.exe \"$(TargetPath)\" /idl " + idlFile + " -version " + version;
                var midl = "midl " + idlFile + " /tlb " + tblFile;
                var idc2 = "$(QTDIR)\\bin\\idc.exe \"$(TargetPath)\" /tlb " + tblFile;
                var idc3 = "$(QTDIR)\\bin\\idc.exe \"$(TargetPath)\" /regserver";

                tool.CommandLine = idc + "\r\n" + midl + "\r\n" + idc2 + "\r\n" + idc3;
                tool.Description = string.Empty;

                var linker = (VCLinkerTool)((IVCCollection)config.Tools).Item("VCLinkerTool");
                var librarian = (VCLibrarianTool)((IVCCollection)config.Tools).Item("VCLibrarianTool");

                if (linker != null) {
                    linker.Version = version;
                    linker.ModuleDefinitionFile = defFile ?? envPro.Name + ".def";
                } else {
                    librarian.ModuleDefinitionFile = defFile ?? envPro.Name + ".def";
                }
            }
        }

        public bool UsesPrecompiledHeaders()
        {
            foreach (VCConfiguration config in vcPro.Configurations as IVCCollection) {
                if (!UsesPrecompiledHeaders(config))
                    return false;
            }
            return true;
        }

        public static bool UsesPrecompiledHeaders(VCConfiguration config)
        {
            var compiler = CompilerToolWrapper.Create(config);
            return UsesPrecompiledHeaders(compiler);
        }

        private static bool UsesPrecompiledHeaders(CompilerToolWrapper compiler)
        {
            try {
                if (compiler.GetUsePrecompiledHeader() != pchOption.pchNone)
                    return true;
            } catch { }
            return false;
        }

        public string GetPrecompiledHeaderThrough()
        {
            foreach (VCConfiguration config in vcPro.Configurations as IVCCollection) {
                var header = GetPrecompiledHeaderThrough(config);
                if (header != null)
                    return header;
            }
            return null;
        }

        public static string GetPrecompiledHeaderThrough(VCConfiguration config)
        {
            var compiler = CompilerToolWrapper.Create(config);
            return GetPrecompiledHeaderThrough(compiler);
        }

        private static string GetPrecompiledHeaderThrough(CompilerToolWrapper compiler)
        {
            try {
                var header = compiler.GetPrecompiledHeaderThrough();
                if (!string.IsNullOrEmpty(header))
                    return header.ToLower();
            } catch { }
            return null;
        }

        public static void SetPCHOption(VCFile vcFile, pchOption option)
        {
            foreach (VCFileConfiguration config in vcFile.FileConfigurations as IVCCollection) {
                var compiler = CompilerToolWrapper.Create(config);
                compiler.SetUsePrecompiledHeader(option);
            }
        }

        private static VCFileConfiguration GetVCFileConfigurationByName(VCFile file, string configName)
        {
            foreach (VCFileConfiguration cfg in (IVCCollection)file.FileConfigurations) {
                if (cfg.Name == configName)
                    return cfg;
            }
            return null;
        }

        /// <summary>
        /// Searches for the generated file inside the "Generated Files" filter.
        /// The function looks for the given filename and uses the fileConfig's
        /// ConfigurationName and Platform if moc directory contains $(ConfigurationName)
        /// and/or $(PlatformName).
        /// Otherwise it just uses the "Generated Files" filter
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="fileConfig"></param>
        /// <returns></returns>
        private VCFile GetGeneratedMocFile(string fileName, VCFileConfiguration fileConfig)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            if (QtVSIPSettings.HasDifferentMocFilePerConfig(envPro)
                || QtVSIPSettings.HasDifferentMocFilePerPlatform(envPro)) {
                var projectConfig = (VCConfiguration)fileConfig.ProjectConfiguration;
                var configName = projectConfig.ConfigurationName;
                var platformName = ((VCPlatform)projectConfig.Platform).Name;
                var generatedFiles = FindFilterFromGuid(Filters.GeneratedFiles().UniqueIdentifier);
                if (generatedFiles == null)
                    return null;
                foreach (VCFilter filt in (IVCCollection)generatedFiles.Filters) {
                    if (filt.Name == configName + "_" + platformName ||
                        filt.Name == configName || filt.Name == platformName) {
                        foreach (VCFile filtFile in (IVCCollection)filt.Files) {
                            if (HelperFunctions.PathIsRelativeTo(filtFile.FullPath, fileName))
                                return filtFile;
                        }
                    }
                }

                //If a project from the an AddIn prior to 1.1.0 was loaded, the generated files are located directly
                //in the generated files filter.
                var relativeMocPath = QtVSIPSettings.GetMocDirectory(
                    envPro,
                    configName,
                    platformName,
                    fileConfig.File as VCFile)
                    + Path.DirectorySeparatorChar + fileName;
                //Remove .\ at the beginning of the mocPath
                if (relativeMocPath.StartsWith(".\\", StringComparison.Ordinal))
                    relativeMocPath = relativeMocPath.Remove(0, 2);
                foreach (VCFile filtFile in (IVCCollection)generatedFiles.Files) {
                    if (HelperFunctions.PathIsRelativeTo(filtFile.FullPath, relativeMocPath))
                        return filtFile;
                }
            } else {
                var generatedFiles = FindFilterFromGuid(Filters.GeneratedFiles().UniqueIdentifier);
                foreach (VCFile filtFile in (IVCCollection)generatedFiles.Files) {
                    if (HelperFunctions.PathIsRelativeTo(filtFile.FullPath, fileName))
                        return filtFile;
                }
            }
            return null;
        }

        public void RefreshQtMocIncludePath()
        {
            foreach (VCConfiguration config in (IVCCollection)vcPro.Configurations) {
                var propsClCompile = config.Rules.Item("CL") as IVCRulePropertyStorage;
                var ruleName = GetRuleName(config, QtMoc.ItemTypeName);
                var propsQtMoc = config.Rules.Item(ruleName) as IVCRulePropertyStorage;
                if (propsClCompile == null || propsQtMoc == null)
                    continue;
                propsQtMoc.SetPropertyValue(QtMoc.Property.IncludePath.ToString(),
                    propsClCompile.GetUnevaluatedPropertyValue("AdditionalIncludeDirectories"));
            }
        }

        public void RefreshQtMocDefine()
        {
            foreach (VCConfiguration config in (IVCCollection)vcPro.Configurations) {
                var propsClCompile = config.Rules.Item("CL") as IVCRulePropertyStorage;
                var ruleName = GetRuleName(config, QtMoc.ItemTypeName);
                var propsQtMoc = config.Rules.Item(ruleName) as IVCRulePropertyStorage;
                if (propsClCompile == null || propsQtMoc == null)
                    continue;
                propsQtMoc.SetPropertyValue(QtMoc.Property.Define.ToString(),
                    propsClCompile.GetUnevaluatedPropertyValue("PreprocessorDefinitions"));
            }
        }

        public void RefreshMocSteps()
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            // Ignore when using shared compiler properties
            if (GetFormatVersion(vcPro) < Resources.qtMinFormatVersion_ClProperties) {
                // TODO: It would be nice if we can inform the user he's on an old project.
                //if (QtVsToolsPackage.Instance.Options.UpdateProjectFormat)
                //    Notifications.UpdateProjectFormat.Show();
            }
        }

        public void RefreshMocStep(VCFile vcfile)
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            RefreshMocStep(vcfile, true);
        }

        /// <summary>
        /// Updates the moc command line for the given header or source file
        /// containing the Q_OBJECT macro.
        /// If the function is called from a property change for a single file
        /// (singleFile =  true) we may have to look for the according header
        /// file and refresh the moc step for this file, if it contains Q_OBJECT.
        /// </summary>
        /// <param name="vcfile"></param>
        private void RefreshMocStep(VCFile vcfile, bool singleFile)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            var isHeaderFile = HelperFunctions.IsHeaderFile(vcfile.FullPath);
            if (!isHeaderFile && !HelperFunctions.IsSourceFile(vcfile.FullPath))
                return;

            if (mocCmdChecker == null)
                mocCmdChecker = new MocCmdChecker();

            foreach (VCFileConfiguration config in (IVCCollection)vcfile.FileConfigurations) {
                try {
                    string commandLine = "";
                    VCCustomBuildTool tool = null;
                    VCFile mocable = null;
                    var customBuildConfig = config;
                    if (isHeaderFile || vcfile.ItemType == QtMoc.ItemTypeName) {
                        mocable = vcfile;
                        if (vcfile.ItemType == "CustomBuild")
                            tool = HelperFunctions.GetCustomBuildTool(config);
                    } else {
                        var mocFileName = GetMocFileName(vcfile.FullPath);
                        var mocFile = GetGeneratedMocFile(mocFileName, config);
                        if (mocFile == null)
                            continue;

                        var mocFileConfig = GetVCFileConfigurationByName(mocFile, config.Name);
                        if (vcfile.ItemType == "CustomBuild")
                            tool = HelperFunctions.GetCustomBuildTool(mocFileConfig);
                        mocable = mocFile;
                        // It is possible that the function was called from a source file's property change, it is possible that
                        // we have to obtain the tool from the according header file
                        if ((vcfile.ItemType != "CustomBuild" || tool == null) && singleFile) {
                            var headerName = vcfile.FullPath.Remove(vcfile.FullPath.LastIndexOf('.')) + ".h";
                            mocFileName = GetMocFileName(headerName);
                            mocFile = GetGeneratedMocFile(mocFileName, config);
                            if (mocFile != null) {
                                mocable = GetFileFromProject(headerName);
                                customBuildConfig = GetVCFileConfigurationByName(mocable, config.Name);
                                if (mocable.ItemType == "CustomBuild")
                                    tool = HelperFunctions.GetCustomBuildTool(customBuildConfig);
                            }
                        }
                    }

                    if (mocable.ItemType == "CustomBuild") {
                        if (tool != null)
                            commandLine = tool.CommandLine;
                    } else if (mocable.ItemType == QtMoc.ItemTypeName) {
                        commandLine = qtMsBuild.GenerateQtMocCommandLine(customBuildConfig);
                    } else {
                        continue;
                    }

                    if ((mocable.ItemType == "CustomBuild" && tool == null)
                        || commandLine.IndexOf(
                            "moc.exe",
                            StringComparison.OrdinalIgnoreCase) == -1)
                        continue;

                    VCFile srcMocFile, cppFile;
                    if (vcfile.ItemType == QtMoc.ItemTypeName
                        && HelperFunctions.IsSourceFile(vcfile.ItemName)) {
                        srcMocFile = cppFile = vcfile;
                    } else {
                        srcMocFile = GetSourceFileForMocStep(mocable);
                        cppFile = GetCppFileForMocStep(mocable);
                    }
                    if (srcMocFile == null)
                        continue;
                    var mocableIsCPP = (srcMocFile == cppFile);

                    var cppItemType = (cppFile != null) ? cppFile.ItemType : "";
                    if (cppFile != null && cppItemType != "ClCompile")
                        cppFile.ItemType = "ClCompile";

                    string pchParameters = null;
                    VCFileConfiguration defineIncludeConfig = null;
                    CompilerToolWrapper compiler = null;
                    if (cppFile == null) {
                        // No file specific defines/includes
                        // but at least the project defines/includes are added
                        defineIncludeConfig = config;
                        compiler = CompilerToolWrapper.Create(config.ProjectConfiguration as VCConfiguration);
                    } else {
                        defineIncludeConfig = GetVCFileConfigurationByName(cppFile, config.Name);
                        compiler = CompilerToolWrapper.Create(defineIncludeConfig);
                    }

                    if (compiler != null && compiler.GetUsePrecompiledHeader() != pchOption.pchNone)
                        pchParameters = GetPCHMocOptions(srcMocFile, compiler);

                    var outputFileName = QtVSIPSettings.GetMocDirectory(envPro)
                        + Path.DirectorySeparatorChar;
                    if (mocableIsCPP) {
                        outputFileName += ProjectMacros.Name;
                        outputFileName += ".moc";
                    } else {
                        outputFileName += "moc_";
                        outputFileName += ProjectMacros.Name;
                        outputFileName += ".cpp";
                    }

                    var newCmdLine = mocCmdChecker.NewCmdLine(commandLine,
                        GetIncludes(defineIncludeConfig),
                        GetDefines(defineIncludeConfig),
                        QtVSIPSettings.GetMocOptions(envPro), srcMocFile.RelativePath,
                        pchParameters,
                        outputFileName);

                    if (cppFile != null && cppItemType != "ClCompile")
                        cppFile.ItemType = cppItemType;

                    // The tool's command line automatically gets a trailing "\r\n".
                    // We have to remove it to make the check below work.
                    var origCommandLine = commandLine;
                    if (origCommandLine.EndsWith("\r\n", StringComparison.Ordinal))
                        origCommandLine = origCommandLine.Substring(0, origCommandLine.Length - 2);

                    if (newCmdLine != null && newCmdLine != origCommandLine) {
                        // We have to delete the old moc file in order to trigger custom build step.
                        var configName = config.Name.Remove(config.Name.IndexOf('|'));
                        var platformName = config.Name.Substring(config.Name.IndexOf('|') + 1);
                        var projectPath = envPro.FullName.Remove(envPro.FullName.LastIndexOf(Path
                            .DirectorySeparatorChar));
                        var mocRelPath = GetRelativeMocFilePath(srcMocFile.FullPath, configName, platformName);
                        var mocPath = Path.Combine(projectPath, mocRelPath);
                        if (File.Exists(mocPath))
                            File.Delete(mocPath);
                        if (mocable.ItemType == "CustomBuild") {
                            tool.CommandLine = newCmdLine;
                        } else {
                            qtMsBuild.SetQtMocCommandLine(
                                customBuildConfig, newCmdLine, new VCMacroExpander(config));
                        }
                    }
                } catch {
                    Messages.Print("ERROR: failed to refresh moc step for " + vcfile.ItemName);
                }
            }
        }

        public void OnExcludedFromBuildChanged(VCFile vcFile, VCFileConfiguration vcFileCfg)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            // Update the ExcludedFromBuild flags of the mocced file
            // according to the ExcludedFromBuild flag of the mocable source file.
            var moccedFileName = GetMocFileName(vcFile.Name);
            if (string.IsNullOrEmpty(moccedFileName))
                return;

            var moccedFile = GetGeneratedMocFile(moccedFileName, vcFileCfg);

            if (moccedFile != null) {
                VCFile cppFile = null;
                if (HelperFunctions.IsHeaderFile(vcFile.Name))
                    cppFile = GetCppFileForMocStep(vcFile);

                var moccedFileConfig = GetVCFileConfigurationByName(moccedFile, vcFileCfg.Name);
                if (moccedFileConfig != null) {
                    if (cppFile != null && IsMoccedFileIncluded(cppFile)) {
                        if (!moccedFileConfig.ExcludedFromBuild)
                            moccedFileConfig.ExcludedFromBuild = true;
                    } else if (moccedFileConfig.ExcludedFromBuild != vcFileCfg.ExcludedFromBuild) {
                        moccedFileConfig.ExcludedFromBuild = vcFileCfg.ExcludedFromBuild;
                    }
                }
            }
        }

        /// <summary>
        /// Helper function for RefreshMocStep.
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        private VCFile GetSourceFileForMocStep(VCFile file)
        {
            if (HelperFunctions.IsHeaderFile(file.Name))
                return file;
            var fileName = file.Name;
            if (HelperFunctions.IsMocFile(fileName)) {
                fileName = fileName.Substring(0, fileName.Length - 4) + ".cpp";
                if (fileName.Length > 0) {
                    foreach (VCFile f in (IVCCollection)vcPro.Files) {
                        if (f.FullPath.EndsWith(Path.DirectorySeparatorChar + fileName, StringComparison.OrdinalIgnoreCase))
                            return f;
                    }
                }
            }
            return null;
        }

        /// <summary>
        /// Helper function for Refresh/UpdateMocStep.
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        private VCFile GetCppFileForMocStep(VCFile file)
        {
            string fileName = file.Name;
            if (fileName.EndsWith(".moc.cbt", StringComparison.OrdinalIgnoreCase))
                fileName = fileName.Remove(fileName.LastIndexOf('.'));
            if (HelperFunctions.IsHeaderFile(fileName) || HelperFunctions.IsMocFile(fileName)) {
                fileName = fileName.Remove(fileName.LastIndexOf('.')) + ".cpp";
                foreach (VCFile f in (IVCCollection)vcPro.Files) {
                    if (f.FullPath.EndsWith(Path.DirectorySeparatorChar + fileName, StringComparison.OrdinalIgnoreCase))
                        return f;
                }
            }
            return null;
        }

        public bool HasPlatform(string platformName)
        {
            foreach (VCConfiguration config in (IVCCollection)vcPro.Configurations) {
                var platform = (VCPlatform)config.Platform;
                if (platform.Name == platformName)
                    return true;
            }
            return false;
        }

        public bool SelectSolutionPlatform(string platformName)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            foreach (SolutionConfiguration solutionCfg in dte.Solution.SolutionBuild.SolutionConfigurations) {
                var contexts = solutionCfg.SolutionContexts;
                for (var i = 1; i <= contexts.Count; ++i) {
                    SolutionContext ctx = null;
                    try {
                        ctx = contexts.Item(i);
                    } catch (ArgumentException) {
                        // This may happen if we encounter an unloaded project.
                        continue;
                    }

                    if (ctx.PlatformName == platformName
                        && solutionCfg.Name == dte.Solution.SolutionBuild.ActiveConfiguration.Name) {
                        solutionCfg.Activate();
                        return true;
                    }
                }
            }

            return false;
        }

        public void CreatePlatform(string oldPlatform, string newPlatform,
                                   VersionInformation viOld, VersionInformation viNew, ref bool newProjectCreated)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            try {
                var cfgMgr = envPro.ConfigurationManager;
                cfgMgr.AddPlatform(newPlatform, oldPlatform, true);
                vcPro.AddPlatform(newPlatform);
                newProjectCreated = false;
            } catch {
                // That stupid ConfigurationManager can't handle platform names
                // containing dots (e.g. "Windows Mobile 5.0 Pocket PC SDK (ARMV4I)")
                // So we have to do it the nasty way...
                var projectFileName = envPro.FullName;
                envPro.Save(null);
                dte.Solution.Remove(envPro);
                AddPlatformToVCProj(projectFileName, oldPlatform, newPlatform);
                envPro = dte.Solution.AddFromFile(projectFileName, false);
                vcPro = (VCProject)envPro.Object;
                newProjectCreated = true;
            }

            // update the platform settings
            foreach (VCConfiguration config in (IVCCollection)vcPro.Configurations) {
                var vcplatform = (VCPlatform)config.Platform;
                if (vcplatform.Name == newPlatform) {
                    if (viOld != null)
                        RemovePlatformDependencies(config, viOld);
                    SetupConfiguration(config, viNew);
                }
            }

            SelectSolutionPlatform(newPlatform);
        }

        public static void RemovePlatformDependencies(VCConfiguration config, VersionInformation viOld)
        {
            var compiler = CompilerToolWrapper.Create(config);
            var minuend = new HashSet<string>(compiler.PreprocessorDefinitions);
            minuend.ExceptWith(viOld.GetQMakeConfEntry("DEFINES").Split(' ', '\t'));
            compiler.SetPreprocessorDefinitions(string.Join(",", minuend));
        }

        public void SetupConfiguration(VCConfiguration config, VersionInformation viNew)
        {
            var compiler = CompilerToolWrapper.Create(config);
            var ppdefs = new HashSet<string>(compiler.PreprocessorDefinitions);
            ppdefs.UnionWith(viNew.GetQMakeConfEntry("DEFINES").Split(' ', '\t'));
            compiler.SetPreprocessorDefinitions(string.Join(",", ppdefs));

            var linker = (VCLinkerTool)((IVCCollection)config.Tools).Item("VCLinkerTool");
            if (linker == null)
                return;

            linker.SubSystem = subSystemOption.subSystemWindows;
            SetTargetMachine(linker, viNew);
        }

        public void RemoveGeneratedFiles(string fileName)
        {
            var fi = new FileInfo(fileName);
            var lastIndex = fileName.LastIndexOf(fi.Extension, StringComparison.Ordinal);
            var baseName = fi.Name.Remove(lastIndex, fi.Extension.Length);
            string delName = null;
            if (HelperFunctions.IsHeaderFile(fileName))
                delName = "moc_" + baseName + ".cpp";
            else if (HelperFunctions.IsSourceFile(fileName) && !fileName.StartsWith("moc_", StringComparison.OrdinalIgnoreCase))
                delName = baseName + ".moc";
            else if (HelperFunctions.IsUicFile(fileName))
                delName = "ui_" + baseName + ".h";
            else if (HelperFunctions.IsQrcFile(fileName))
                delName = "qrc_" + baseName + ".cpp";

            if (delName != null) {
                foreach (var delFile in GetFilesFromProject(delName))
                    RemoveFileFromFilter(delFile, Filters.GeneratedFiles());
            }
        }

        private static void AddPlatformToVCProj(string projectFileName, string oldPlatformName, string newPlatformName)
        {
            var tempFileName = Path.GetTempFileName();
            var fi = new FileInfo(projectFileName);
            fi.CopyTo(tempFileName, true);

            var myXmlDocument = new XmlDocument();
            myXmlDocument.Load(tempFileName);
            AddPlatformToVCProj(myXmlDocument, oldPlatformName, newPlatformName);
            myXmlDocument.Save(projectFileName);

            fi = new FileInfo(tempFileName);
            fi.Delete();
        }

        private static void AddPlatformToVCProj(XmlDocument doc, string oldPlatformName, string newPlatformName)
        {
            var vsProj = doc.DocumentElement.SelectSingleNode("/VisualStudioProject");
            var platforms = vsProj.SelectSingleNode("Platforms");
            if (platforms == null) {
                platforms = doc.CreateElement("Platforms");
                vsProj.AppendChild(platforms);
            }
            var platform = platforms.SelectSingleNode("Platform[@Name='" + newPlatformName + "']");
            if (platform == null) {
                platform = doc.CreateElement("Platform");
                ((XmlElement)platform).SetAttribute("Name", newPlatformName);
                platforms.AppendChild(platform);
            }

            var configurations = vsProj.SelectSingleNode("Configurations");
            var cfgList = configurations.SelectNodes("Configuration[@Name='Debug|" + oldPlatformName + "'] | " +
                                                             "Configuration[@Name='Release|" + oldPlatformName + "']");
            foreach (XmlNode oldCfg in cfgList) {
                var newCfg = (XmlElement)oldCfg.Clone();
                newCfg.SetAttribute("Name", oldCfg.Attributes["Name"].Value.Replace(oldPlatformName, newPlatformName));
                configurations.AppendChild(newCfg);
            }

            var fileCfgPath = "Files/Filter/File/FileConfiguration";
            var fileCfgList = vsProj.SelectNodes(fileCfgPath + "[@Name='Debug|" + oldPlatformName + "'] | " +
                                                         fileCfgPath + "[@Name='Release|" + oldPlatformName + "']");
            foreach (XmlNode oldCfg in fileCfgList) {
                var newCfg = (XmlElement)oldCfg.Clone();
                newCfg.SetAttribute("Name", oldCfg.Attributes["Name"].Value.Replace(oldPlatformName, newPlatformName));
                oldCfg.ParentNode.AppendChild(newCfg);
            }
        }

        private static void SetTargetMachine(VCLinkerTool linker, VersionInformation versionInfo)
        {
            var qMakeLFlagsWindows = versionInfo.GetQMakeConfEntry("QMAKE_LFLAGS_WINDOWS");
            var rex = new Regex("/MACHINE:(\\S+)");
            var match = rex.Match(qMakeLFlagsWindows);
            if (match.Success) {
                linker.TargetMachine = HelperFunctions.TranslateMachineType(match.Groups[1].Value);
            } else {
                var platformName = versionInfo.GetVSPlatformName();
                if (platformName == "Win32")
                    linker.TargetMachine = machineTypeOption.machineX86;
                else if (platformName == "x64")
                    linker.TargetMachine = machineTypeOption.machineAMD64;
                else
                    linker.TargetMachine = machineTypeOption.machineNotSet;
            }

            var subsystemOption = string.Empty;
            var linkerOptions = linker.AdditionalOptions ?? string.Empty;

            rex = new Regex("(/SUBSYSTEM:\\S+)");
            match = rex.Match(qMakeLFlagsWindows);
            if (match.Success)
                subsystemOption = match.Groups[1].Value;

            match = rex.Match(linkerOptions);
            if (match.Success) {
                linkerOptions = rex.Replace(linkerOptions, subsystemOption);
            } else {
                if (linkerOptions.Length > 0)
                    linkerOptions += " ";
                linkerOptions += subsystemOption;
            }
            linker.AdditionalOptions = linkerOptions;
        }

        /// <summary>
        /// Gets the Qt version of the project
        /// </summary>
        public string GetQtVersion()
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            return QtVersionManager.The().GetProjectQtVersion(envPro);
        }

        public class CppConfig
        {
            public VCConfiguration Config;
            public IVCRulePropertyStorage Cpp;

            public string GetUserPropertyValue(string pszPropName)
            {
                var vcProj = Config.project as VCProject;
                var projProps = vcProj as IVCBuildPropertyStorage;
                try {
                    return projProps.GetPropertyValue(pszPropName, Config.Name, "UserFile");
                } catch (Exception exception) {
                    exception.Log();
                    return string.Empty;
                }
            }

            public void SetUserPropertyValue(string pszPropName, string pszPropValue)
            {
                var vcProj = Config.project as VCProject;
                var projProps = vcProj as IVCBuildPropertyStorage;
                try {
                    projProps.SetPropertyValue(pszPropName, Config.Name, "UserFile", pszPropValue);
                } catch (Exception exception) {
                    exception.Log();
                }
            }

            public void RemoveUserProperty(string pszPropName)
            {
                var vcProj = Config.project as VCProject;
                var projProps = vcProj as IVCBuildPropertyStorage;
                try {
                    projProps.RemoveProperty(pszPropName, Config.Name, "UserFile");
                } catch (Exception exception) {
                    exception.Log();
                }
            }
        }

        public static IEnumerable<CppConfig> GetCppConfigs(VCProject vcPro)
        {
            return ((IVCCollection)vcPro.Configurations).Cast<VCConfiguration>()
                .Select(x => new CppConfig
                {
                    Config = x,
                    Cpp = x.Rules.Item("CL") as IVCRulePropertyStorage,
                })
                .Where(x => x.Cpp != null
                    && x.Config.GetEvaluatedPropertyValue("ApplicationType") != "Linux");
        }

        public static IEnumerable<CppConfig> GetCppDebugConfigs(VCProject vcPro)
        {
            var cppConfigs = GetCppConfigs(vcPro)
                .Select(x => new { Self = x, x.Cpp });
            var cppConfigMacros = cppConfigs
                .Select(x => new
                {
                    x.Self,
                    Macros = x.Cpp.GetEvaluatedPropertyValue("PreprocessorDefinitions")
                })
                .Where(x => !string.IsNullOrEmpty(x.Macros));
            var cppDebugConfigs = cppConfigMacros
                .Where(x => !x.Macros.Split(';').Contains("QT_NO_DEBUG"))
                .Select(x => x.Self);
            return cppDebugConfigs;
        }

        public static bool IsQtQmlDebugDefined(VCProject vcPro)
        {
            var cppConfigs = GetCppConfigs(vcPro)
                .Select(x => new { Self = x, x.Cpp });
            var cppConfigMacros = cppConfigs
                .Select(x => new
                {
                    x.Self,
                    Macros = x.Cpp.GetEvaluatedPropertyValue("PreprocessorDefinitions")
                })
                .Where(x => !string.IsNullOrEmpty(x.Macros));
            return cppConfigMacros
                .Any(x => x.Macros.Split(';').Contains("QT_QML_DEBUG"));
        }

        public static void DefineQtQmlDebug(VCProject vcPro)
        {
            var configs = GetCppDebugConfigs(vcPro).Where(x => x.Cpp
                .GetEvaluatedPropertyValue("PreprocessorDefinitions").Split(new char[] { ';' })
                .Contains("QT_QML_DEBUG") == false)
                .Select(x => new
                {
                    x.Cpp,
                    Macros = x.Cpp.GetUnevaluatedPropertyValue("PreprocessorDefinitions")
                });

            foreach (var config in configs) {
                config.Cpp.SetPropertyValue("PreprocessorDefinitions",
                    string.Format("QT_QML_DEBUG;{0}", config.Macros));
            }
        }

        public static void UndefineQtQmlDebug(VCProject vcPro)
        {
            var configs = GetCppDebugConfigs(vcPro).Where(x => x.Cpp
                .GetEvaluatedPropertyValue("PreprocessorDefinitions").Split(new char[] { ';' })
                .Contains("QT_QML_DEBUG") == true)
                .Select(x => new
                {
                    x.Cpp,
                    Macros = x.Cpp.GetUnevaluatedPropertyValue("PreprocessorDefinitions")
                        .Split(new char[] { ';' }).ToList()
                });

            foreach (var config in configs) {
                config.Macros.Remove("QT_QML_DEBUG");
                config.Cpp.SetPropertyValue("PreprocessorDefinitions",
                    string.Join(";", config.Macros));
            }
        }

        public static bool IsQmlJsDebuggerDefined(VCProject vcPro)
        {
            foreach (var config in GetCppDebugConfigs(vcPro)) {
                var qmlDebug = config.GetUserPropertyValue("QmlDebug");
                if (string.IsNullOrEmpty(qmlDebug))
                    return false;
                var debugArgs = config.GetUserPropertyValue("LocalDebuggerCommandArguments");
                if (string.IsNullOrEmpty(debugArgs))
                    return false;
                if (!debugArgs.Contains(qmlDebug))
                    return false;
            }
            return true;
        }

        public static void DefineQmlJsDebugger(VCProject vcPro)
        {
            var configs = GetCppDebugConfigs(vcPro)
                .Select(x => new
                {
                    Self = x,
                    QmlDebug = x.GetUserPropertyValue("QmlDebug"),
                    Args = x.GetUserPropertyValue("LocalDebuggerCommandArguments")
                })
                .Where(x => string.IsNullOrEmpty(x.QmlDebug) || !x.Args.Contains(x.QmlDebug));

            foreach (var config in configs) {

                config.Self.RemoveUserProperty("LocalDebuggerCommandArguments");
                config.Self.RemoveUserProperty("QmlDebug");
                config.Self.RemoveUserProperty("QmlDebugSettings");

                config.Self.SetUserPropertyValue("QmlDebugSettings", "file:$(ProjectGuid),block");
                config.Self.SetUserPropertyValue("QmlDebug", "-qmljsdebugger=$(QmlDebugSettings)");

                config.Self.SetUserPropertyValue("LocalDebuggerCommandArguments",
                    string.Join(" ", new[] { config.Args, "$(QmlDebug)" }).Trim());
            }
        }

        public static void UndefineQmlJsDebugger(VCProject vcPro)
        {
            var configs = GetCppDebugConfigs(vcPro)
                .Select(x => new
                {
                    Self = x,
                    QmlDebug = x.GetUserPropertyValue("QmlDebug"),
                    Args = x.GetUserPropertyValue("LocalDebuggerCommandArguments")
                })
                .Where(x => !string.IsNullOrEmpty(x.QmlDebug) && x.Args.Contains(x.QmlDebug));

            foreach (var config in configs) {

                config.Self.SetUserPropertyValue("QmlDebug", "##QMLDEBUG##");
                var args = config.Self.GetUserPropertyValue("LocalDebuggerCommandArguments");

                var newArgs = args.Replace("##QMLDEBUG##", "").Trim();
                if (string.IsNullOrEmpty(newArgs))
                    config.Self.RemoveUserProperty("LocalDebuggerCommandArguments");
                else
                    config.Self.SetUserPropertyValue("LocalDebuggerCommandArguments", newArgs);

                config.Self.RemoveUserProperty("QmlDebug");
                config.Self.SetUserPropertyValue("QmlDebugSettings", "false");
            }
        }

        public bool QmlDebug
        {
            get => IsQtQmlDebugDefined(vcPro) && IsQmlJsDebuggerDefined(vcPro);
            set
            {
                bool enabled = (IsQtQmlDebugDefined(vcPro) && IsQmlJsDebuggerDefined(vcPro));
                if (value == enabled)
                    return;

                if (value) {
                    DefineQtQmlDebug(vcPro);
                    DefineQmlJsDebugger(vcPro);
                } else {
                    UndefineQtQmlDebug(vcPro);
                    UndefineQmlJsDebugger(vcPro);
                }
            }
        }
    }

    public class VCPropertyStorageProvider : IPropertyStorageProvider
    {
        string GetProperty(IVCRulePropertyStorage propertyStorage, string propertyName)
        {
            if (propertyStorage == null)
                return "";
            return propertyStorage.GetUnevaluatedPropertyValue(propertyName);
        }

        public string GetProperty(object propertyStorage, string itemType, string propertyName)
        {
            if (propertyStorage is VCFileConfiguration vcFileConfiguration) {
                return GetProperty(
                    vcFileConfiguration.Tool
                    as IVCRulePropertyStorage,
                    propertyName);
            }
            if (propertyStorage is VCConfiguration vcConfiguration) {
                var ruleName = QtProject.GetRuleName(vcConfiguration, itemType);
                return GetProperty(vcConfiguration.Rules.Item(ruleName)
                    as IVCRulePropertyStorage,
                    propertyName);
            }
            return "";
        }

        static bool SetProperty(
            IVCRulePropertyStorage propertyStorage,
            string propertyName,
            string propertyValue)
        {
            if (propertyStorage == null)
                return false;
            if (propertyStorage.GetUnevaluatedPropertyValue(propertyName) != propertyValue)
                propertyStorage.SetPropertyValue(propertyName, propertyValue);
            return true;
        }

        public bool SetProperty(
            object propertyStorage,
            string itemType,
            string propertyName,
            string propertyValue)
        {
            if (propertyStorage is VCFileConfiguration vcFileConfiguration) {
                return SetProperty(
                    vcFileConfiguration.Tool
                    as IVCRulePropertyStorage,
                    propertyName,
                    propertyValue);
            }
            if (propertyStorage is VCConfiguration vcConfiguration) {
                var ruleName = QtProject.GetRuleName(vcConfiguration, itemType);
                return SetProperty(
                    vcConfiguration.Rules.Item(ruleName)
                    as IVCRulePropertyStorage,
                    propertyName,
                    propertyValue);
            }
            return false;
        }

        static bool DeleteProperty(IVCRulePropertyStorage propertyStorage, string propertyName)
        {
            if (propertyStorage == null)
                return false;
            propertyStorage.DeleteProperty(propertyName);
            return true;
        }

        public bool DeleteProperty(object propertyStorage, string itemType, string propertyName)
        {
            if (propertyStorage is VCFileConfiguration vcFileConfiguration) {
                return DeleteProperty(
                    vcFileConfiguration.Tool
                    as IVCRulePropertyStorage,
                    propertyName);
            }
            if (propertyStorage is VCConfiguration vcConfiguration) {
                var ruleName = QtProject.GetRuleName(vcConfiguration, itemType);
                return DeleteProperty(
                    vcConfiguration.Rules.Item(ruleName)
                    as IVCRulePropertyStorage,
                    propertyName);
            }
            return false;
        }

        public string GetConfigName(object propertyStorage)
        {
            if (propertyStorage is VCFileConfiguration vcFileConfiguration)
                return vcFileConfiguration.Name;
            if (propertyStorage is VCConfiguration vcConfiguration)
                return vcConfiguration.Name;
            return "";
        }

        string GetItemType(VCFileConfiguration propertyStorage)
        {
            if (propertyStorage?.File is VCFile vcFile)
                return vcFile.ItemType;
            return "";
        }

        public string GetItemType(object propertyStorage)
        {
            if (propertyStorage is VCFileConfiguration vcFileConfiguration)
                return GetItemType(vcFileConfiguration);
            return "";
        }

        string GetItemName(VCFileConfiguration propertyStorage)
        {
            if (propertyStorage?.File is VCFile vcFile)
                return vcFile.Name;
            return "";
        }

        public string GetItemName(object propertyStorage)
        {
            if (propertyStorage is VCFileConfiguration vcFileConfiguration)
                return GetItemName(vcFileConfiguration);
            return "";
        }

        object GetParentProject(VCConfiguration propertyStorage)
        {
            if (propertyStorage == null)
                return null;
            return propertyStorage.project as VCProject;
        }

        object GetParentProject(VCFileConfiguration propertyStorage)
        {
            if (propertyStorage == null)
                return null;
            return GetParentProject(propertyStorage.ProjectConfiguration as VCConfiguration);
        }

        public object GetParentProject(object propertyStorage)
        {
            if (propertyStorage == null)
                return null;
            if (propertyStorage is VCFileConfiguration configuration)
                return GetParentProject(configuration);
            else if (propertyStorage is VCConfiguration storage)
                return GetParentProject(storage);
            return null;
        }

        object GetProjectConfiguration(VCProject project, string configName)
        {
            if (project == null)
                return null;
            foreach (VCConfiguration projConfig in (IVCCollection)project.Configurations) {
                if (projConfig.Name == configName)
                    return projConfig;
            }
            return null;
        }

        public object GetProjectConfiguration(object project, string configName)
        {
            if (project == null)
                return null;
            return GetProjectConfiguration(project as VCProject, configName);
        }

        IEnumerable<object> GetItems(VCProject project, string itemType, string configName = "")
        {
            if (project == null)
                return new List<object>();
            var allItems = project.GetFilesWithItemType(itemType) as IVCCollection;
            var items = new List<VCFileConfiguration>();
            foreach (VCFile vcFile in allItems) {
                foreach (VCFileConfiguration vcFileConfig
                    in vcFile.FileConfigurations as IVCCollection) {
                    if (!string.IsNullOrEmpty(configName) && vcFileConfig.Name != configName)
                        continue;
                    items.Add(vcFileConfig);
                }
            }
            return items;
        }

        public IEnumerable<object> GetItems(
            object project,
            string itemType,
            string configName = "")
        {
            if (project == null)
                return null;
            return GetItems(project as VCProject, itemType, configName);
        }

    }

    public class VCMacroExpander : IVSMacroExpander
    {
        readonly object config;
        public VCMacroExpander(object config)
        {
            this.config = config;
        }

        public string ExpandString(string stringToExpand)
        {
            HelperFunctions.ExpandString(ref stringToExpand, config);
            return stringToExpand;
        }
    }

    public class QtCustomBuildTool
    {
        readonly QtMsBuildContainer qtMsBuild;
        readonly VCFileConfiguration vcConfig;
        readonly VCFile vcFile;
        readonly VCCustomBuildTool tool;
        readonly VCMacroExpander macros;

        enum FileItemType { Other = 0, CustomBuild, QtMoc, QtRcc, QtRepc, QtUic };
        readonly FileItemType itemType = FileItemType.Other;

        public QtCustomBuildTool(VCFileConfiguration vcConfig, QtMsBuildContainer container = null)
        {
            if (container != null)
                qtMsBuild = container;
            else
                qtMsBuild = new QtMsBuildContainer(new VCPropertyStorageProvider());
            this.vcConfig = vcConfig;
            if (vcConfig != null)
                vcFile = vcConfig.File as VCFile;
            if (vcFile != null) {
                if (vcFile.ItemType == "CustomBuild")
                    itemType = FileItemType.CustomBuild;
                else if (vcFile.ItemType == QtMoc.ItemTypeName)
                    itemType = FileItemType.QtMoc;
                else if (vcFile.ItemType == QtRcc.ItemTypeName)
                    itemType = FileItemType.QtRcc;
                else if (vcFile.ItemType == QtRepc.ItemTypeName)
                    itemType = FileItemType.QtRepc;
                else if (vcFile.ItemType == QtUic.ItemTypeName)
                    itemType = FileItemType.QtUic;
            }
            if (itemType == FileItemType.CustomBuild)
                tool = HelperFunctions.GetCustomBuildTool(vcConfig);
            macros = new VCMacroExpander(vcConfig);
        }

        public string CommandLine
        {
            get
            {
                switch (itemType) {
                case FileItemType.CustomBuild:
                    return (tool != null) ? tool.CommandLine : "";
                case FileItemType.QtMoc:
                    return qtMsBuild.GenerateQtMocCommandLine(vcConfig);
                case FileItemType.QtRcc:
                    return qtMsBuild.GenerateQtRccCommandLine(vcConfig);
                case FileItemType.QtRepc:
                    return qtMsBuild.GenerateQtRepcCommandLine(vcConfig);
                case FileItemType.QtUic:
                    return qtMsBuild.GenerateQtUicCommandLine(vcConfig);
                }
                return "";
            }
            set
            {
                switch (itemType) {
                case FileItemType.CustomBuild:
                    if (tool != null)
                        tool.CommandLine = value;
                    break;
                case FileItemType.QtMoc:
                    qtMsBuild.SetQtMocCommandLine(vcConfig, value, macros);
                    break;
                case FileItemType.QtRcc:
                    qtMsBuild.SetQtRccCommandLine(vcConfig, value, macros);
                    break;
                case FileItemType.QtRepc:
                    qtMsBuild.SetQtRepcCommandLine(vcConfig, value, macros);
                    break;
                case FileItemType.QtUic:
                    qtMsBuild.SetQtUicCommandLine(vcConfig, value, macros);
                    break;
                }
            }
        }

        public string Outputs
        {
            get
            {
                switch (itemType) {
                case FileItemType.CustomBuild:
                    return (tool != null) ? tool.Outputs : "";
                case FileItemType.QtMoc:
                    return qtMsBuild.GetPropertyValue(vcConfig, QtMoc.Property.OutputFile);
                case FileItemType.QtRcc:
                    return qtMsBuild.GetPropertyValue(vcConfig, QtRcc.Property.OutputFile);
                case FileItemType.QtRepc:
                    return qtMsBuild.GetPropertyValue(vcConfig, QtRepc.Property.OutputFile);
                case FileItemType.QtUic:
                    return qtMsBuild.GetPropertyValue(vcConfig, QtUic.Property.OutputFile);
                }
                return "";
            }
        }

    }

}