aboutsummaryrefslogtreecommitdiffstats
path: root/QtVsTools.Core/MsBuild/MsBuildProjectReaderWriter.cs
blob: 1f7aea28e6a73bb6c3d1a7a5b58c582e083d9695 (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
// Copyright (C) 2025 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Linq;
using Microsoft.Build.Construction;
using Microsoft.Build.Evaluation;
using Microsoft.Build.Execution;
using Microsoft.Win32;

namespace QtVsTools.Core.MsBuild
{
    using Common;
    using SyntaxAnalysis;
    using static Common.Utils;
    using static HelperFunctions;
    using static MsBuildProjectFormat;
    using static SyntaxAnalysis.RegExpr;

    public partial class MsBuildProjectReaderWriter
    {
        private class MsBuildXmlFile
        {
            public string Path { get; set; } = "";
            public XDocument Xml { get; set; }
            public XDocument XmlCommitted { get; set; }
            public bool IsDirty => XmlCommitted?.ToString() != Xml?.ToString();
        }

        private enum Files
        {
            Project = 0,
            Filters,
            User,
            Count
        }

        private readonly MsBuildXmlFile[] files = new MsBuildXmlFile[(int)Files.Count];

        public class FileChangeData
        {
            public string Path { get; set; }
            public string Before { get; set; }
            public string After { get; set; }
        }

        public class CommitData
        {
            public string Message { get; set; }
            public List<FileChangeData> Changes { get; } = new();
        }

        public class ConversionData
        {
            public DateTime DateTime { get; set; }
            public List<FileChangeData> FilesChanged { get; set; }
            public List<CommitData> Commits { get; set; }
        }

        private List<CommitData> Commits { get; } = new();

        private MsBuildProjectReaderWriter()
        {
            for (var i = 0; i < files.Length; i++)
                files[i] = new MsBuildXmlFile();
        }

        private MsBuildXmlFile this[Files file]
        {
            get => (int)file >= (int)Files.Count ? files[0] : files[(int)file];
        }

        private static readonly XNamespace ns = "http://schemas.microsoft.com/developer/msbuild/2003";

        public static MsBuildProjectReaderWriter Load(string pathToProject)
        {
            if (!File.Exists(pathToProject))
                return null;

            var project = new MsBuildProjectReaderWriter
            {
                [Files.Project] =
                {
                    Path = pathToProject
                }
            };

            if (!LoadXml(project[Files.Project]))
                return null;

            project[Files.Filters].Path = pathToProject + ".filters";
            if (File.Exists(project[Files.Filters].Path) && !LoadXml(project[Files.Filters]))
                return null;

            project[Files.User].Path = pathToProject + ".user";
            if (File.Exists(project[Files.User].Path) && !LoadXml(project[Files.User]))
                return null;

            return project;
        }

        private static bool LoadXml(MsBuildXmlFile xmlFile)
        {
            try {
                var xmlText = File.ReadAllText(xmlFile.Path, Encoding.UTF8);
                xmlFile.Xml = XDocument.Parse(xmlText);
            } catch (Exception) {
                return false;
            }
            xmlFile.XmlCommitted = new XDocument(xmlFile.Xml);
            return true;
        }

        public bool Save()
        {
            var fileChanges = new List<FileChangeData>();
            foreach (var file in files) {
                if (file.Xml is null)
                    continue;
                try {
                    var before = File.ReadAllText(file.Path);
                    file.Xml.Save(file.Path, SaveOptions.None);
                    var after = File.ReadAllText(file.Path);
                    if (before == after)
                        continue;
                    fileChanges.Add(new FileChangeData
                    {
                        Path = file.Path,
                        Before = before,
                        After = after
                    });
                } catch (Exception e) {
                    e.Log();
                    return false;
                }
            }
            if (!fileChanges.Any())
                return true;

            var conversionData = new ConversionData
            {
                DateTime = DateTime.Now,
                FilesChanged = fileChanges,
                Commits = Commits
            };
            if (ConversionReport.Generate(conversionData) is not { } report)
                return false;

            return report.Save(Path.ChangeExtension(this[Files.Project].Path, "qtvscr"));
        }

        private void Commit(string message)
        {
            var commit = new CommitData { Message = message };
            foreach (var file in files.Where(x => x.Xml != null)) {
                if (!file.IsDirty)
                    continue;
                // Log file change
                try {
                    var tempXmlCommitted = Path.GetTempFileName();
                    var tempXml = Path.GetTempFileName();
                    file.XmlCommitted.Save(tempXmlCommitted);
                    file.Xml.Save(tempXml);
                    commit.Changes.Add(new FileChangeData
                    {
                        Path = file.Path,
                        Before = File.ReadAllText(tempXmlCommitted),
                        After = File.ReadAllText(tempXml)
                    });
                    Utils.DeleteFile(tempXmlCommitted);
                    Utils.DeleteFile(tempXml);
                } catch (Exception e) {
                    e.Log();
                }
                //file was modified: sync committed copy
                file.XmlCommitted = new XDocument(file.Xml);
                file.Xml = new XDocument(file.XmlCommitted);
            }
            if (commit.Changes.Any())
                Commits.Add(commit);
        }

        private void Rollback()
        {
            foreach (var file in files.Where(x => x.Xml != null))
                file.Xml = new XDocument(file.XmlCommitted);
        }

        public string GetProperty(string propertyName)
        {
            var xProperty = this[Files.Project].Xml
                .Elements(ns + "Project")
                .Elements(ns + "PropertyGroup")
                .Elements()
                .FirstOrDefault(x => x.Name.LocalName == propertyName);
            return xProperty?.Value ?? "";
        }

        public string GetProperty(string itemType, string propertyName)
        {
            var xProperty = this[Files.Project].Xml
                .Elements(ns + "Project")
                .Elements(ns + "ItemDefinitionGroup")
                .Elements(ns + itemType)
                .Elements()
                .FirstOrDefault(x => x.Name.LocalName == propertyName);
            return xProperty?.Value ?? "";
        }

        public IEnumerable<string> GetItems(string itemType)
        {
            return this[Files.Project].Xml
                .Elements(ns + "Project")
                .Elements(ns + "ItemGroup")
                .Elements(ns + itemType)
                .Select(x => (string)x.Attribute("Include"));
        }

        public bool EnableMultiProcessorCompilation()
        {
            var xClCompileDefs = this[Files.Project].Xml
                .Elements(ns + "Project")
                .Elements(ns + "ItemDefinitionGroup")
                .Elements(ns + "ClCompile");
            foreach (var xClCompileDef in xClCompileDefs) {
                if (!xClCompileDef.Elements(ns + "MultiProcessorCompilation").Any())
                    xClCompileDef.Add(new XElement(ns + "MultiProcessorCompilation", "true"));
            }

            Commit("Enabling multi-processor compilation");
            return true;
        }

        /// <summary>
        /// Parser for project configuration conditional expressions of the type:
        ///
        ///     '$(Configuration)|$(Platform)'=='_TOKEN_|_TOKEN_'
        ///
        /// </summary>
        private Parser _ConfigCondition;

        private Parser ConfigCondition
        {
            get
            {
                if (_ConfigCondition != null)
                    return _ConfigCondition;
                var config = new Token("Configuration", CharWord.Repeat());
                var platform = new Token("Platform", CharWord.Repeat());
                var expr = "'$(Configuration)|$(Platform)'=='" & config & "|" & platform & "'";
                try {
                    _ConfigCondition = expr.Render();
                } catch (Exception e) {
                    e.Log();
                }
                return _ConfigCondition;
            }
        }

        /// <summary>
        /// Parser for project format version string:
        ///
        ///     QtVS_vNNN
        ///
        /// </summary>
        private Parser _ProjectFormatVersion;

        private Parser ProjectFormatVersion
        {
            get
            {
                if (_ProjectFormatVersion != null)
                    return _ProjectFormatVersion;
                var expr = "QtVS_v" & new Token("VERSION", Char['0', '9'].Repeat(3))
                {
                    new Rule<int> { Capture(int.Parse) }
                };
                try {
                    _ProjectFormatVersion = expr.Render();
                } catch (Exception e) {
                    e.Log();
                }
                return _ProjectFormatVersion;
            }
        }

        private Version ParseProjectFormatVersion(string text)
        {
            if (string.IsNullOrEmpty(text) || ProjectFormatVersion == null)
                return Version.Unknown;
            try {
                return (Version)ProjectFormatVersion.Parse(text)
                    .GetValues<int>("VERSION")
                    .First();
            } catch {
                return text.StartsWith(KeywordV2, StringComparison.Ordinal)
                    ? Version.V1
                    : Version.Unknown;
            }
        }

        public Version GetProjectFormatVersion()
        {
            var globals = this[Files.Project].Xml
                .Elements(ns + "Project")
                .Elements(ns + "PropertyGroup")
                .FirstOrDefault(x => (string)x.Attribute("Label") == "Globals");
            // Set Qt project format version
            var projKeyword = globals?.Elements(ns + "Keyword")
                .FirstOrDefault(x => x.Value.StartsWith(KeywordLatest)
                    || x.Value.StartsWith(KeywordV2));
            return ParseProjectFormatVersion(projKeyword?.Value);
        }

        /// <summary>
        /// Converts project format version to the latest version:
        ///  * Set latest project version;
        ///  * Add QtSettings property group;
        ///  * Set QtInstall property;
        ///  * Remove hard-coded macros, include paths and libs related to Qt modules.
        ///  * Set QtModules property;
        /// </summary>
        /// <param name="oldVersion"></param>
        /// <returns>true if successful</returns>
        public bool UpdateProjectFormatVersion(Version oldVersion)
        {
            if (ConfigCondition == null)
                return false;

            switch (oldVersion) {
            case Version.Latest:
                return true; // Nothing to do!
            case > Version.Latest:
                return false; // Nothing we can do!
            }

            // Set up V3 format infrastructure
            if (!ConvertToV3())
                return false;

            // Converting non-Qt project, or upgrading from a previous V3 format; nothing more to do
            if (oldVersion == Version.Unknown || oldVersion > Version.V2)
                return true;

            //// Upgrading from v2.0

            // Migrate existing V2 definitions into V3
            //  * Copy / adapt build settings from V2 to V3
            //  * Clean up outdated V2 definitions
            //  * Requires V3 infrastructure already set-up
            return UpgradeFromV2();
        }

        private static bool IsModuleUsed(
            QtModule module,
            IEnumerable<XElement> compiler,
            IEnumerable<XElement> linker,
            IEnumerable<XElement> resourceCompiler)
        {
            // Module .lib is present in linker additional dependencies
            if (linker.Elements(ns + "AdditionalDependencies")
                .SelectMany(x => x.Value.Split(';'))
                .Any(x => string.Equals(Path.GetFileName(Unquote(x)), module.LibRelease, IgnoreCase)
                    || string.Equals(Path.GetFileName(Unquote(x)), module.LibDebug, IgnoreCase))) {
                return true;
            }

            // Module macro is present in the compiler pre-processor definitions
            if (compiler.Elements(ns + "PreprocessorDefinitions")
                .SelectMany(x => x.Value.Split(';'))
                .Any(x => module.Defines.Contains(x))) {
                return true;
            }

            // true if Module macro is present in resource compiler pre-processor definitions
            return resourceCompiler.Elements(ns + "PreprocessorDefinitions")
                .SelectMany(x => x.Value.Split(';'))
                .Any(x => module.Defines.Contains(x));
        }

        private static bool IsPrivateIncludePathUsed(
            QtModule module,
            IEnumerable<XElement> compiler)
        {
            var privateIncludePattern = new Regex(
                $@"^\$\(QTDIR\)[\\\/]include[\\\/]{module.LibraryPrefix}[\\\/]\d+\.\d+\.\d+");

            // true if Module private header path is present in compiler include dirs
            return compiler.Elements(ns + "AdditionalIncludeDirectories")
                .SelectMany(x => x.Value.Split(';'))
                .Any(x => privateIncludePattern.IsMatch(x));
        }

        public bool SetDefaultWindowsSDKVersion(string winSDKVersion)
        {
            var xGlobals = this[Files.Project].Xml
                .Elements(ns + "Project")
                .Elements(ns + "PropertyGroup")
                .FirstOrDefault(x => (string)x.Attribute("Label") == "Globals");
            if (xGlobals == null)
                return false;
            if (xGlobals.Element(ns + "WindowsTargetPlatformVersion") != null)
                return true;
            xGlobals.Add(
                new XElement(ns + "WindowsTargetPlatformVersion", winSDKVersion));

            Commit("Setting default Windows SDK");
            return true;
        }

        private delegate string ItemCommandLineReplacement(string itemName, string cmdLine);

        private bool SetCommandLines(
            MsBuildProjectContainer qtMsBuild,
            IEnumerable<XElement> configurations,
            IEnumerable<XElement> customBuilds,
            string toolExec,
            string itemType,
            IList<ItemCommandLineReplacement> extraReplacements)
        {
            var query = from customBuild in customBuilds
                        let itemName = customBuild.Attribute("Include")?.Value
                        from config in configurations
                        from command in customBuild.Elements(ns + "Command")
                        let excludedFromBuild = customBuild.Element(ns + "ExcludedFromBuild")
                        where command.Attribute("Condition")?.Value
                            == $"'$(Configuration)|$(Platform)'=='{(string)config.Attribute("Include")}'"
                        select new { customBuild, itemName, config, command, excludedFromBuild };

            var projPath = this[Files.Project].Path;
            var error = false;
            using var evaluator = new MSBuildEvaluator(this[Files.Project]);
            foreach (var row in query) {

                var configId = (string)row.config.Attribute("Include");
                if (!row.command.Value.Contains(toolExec)) {
                    Messages.Print($"{projPath}: warning: [{itemType}] converting "
                      + $"\"{row.itemName}\", configuration \"{configId}\": "
                      + $"tool not found: \"{toolExec}\"; applying default options");
                    continue;
                }

                XElement item;
                row.customBuild.Add(item =
                    new XElement(ns + itemType,
                        new XAttribute("Include", row.itemName),
                        new XAttribute("ConfigName", configId),
                        row.excludedFromBuild
                    )
                );

                var configName = (string)row.config.Element(ns + "Configuration");
                var platformName = (string)row.config.Element(ns + "Platform");

                ///////////////////////////////////////////////////////////////////////////////
                // Replace fixed values with VS macros
                //
                //   * Filename, e.g. foo.ui --> %(Filename)%(Extension)
                var commandLine = row.command.Value.Replace(Path.GetFileName(row.itemName),
                    "%(Filename)%(Extension)", IgnoreCase);
                //
                //   * Context specific, e.g. ui_foo.h --> ui_%(FileName).h
                foreach (var replace in extraReplacements)
                    commandLine = replace(row.itemName, commandLine);
                //
                //   * Configuration/platform, e.g. x64\Debug --> $(Platform)\$(Configuration)
                //   * ignore any word other than the expected configuration, e.g. lrelease.exe
                commandLine = Regex.Replace(commandLine, @"\b" + configName + @"\b",
                        "$(Configuration)", RegexOptions.IgnoreCase)
                    .Replace(platformName, "$(Platform)", IgnoreCase);

                evaluator.Properties.Clear();
                foreach (var configProp in row.config.Elements())
                    evaluator.Properties.Add(configProp.Name.LocalName, (string)configProp);
                if (qtMsBuild.SetCommandLine(itemType, item, commandLine, evaluator))
                    continue;

                var lineNumber = 1;
                if (row.command is IXmlLineInfo errorLine && errorLine.HasLineInfo())
                    lineNumber = errorLine.LineNumber;

                Messages.Print($"{projPath}({lineNumber}): error: [{itemType}] "
                  + $"converting \"{row.itemName}\", configuration \"{configId}\": "
                  + "failed to convert custom build command");

                item.Remove();
                error = true;
            }

            return !error;
        }

        private List<XElement> GetCustomBuilds(string toolExecName)
        {
            return this[Files.Project].Xml
                .Elements(ns + "Project")
                .Elements(ns + "ItemGroup")
                .Elements(ns + "CustomBuild")
                .Where(x => x.Elements(ns + "Command")
                    .Any(y => y.Value.Contains(toolExecName)))
                .ToList();
        }

        private List<XElement> GetPostBuildEvents(string toolExecName)
        {
            return this[Files.Project].Xml
                .Elements(ns + "Project")
                .Elements(ns + "ItemDefinitionGroup")
                .Elements(ns + "PostBuildEvent")
                .Where(x => x.Elements(ns + "Command")
                    .Any(y => y.Value.Contains(toolExecName)))
                .ToList();
        }

        private void FinalizeProjectChanges(List<XElement> customBuilds, string itemTypeName)
        {
            customBuilds
                .Elements().Where(
                    elem => elem.Name.LocalName != itemTypeName)
                .ToList().ForEach(oldElem => oldElem.Remove());

            customBuilds.Elements(ns + itemTypeName).ToList().ForEach(item =>
            {
                item.Elements().ToList().ForEach(prop =>
                {
                    var configName = prop.Parent?.Attribute("ConfigName")?.Value;
                    prop.SetAttributeValue("Condition",
                        $"'$(Configuration)|$(Platform)'=='{configName}'");
                    prop.Remove();
                    item.Parent?.Add(prop);
                });
                item.Remove();
            });

            customBuilds.ForEach(customBuild =>
            {
                var filterCustomBuild = (this[Files.Filters]?.Xml
                        ?.Elements(ns + "Project")
                        .Elements(ns + "ItemGroup")
                        .Elements(ns + "CustomBuild") ?? Array.Empty<XElement>())
                    .FirstOrDefault(
                        filterItem => filterItem.Attribute("Include")?.Value
                         == customBuild.Attribute("Include")?.Value);
                if (filterCustomBuild != null)
                    filterCustomBuild.Name = ns + itemTypeName;
                customBuild.Name = ns + itemTypeName;
            });
        }

        private static string AddGeneratedFilesPath(string includePathList)
        {
            var includes = new HashSet<string> {
                GetDirectory("MocDir"),
                GetDirectory("UicDir"),
                GetDirectory("RccDir")
            };
            foreach (var includePath in includePathList.Split(';'))
                includes.Add(includePath);
            return string.Join<string>(";", includes);
        }

        private static string GetDirectory(string type)
        {
            try {
                if (Registry.CurrentUser.OpenSubKey(Resources.SettingsRegistryPath) is { } key) {
                    if (key.GetValue(type, null) is string path)
                        return NormalizeRelativeFilePath(path);
                }
            } catch (Exception exception) {
                exception.Log();
            }
            return type == "MocDir" ? "GeneratedFiles\\$(ConfigurationName)" : "GeneratedFiles";
        }

        private string CustomBuildMocInput(XElement cbt)
        {
            var commandLine = (string)cbt.Element(ns + "Command");
            Dictionary<QtMoc.Property, string> properties;
            using (var evaluator = new MSBuildEvaluator(this[Files.Project])) {
                if (!MsBuildProjectContainer.QtMocInstance.ParseCommandLine(
                    commandLine, evaluator, out properties)) {
                    return (string)cbt.Attribute("Include");
                }
            }
            if (!properties.TryGetValue(QtMoc.Property.InputFile, out var outputFile))
                return (string)cbt.Attribute("Include");
            return outputFile;
        }

        private static bool RemoveGeneratedFiles(
            string projDir,
            IEnumerable<CustomBuildEval> cbEvals,
            string configName,
            string itemName,
            IReadOnlyDictionary<string, List<XElement>> projItemsByPath,
            IReadOnlyDictionary<string, List<XElement>> filterItemsByPath)
        {
            //remove items with generated files
            var cbEval = cbEvals
                .FirstOrDefault(x => x.ProjectConfig == configName && x.Identity == itemName);
            if (cbEval == null)
                return false;

            var hasGeneratedFiles = false;
            var outputFiles = cbEval.Outputs
                .Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
                .Select(x => CanonicalPath(
                    Path.IsPathRooted(x) ? x : Path.Combine(projDir, x)));
            var outputItems = new List<XElement>();
            foreach (var outputFile in outputFiles) {
                if (projItemsByPath.TryGetValue(outputFile, out var mocOutput)) {
                    outputItems.AddRange(mocOutput);
                    hasGeneratedFiles |= hasGeneratedFiles || mocOutput
                        .Any(x => !x.Elements(ns + "ExcludedFromBuild")
                            .Any(y => (string)y.Attribute("Condition") == $"'$(Configuration)|$(Platform)'=='{configName}'"
                             && y.Value == "true"));
                }
                if (filterItemsByPath.TryGetValue(outputFile, out mocOutput))
                    outputItems.AddRange(mocOutput);
            }
            foreach (var item in outputItems.Where(x => x.Parent != null))
                item.Remove();
            return hasGeneratedFiles;
        }

        public bool ConvertCustomBuildToQtMsBuild()
        {
            var cbEvals = EvaluateCustomBuild();

            var qtMsBuild = new MsBuildProjectContainer(new MsBuildConverterProvider());
            qtMsBuild.BeginSetItemProperties();

            var projDir = Path.GetDirectoryName(this[Files.Project].Path);

            var configurations = this[Files.Project].Xml
                .Elements(ns + "Project")
                .Elements(ns + "ItemGroup")
                .Elements(ns + "ProjectConfiguration")
                .ToList();

            var projItemsByPath = this[Files.Project].Xml
                .Elements(ns + "Project")
                .Elements(ns + "ItemGroup")
                .Elements()
                .Where(x => ((string)x.Attribute("Include"))
                    .IndexOfAny(Path.GetInvalidPathChars()) == -1)
                .GroupBy(x => CanonicalPath(
                    Path.Combine(projDir ?? "", (string)x.Attribute("Include"))), CaseIgnorer)
                .ToDictionary(x => x.Key, x => new List<XElement>(x));

            var filterItemsByPath = this[Files.Filters]?.Xml != null
                ? this[Files.Filters].Xml
                    .Elements(ns + "Project")
                    .Elements(ns + "ItemGroup")
                    .Elements()
                    .Where(x => ((string)x.Attribute("Include"))
                        .IndexOfAny(Path.GetInvalidPathChars()) == -1)
                    .GroupBy(x => CanonicalPath(
                        Path.Combine(projDir ?? "", (string)x.Attribute("Include"))), CaseIgnorer)
                    .ToDictionary(x => x.Key, x => new List<XElement>(x))
                : new Dictionary<string, List<XElement>>();

            var cppIncludePaths = this[Files.Project].Xml
                .Elements(ns + "Project")
                .Elements(ns + "ItemDefinitionGroup")
                .Elements(ns + "ClCompile")
                .Elements(ns + "AdditionalIncludeDirectories");

            //add generated files path to C++ additional include dirs
            foreach (var cppIncludePath in cppIncludePaths)
                cppIncludePath.Value = AddGeneratedFilesPath((string)cppIncludePath);

            // replace each set of .moc.cbt custom build steps
            // with a single .cpp custom build step
            var mocCbtCustomBuilds = GetCustomBuilds("moc_predefs")
                .Where(x =>
                ((string)x.Attribute("Include")).EndsWith(".cbt", IgnoreCase)
                || ((string)x.Attribute("Include")).EndsWith(".moc", IgnoreCase))
                .GroupBy(CustomBuildMocInput);

            var cbtToRemove = new List<XElement>();
            foreach (var cbtGroup in mocCbtCustomBuilds) {

                //create new CustomBuild item for .cpp
                var newCbt = new XElement(ns + "CustomBuild",
                    new XAttribute("Include", cbtGroup.Key),
                    new XElement(ns + "FileType", "Document"));

                //add properties from .moc.cbt items
                var cbtPropertyNames = new List<string> {
                    "AdditionalInputs",
                    "Command",
                    "Message",
                    "Outputs"
                };
                foreach (var cbt in cbtGroup) {
                    var enabledProperties = cbt.Elements().Where(x =>
                        x.Parent != null
                        && cbtPropertyNames.Contains(x.Name.LocalName)
                        && x.Parent.Elements(ns + "ExcludedFromBuild")
                            .All(y => (string)x.Attribute("Condition") != (string)y.Attribute("Condition")));
                    foreach (var property in enabledProperties) {
                        property.Value = property.Value.Replace("debug", "$(IntDir)")
                            .Replace("release", "$(IntDir)");
                        newCbt.Add(new XElement(property));
                    }
                    cbtToRemove.Add(cbt);
                }
                cbtGroup.First().AddBeforeSelf(newCbt);

                //remove ClCompile item (cannot have duplicate items)
                var cppMocItems = this[Files.Project].Xml
                    .Elements(ns + "Project")
                    .Elements(ns + "ItemGroup")
                    .Elements(ns + "ClCompile")
                    .Where(x =>
                        string.Equals(cbtGroup.Key, (string)x.Attribute("Include"), IgnoreCase));
                foreach (var cppMocItem in cppMocItems)
                    cppMocItem.Remove();

                //change type of item in filter
                cppMocItems = this[Files.Filters]?.Xml
                    ?.Elements(ns + "Project")
                    .Elements(ns + "ItemGroup")
                    .Elements(ns + "ClCompile")
                    .Where(x =>
                        string.Equals(cbtGroup.Key, (string)x.Attribute("Include"), IgnoreCase));
                foreach (var cppMocItem in cppMocItems)
                    cppMocItem.Name = ns + "CustomBuild";
            }

            //remove .moc.cbt CustomBuild items
            cbtToRemove.ForEach(x => x.Remove());

            //convert moc custom build steps
            var mocCustomBuilds = GetCustomBuilds(QtMoc.ToolExecName);
            if (!SetCommandLines(qtMsBuild, configurations, mocCustomBuilds,
                QtMoc.ToolExecName, QtMoc.ItemTypeName,
                new ItemCommandLineReplacement[]
                {
                    (item, cmdLine) => cmdLine.Replace(
                            $@"\moc_{Path.GetFileNameWithoutExtension(item)}.cpp",
                        @"\moc_%(Filename).cpp", IgnoreCase)
                    .Replace($" -o moc_{Path.GetFileNameWithoutExtension(item)}.cpp",
                        @" -o $(ProjectDir)\moc_%(Filename).cpp", IgnoreCase),

                    (item, cmdLine) => cmdLine.Replace(
                            $@"\{Path.GetFileNameWithoutExtension(item)}.moc",
                        @"\%(Filename).moc", IgnoreCase)
                    .Replace($" -o {Path.GetFileNameWithoutExtension(item)}.moc",
                        @" -o $(ProjectDir)\%(Filename).moc", IgnoreCase)
                })) {
                Rollback();
                return false;
            }
            var mocDisableDynamicSource = new List<XElement>();
            foreach (var qtMoc in mocCustomBuilds.Elements(ns + QtMoc.ItemTypeName)) {
                var itemName = (string)qtMoc.Attribute("Include");
                var configName = (string)qtMoc.Attribute("ConfigName");

                //remove items with generated files
                var hasGeneratedFiles = RemoveGeneratedFiles(
                    projDir, cbEvals, configName, itemName,
                    projItemsByPath, filterItemsByPath);

                //set properties
                qtMsBuild.SetItemProperty(qtMoc,
                    QtMoc.Property.ExecutionDescription, "Moc'ing %(Identity)...");
                qtMsBuild.SetItemProperty(qtMoc,
                    QtMoc.Property.InputFile, "%(FullPath)");
                if (!IsSourceFile(itemName)) {
                    qtMsBuild.SetItemProperty(qtMoc,
                        QtMoc.Property.DynamicSource, "output");
                    if (!hasGeneratedFiles)
                        mocDisableDynamicSource.Add(qtMoc);
                } else {
                    qtMsBuild.SetItemProperty(qtMoc,
                        QtMoc.Property.DynamicSource, "input");
                }
                var includePath = qtMsBuild.GetPropertyChangedValue(
                    QtMoc.Property.IncludePath, itemName, configName);
                if (!string.IsNullOrEmpty(includePath)) {
                    qtMsBuild.SetItemProperty(qtMoc,
                        QtMoc.Property.IncludePath, AddGeneratedFilesPath(includePath));
                }
            }

            //convert rcc custom build steps
            var rccCustomBuilds = GetCustomBuilds(QtRcc.ToolExecName);
            if (!SetCommandLines(qtMsBuild, configurations, rccCustomBuilds,
                QtRcc.ToolExecName, QtRcc.ItemTypeName,
                new ItemCommandLineReplacement[]
                {
                    (item, cmdLine) => cmdLine.Replace(
                        $@"\qrc_{Path.GetFileNameWithoutExtension(item)}.cpp",
                        @"\qrc_%(Filename).cpp", IgnoreCase)
                    .Replace(
                        $" -o qrc_{Path.GetFileNameWithoutExtension(item)}.cpp",
                        @" -o $(ProjectDir)\qrc_%(Filename).cpp", IgnoreCase)
                })) {
                Rollback();
                return false;
            }
            foreach (var qtRcc in rccCustomBuilds.Elements(ns + QtRcc.ItemTypeName)) {
                var itemName = (string)qtRcc.Attribute("Include");
                var configName = (string)qtRcc.Attribute("ConfigName");

                //remove items with generated files
                RemoveGeneratedFiles(projDir, cbEvals, configName, itemName,
                    projItemsByPath, filterItemsByPath);

                //set properties
                qtMsBuild.SetItemProperty(qtRcc,
                    QtRcc.Property.ExecutionDescription, "Rcc'ing %(Identity)...");
                qtMsBuild.SetItemProperty(qtRcc,
                    QtRcc.Property.InputFile, "%(FullPath)");
            }

            //convert repc custom build steps
            var repcCustomBuilds = GetCustomBuilds(QtRepc.ToolExecName);
            if (!SetCommandLines(qtMsBuild, configurations, repcCustomBuilds,
                QtRepc.ToolExecName, QtRepc.ItemTypeName,
                new ItemCommandLineReplacement[] { })) {
                Rollback();
                return false;
            }
            foreach (var qtRepc in repcCustomBuilds.Elements(ns + QtRepc.ItemTypeName)) {
                var itemName = (string)qtRepc.Attribute("Include");
                var configName = (string)qtRepc.Attribute("ConfigName");

                //remove items with generated files
                RemoveGeneratedFiles(projDir, cbEvals, configName, itemName,
                    projItemsByPath, filterItemsByPath);

                //set properties
                qtMsBuild.SetItemProperty(qtRepc,
                    QtRepc.Property.ExecutionDescription, "Repc'ing %(Identity)...");
                qtMsBuild.SetItemProperty(qtRepc,
                    QtRepc.Property.InputFile, "%(FullPath)");
            }

            //convert uic custom build steps
            var uicCustomBuilds = GetCustomBuilds(QtUic.ToolExecName);
            if (!SetCommandLines(qtMsBuild, configurations, uicCustomBuilds,
                QtUic.ToolExecName, QtUic.ItemTypeName,
                new ItemCommandLineReplacement[]
                {
                    (item, cmdLine) => cmdLine.Replace(
                        $@"\ui_{Path.GetFileNameWithoutExtension(item)}.h",
                        @"\ui_%(Filename).h", IgnoreCase)
                    .Replace(
                        $" -o ui_{Path.GetFileNameWithoutExtension(item)}.h",
                        @" -o $(ProjectDir)\ui_%(Filename).h", IgnoreCase)
                })) {
                Rollback();
                return false;
            }
            foreach (var qtUic in uicCustomBuilds.Elements(ns + QtUic.ItemTypeName)) {
                var itemName = (string)qtUic.Attribute("Include");
                var configName = (string)qtUic.Attribute("ConfigName");

                //remove items with generated files
                RemoveGeneratedFiles(projDir, cbEvals, configName, itemName,
                    projItemsByPath, filterItemsByPath);

                //set properties
                qtMsBuild.SetItemProperty(qtUic,
                    QtUic.Property.ExecutionDescription, "Uic'ing %(Identity)...");
                qtMsBuild.SetItemProperty(qtUic,
                    QtUic.Property.InputFile, "%(FullPath)");
            }

            // convert qm custom build steps
            var qmCustomBuilds = GetCustomBuilds(QtLRelease.ToolExecName);
            if (!SetCommandLines(qtMsBuild, configurations, qmCustomBuilds,
                QtLRelease.ToolExecName, QtLRelease.ItemTypeName,
                new ItemCommandLineReplacement[]
                {
                    (item, cmdLine) => cmdLine.Replace(
                        $@"{Path.GetFileNameWithoutExtension(item)}.ts",
                        @"%(Filename).ts", IgnoreCase)
                    .Replace(
                        $"{Path.GetFileNameWithoutExtension(item)}.qm",
                        @"%(Filename).qm", IgnoreCase)
                })) {
                Rollback();
                return false;
            }
            foreach (var qtQm in qmCustomBuilds.Elements(ns + QtLRelease.ItemTypeName)) {
                var itemName = qtQm.Attribute("Include").ToString();
                var configName = qtQm.Attribute("ConfigName").ToString();

                // remove items with generated files
                RemoveGeneratedFiles(projDir, cbEvals, configName, itemName, projItemsByPath,
                    filterItemsByPath);

                // set properties
                qtMsBuild.SetItemProperty(qtQm, QtLRelease.Property.ReleaseDescription,
                    "lrelease %(Identity)");

                qtMsBuild.SetItemProperty(qtQm, QtLRelease.Property.BuildAction, "lrelease");
                qtMsBuild.SetItemProperty(qtQm, QtLRelease.Property.InputFile, "%(FullPath)");
            }

            // convert idc custom build steps
            var idcPostBuilds = GetPostBuildEvents("idc.exe");
            foreach (var idcPostBuild in idcPostBuilds) {
                this[Files.Project].Xml.Root.Add(new XElement(ns + "PropertyGroup",
                    new XAttribute("Label", "QtIDC"),
                    idcPostBuild.Parent.Attribute("Condition"),
                    new XElement(ns + "QtIDC", new XText("true")),
                    new XElement(ns + "QtIDCVersion", new XText("1.0"))));
                idcPostBuild.Remove();
            }

            qtMsBuild.EndSetItemProperties();

            //disable dynamic C++ source for moc headers without generated files
            //(needed for the case of #include "moc_foo.cpp" in source file)
            foreach (var qtMoc in mocDisableDynamicSource) {
                qtMsBuild.SetItemProperty(qtMoc,
                    QtMoc.Property.DynamicSource, "false");
            }

            FinalizeProjectChanges(mocCustomBuilds, QtMoc.ItemTypeName);
            FinalizeProjectChanges(rccCustomBuilds, QtRcc.ItemTypeName);
            FinalizeProjectChanges(repcCustomBuilds, QtRepc.ItemTypeName);
            FinalizeProjectChanges(uicCustomBuilds, QtUic.ItemTypeName);
            FinalizeProjectChanges(qmCustomBuilds, QtLRelease.ItemTypeName);

            Commit("Converting custom build steps to Qt/MSBuild items");
            return true;
        }

        private static bool TryReplaceTextInPlace(ref string text, Regex findWhat, string newText)
        {
            var match = findWhat.Match(text);
            if (!match.Success)
                return false;
            do {
                text = text.Remove(match.Index, match.Length).Insert(match.Index, newText);
                match = findWhat.Match(text, match.Index);
            } while (match.Success);

            return true;
        }

        private static void ReplaceText(XElement xElem, Regex findWhat, string newText)
        {
            var elemValue = (string)xElem;
            if (!string.IsNullOrEmpty(elemValue)
                && TryReplaceTextInPlace(ref elemValue, findWhat, newText)) {
                xElem.Value = elemValue;
            }
        }

        private static void ReplaceText(XAttribute xAttr, Regex findWhat, string newText)
        {
            var attrValue = (string)xAttr;
            if (!string.IsNullOrEmpty(attrValue)
                && TryReplaceTextInPlace(ref attrValue, findWhat, newText)) {
                xAttr.Value = attrValue;
            }
        }

        /// <summary>
        /// All path separators
        /// </summary>
        private static readonly char[] slashChars = {
            Path.DirectorySeparatorChar,
            Path.AltDirectorySeparatorChar
        };

        /// <summary>
        /// Pattern that matches one path separator char
        /// </summary>
        private static readonly RegExpr slash = CharSet[slashChars];

        /// <summary>
        /// Gets a RegExpr that matches a given path, regardless
        /// of case and varying directory separators
        /// </summary>
        private static RegExpr GetPathPattern(string findWhatPath)
        {
            return
                // Make pattern case-insensitive
                CaseInsensitive &
                // Split path string by directory separators
                findWhatPath.Split(slashChars, StringSplitOptions.RemoveEmptyEntries)
                // Convert path parts to RegExpr (escapes regex special chars)
                .Select(dirName => (RegExpr)dirName)
                // Join all parts, separated by path separator pattern
                .Aggregate((path, dirName) => path & slash & dirName);
        }

        public void ReplacePath(string oldPath, string newPath)
        {
            var srcUri = new Uri(Path.GetFullPath(oldPath));
            var projUri = new Uri(this[Files.Project].Path);

            var absolutePath = GetPathPattern(srcUri.AbsolutePath);
            var relativePath = GetPathPattern(projUri.MakeRelativeUri(srcUri).OriginalString);

            var findWhat = (absolutePath | relativePath).Render().Regex;

            foreach (var xElem in this[Files.Project].Xml.Descendants()) {
                if (!xElem.HasElements)
                    ReplaceText(xElem, findWhat, newPath);
                foreach (var xAttr in xElem.Attributes())
                    ReplaceText(xAttr, findWhat, newPath);
            }
            Commit($"Replacing paths with \"{newPath}\"");
        }

        private class MSBuildEvaluator : IVsMacroExpander, IDisposable
        {
            private readonly MsBuildXmlFile projFile;
            private string tempProjFilePath;
            private XElement evaluateTarget;
            private XElement evaluateProperty;
            private ProjectRootElement projRoot;
            private readonly Dictionary<string, string> expansionCache;

            public Dictionary<string, string> Properties
            {
                get;
            }

            public MSBuildEvaluator(MsBuildXmlFile projFile)
            {
                this.projFile = projFile;
                tempProjFilePath = string.Empty;
                evaluateTarget = evaluateProperty = null;
                expansionCache = new Dictionary<string, string>();
                Properties = new Dictionary<string, string>();
            }

            public void Dispose()
            {
                if (evaluateTarget == null)
                    return;
                evaluateTarget.Remove();
                Utils.DeleteFile(tempProjFilePath);
            }

            private string ExpansionCacheKey(string stringToExpand)
            {
                var key = new StringBuilder();
                foreach (var property in Properties)
                    key.AppendFormat("{0};{1};", property.Key, property.Value);
                key.Append(stringToExpand);
                return key.ToString();
            }

            private bool TryExpansionCache(string stringToExpand, out string expandedString)
            {
                return expansionCache.TryGetValue(
                    ExpansionCacheKey(stringToExpand), out expandedString);
            }

            private void AddToExpansionCache(string stringToExpand, string expandedString)
            {
                expansionCache[ExpansionCacheKey(stringToExpand)] = expandedString;
            }

            public string ExpandString(string stringToExpand)
            {
                if (TryExpansionCache(stringToExpand, out var expandedString))
                    return expandedString;

                if (evaluateTarget == null) {
                    projFile.XmlCommitted.Root?.Add(evaluateTarget = new XElement(ns + "Target",
                        new XAttribute("Name", "MSBuildEvaluatorTarget"),
                        new XElement(ns + "PropertyGroup",
                            evaluateProperty = new XElement(ns + "MSBuildEvaluatorProperty"))));
                }

                if (stringToExpand != (string)evaluateProperty) {
                    evaluateProperty.SetValue(stringToExpand);
                    if (!string.IsNullOrEmpty(tempProjFilePath))
                        Utils.DeleteFile(tempProjFilePath);
                    tempProjFilePath = Path.Combine(
                        Path.GetDirectoryName(projFile.Path) ?? "",
                        Path.GetRandomFileName());
                    Utils.DeleteFile(tempProjFilePath);
                    projFile.XmlCommitted.Save(tempProjFilePath);
                    projRoot = ProjectRootElement.Open(tempProjFilePath);
                }

                var projInst = new ProjectInstance(projRoot, Properties,
                    null, new ProjectCollection());
                var buildRequest = new BuildRequestData(
                    projInst, new[] { "MSBuildEvaluatorTarget" },
                    null, BuildRequestDataFlags.ProvideProjectStateAfterBuild);
                var buildResult = BuildManager.DefaultBuildManager.Build(
                    new BuildParameters(), buildRequest);
                expandedString = buildResult.ProjectStateAfterBuild
                    .GetPropertyValue("MSBuildEvaluatorProperty");

                AddToExpansionCache(stringToExpand, expandedString);
                return expandedString;
            }
        }

        private class CustomBuildEval
        {
            public string ProjectConfig { get; set; }
            public string Identity { get; set; }
            public string AdditionalInputs { get; set; }
            public string Outputs { get; set; }
            public string Message { get; set; }
            public string Command { get; set; }
        }

        private List<CustomBuildEval> EvaluateCustomBuild()
        {
            var eval = new List<CustomBuildEval>();

            var pattern = new Regex(@"{([^}]+)}{([^}]+)}{([^}]+)}{([^}]+)}{([^}]+)}");

            var projConfigs = this[Files.Project].Xml
                .Elements(ns + "Project")
                .Elements(ns + "ItemGroup")
                .Elements(ns + "ProjectConfiguration");

            using var evaluator = new MSBuildEvaluator(this[Files.Project]);
            foreach (var projConfig in projConfigs) {

                evaluator.Properties.Clear();
                foreach (var configProp in projConfig.Elements())
                    evaluator.Properties.Add(configProp.Name.LocalName, (string)configProp);

                var expandedValue = evaluator.ExpandString(
                    "@(CustomBuild->'" +
                    "{%(Identity)}" +
                    "{%(AdditionalInputs)}" +
                    "{%(Outputs)}" +
                    "{%(Message)}" +
                    "{%(Command)}')");

                foreach (Match cbEval in pattern.Matches(expandedValue)) {
                    eval.Add(new CustomBuildEval
                    {
                        ProjectConfig = (string)projConfig.Attribute("Include"),
                        Identity = cbEval.Groups[1].Value,
                        AdditionalInputs = cbEval.Groups[2].Value,
                        Outputs = cbEval.Groups[3].Value,
                        Message = cbEval.Groups[4].Value,
                        Command = cbEval.Groups[5].Value
                    });
                }
            }

            return eval;
        }

        public void BuildTarget(string target)
        {
            if (this[Files.Project].IsDirty)
                return;

            var configurations = this[Files.Project].Xml
                .Elements(ns + "Project")
                .Elements(ns + "ItemGroup")
                .Elements(ns + "ProjectConfiguration");

            using var buildManager = new BuildManager();
            foreach (var config in configurations) {
                var configProps = config.Elements()
                    .ToDictionary(x => x.Name.LocalName, x => x.Value);

                var projectInstance = new ProjectInstance(this[Files.Project].Path,
                    new Dictionary<string, string>(configProps)
                        { { "QtVSToolsBuild", "true" } },
                    null, new ProjectCollection());

                var buildRequest = new BuildRequestData(projectInstance,
                    targetsToBuild: new[] { target },
                    hostServices: null,
                    flags: BuildRequestDataFlags.ProvideProjectStateAfterBuild);

                var result = buildManager.Build(new BuildParameters(), buildRequest);
                if (result.OverallResult != BuildResultCode.Success)
                    return;
            }
        }

        private static readonly Regex ConditionParser =
            new(@"\'\$\(Configuration[^\)]*\)\|\$\(Platform[^\)]*\)\'\=\=\'([^\']+)\'");

        private class MsBuildConverterProvider : IPropertyStorageProvider
        {
            public string GetProperty(object propertyStorage, string itemType, string propertyName)
            {
                if (propertyStorage is not XElement xmlPropertyStorage)
                    return "";

                var item = xmlPropertyStorage;
                if (xmlPropertyStorage.Name.LocalName != "ItemDefinitionGroup")
                    return item.Element(ns + propertyName)?.Value;

                item = xmlPropertyStorage.Element(ns + itemType);
                return item == null ? "" : item.Element(ns + propertyName)?.Value;
            }

            public bool SetProperty(
                object propertyStorage,
                string itemType,
                string propertyName,
                string propertyValue)
            {
                if (propertyStorage is not XElement xmlPropertyStorage)
                    return false;

                var item = xmlPropertyStorage;
                if (xmlPropertyStorage.Name.LocalName == "ItemDefinitionGroup") {
                    item = xmlPropertyStorage.Element(ns + itemType);
                    if (item == null)
                        xmlPropertyStorage.Add(item = new XElement(ns + itemType));
                }

                var prop = item.Element(ns + propertyName);
                if (prop != null)
                    prop.Value = propertyValue;
                else
                    item.Add(new XElement(ns + propertyName, propertyValue));
                return true;
            }

            public bool DeleteProperty(
                object propertyStorage,
                string itemType,
                string propertyName)
            {
                if (propertyStorage is not XElement xmlPropertyStorage)
                    return false;

                var item = xmlPropertyStorage;
                if (xmlPropertyStorage.Name.LocalName == "ItemDefinitionGroup") {
                    item = xmlPropertyStorage.Element(ns + itemType);
                    if (item == null)
                        return true;
                }

                item.Element(ns + propertyName)?.Remove();
                return true;
            }

            public string GetConfigName(object propertyStorage)
            {
                if (propertyStorage is not XElement xmlPropertyStorage)
                    return "";

                if (xmlPropertyStorage.Name.LocalName != "ItemDefinitionGroup")
                    return xmlPropertyStorage.Attribute("ConfigName")?.Value;

                var configName = ConditionParser
                    .Match(xmlPropertyStorage.Attribute("Condition")?.Value ?? "");
                if (!configName.Success || configName.Groups.Count <= 1)
                    return "";
                return configName.Groups[1].Value;
            }

            public string GetItemType(object propertyStorage)
            {
                if (propertyStorage is not XElement xmlPropertyStorage)
                    return "";

                if (xmlPropertyStorage.Name.LocalName == "ItemDefinitionGroup")
                    return "";
                return xmlPropertyStorage.Name.LocalName;
            }

            public string GetItemName(object propertyStorage)
            {
                if (propertyStorage is not XElement xmlPropertyStorage)
                    return "";
                if (xmlPropertyStorage.Name.LocalName == "ItemDefinitionGroup")
                    return "";
                return xmlPropertyStorage.Attribute("Include")?.Value;
            }

            public object GetParentProject(object propertyStorage)
            {
                if (propertyStorage is XElement xmlPropertyStorage)
                    return xmlPropertyStorage.Document?.Root;
                return "";
            }

            public object GetProjectConfiguration(object project, string configName)
            {
                if (project is not XElement xmlProject)
                    return null;
                return xmlProject.Elements(ns + "ItemDefinitionGroup")
                    .FirstOrDefault(config =>
                        config.Attribute("Condition")?.Value.Contains(configName) ?? false);
            }

            public IEnumerable<object> GetItems(
                object project,
                string itemType,
                string configName = "")
            {
                if (project is not XElement xmlProject)
                    return new List<object>();
                return xmlProject.Elements(ns + "ItemGroup")
                    .Elements(ns + "CustomBuild")
                    .Elements(ns + itemType)
                    .Where(item =>
                        configName == "" || item.Attribute("ConfigName")?.Value == configName)
                    .GroupBy(item => item.Attribute("Include")?.Value)
                    .Select(item => item.First());
            }
        }
    }
}