1 /****************************************************************************
2 **
3 ** Copyright (C) 2016 The Qt Company Ltd.
4 ** Contact: https://www.qt.io/licensing/
5 **
6 ** This file is part of the qmake application of the Qt Toolkit.
7 **
8 ** $QT_BEGIN_LICENSE:GPL-EXCEPT$
9 ** Commercial License Usage
10 ** Licensees holding valid commercial Qt licenses may use this file in
11 ** accordance with the commercial license agreement provided with the
12 ** Software or, alternatively, in accordance with the terms contained in
13 ** a written agreement between you and The Qt Company. For licensing terms
14 ** and conditions see https://www.qt.io/terms-conditions. For further
15 ** information use the contact form at https://www.qt.io/contact-us.
16 **
17 ** GNU General Public License Usage
18 ** Alternatively, this file may be used under the terms of the GNU
19 ** General Public License version 3 as published by the Free Software
20 ** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
21 ** included in the packaging of this file. Please review the following
22 ** information to ensure the GNU General Public License requirements will
23 ** be met: https://www.gnu.org/licenses/gpl-3.0.html.
24 **
25 ** $QT_END_LICENSE$
26 **
27 ****************************************************************************/
28 
29 #include "msvc_vcproj.h"
30 #include "option.h"
31 #include "xmloutput.h"
32 
33 #include <ioutils.h>
34 
35 #include <qdir.h>
36 #include <qdiriterator.h>
37 #include <qcryptographichash.h>
38 #include <qhash.h>
39 #include <quuid.h>
40 
41 #include <stdlib.h>
42 
43 //#define DEBUG_SOLUTION_GEN
44 
45 using namespace QMakeInternal;
46 
47 QT_BEGIN_NAMESPACE
48 // Filter GUIDs (Do NOT change these!) ------------------------------
49 const char _GUIDSourceFiles[]          = "{4FC737F1-C7A5-4376-A066-2A32D752A2FF}";
50 const char _GUIDHeaderFiles[]          = "{93995380-89BD-4b04-88EB-625FBE52EBFB}";
51 const char _GUIDGeneratedFiles[]       = "{71ED8ED8-ACB9-4CE9-BBE1-E00B30144E11}";
52 const char _GUIDResourceFiles[]        = "{D9D6E242-F8AF-46E4-B9FD-80ECBC20BA3E}";
53 const char _GUIDLexYaccFiles[]         = "{E12AE0D2-192F-4d59-BD23-7D3FA58D3183}";
54 const char _GUIDTranslationFiles[]     = "{639EADAA-A684-42e4-A9AD-28FC9BCB8F7C}";
55 const char _GUIDFormFiles[]            = "{99349809-55BA-4b9d-BF79-8FDBB0286EB3}";
56 const char _GUIDExtraCompilerFiles[]   = "{E0D8C965-CC5F-43d7-AD63-FAEF0BBC0F85}";
57 const char _GUIDDeploymentFiles[]      = "{D9D6E243-F8AF-46E4-B9FD-80ECBC20BA3E}";
58 const char _GUIDDistributionFiles[]    = "{B83CAF91-C7BF-462F-B76C-EA11631F866C}";
59 
60 // Flatfile Tags ----------------------------------------------------
61 const char _slnHeader70[]       = "Microsoft Visual Studio Solution File, Format Version 7.00";
62 const char _slnHeader71[]       = "Microsoft Visual Studio Solution File, Format Version 8.00";
63 const char _slnHeader80[]       = "Microsoft Visual Studio Solution File, Format Version 9.00"
64                                   "\n# Visual Studio 2005";
65 const char _slnHeader90[]       = "Microsoft Visual Studio Solution File, Format Version 10.00"
66                                   "\n# Visual Studio 2008";
67 const char _slnHeader100[]      = "Microsoft Visual Studio Solution File, Format Version 11.00"
68                                   "\n# Visual Studio 2010";
69 const char _slnHeader110[]      = "Microsoft Visual Studio Solution File, Format Version 12.00"
70                                   "\n# Visual Studio 2012";
71 const char _slnHeader120[]      = "Microsoft Visual Studio Solution File, Format Version 12.00"
72                                   "\n# Visual Studio 2013";
73 const char _slnHeader140[]      = "Microsoft Visual Studio Solution File, Format Version 12.00"
74                                   "\n# Visual Studio 2015";
75 const char _slnHeader141[]      = "Microsoft Visual Studio Solution File, Format Version 12.00"
76                                   "\n# Visual Studio 15";
77 const char _slnHeader142[]      = "Microsoft Visual Studio Solution File, Format Version 12.00"
78                                   "\n# Visual Studio Version 16";
79                                   // The following UUID _may_ change for later servicepacks...
80                                   // If so we need to search through the registry at
81                                   // HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\7.0\Projects
82                                   // to find the subkey that contains a "PossibleProjectExtension"
83                                   // containing "vcproj"...
84                                   // Use the hardcoded value for now so projects generated on other
85                                   // platforms are actually usable.
86 const char _slnMSVCvcprojGUID[] = "{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}";
87 const char _slnProjectBeg[]     = "\nProject(\"";
88 const char _slnProjectMid[]     = "\") = ";
89 const char _slnProjectEnd[]     = "\nEndProject";
90 const char _slnGlobalBeg[]      = "\nGlobal";
91 const char _slnGlobalEnd[]      = "\nEndGlobal";
92 const char _slnSolutionConf[]   = "\n\tGlobalSection(SolutionConfigurationPlatforms) = preSolution"
93                                   "\n\t\tDebug|Win32 = Debug|Win32"
94                                   "\n\t\tRelease|Win32 = Release|Win32"
95                                   "\n\tEndGlobalSection";
96 
97 const char _slnProjDepBeg[]     = "\n\tProjectSection(ProjectDependencies) = postProject";
98 const char _slnProjDepEnd[]     = "\n\tEndProjectSection";
99 const char _slnProjConfBeg[]    = "\n\tGlobalSection(ProjectConfigurationPlatforms) = postSolution";
100 const char _slnProjRelConfTag1[]= ".Release|%1.ActiveCfg = Release|";
101 const char _slnProjRelConfTag2[]= ".Release|%1.Build.0 = Release|";
102 const char _slnProjRelConfTag3[]= ".Release|%1.Deploy.0 = Release|";
103 const char _slnProjDbgConfTag1[]= ".Debug|%1.ActiveCfg = Debug|";
104 const char _slnProjDbgConfTag2[]= ".Debug|%1.Build.0 = Debug|";
105 const char _slnProjDbgConfTag3[]= ".Debug|%1.Deploy.0 = Debug|";
106 const char _slnProjConfEnd[]    = "\n\tEndGlobalSection";
107 const char _slnExtSections[]    = "\n\tGlobalSection(ExtensibilityGlobals) = postSolution"
108                                   "\n\tEndGlobalSection"
109                                   "\n\tGlobalSection(ExtensibilityAddIns) = postSolution"
110                                   "\n\tEndGlobalSection";
111 // ------------------------------------------------------------------
112 
VcprojGenerator()113 VcprojGenerator::VcprojGenerator()
114     : Win32MakefileGenerator(),
115       is64Bit(false),
116       customBuildToolFilterFileSuffix(QStringLiteral(".cbt")),
117       projectWriter(nullptr)
118 {
119 }
120 
~VcprojGenerator()121 VcprojGenerator::~VcprojGenerator()
122 {
123     delete projectWriter;
124 }
125 
writeMakefile(QTextStream & t)126 bool VcprojGenerator::writeMakefile(QTextStream &t)
127 {
128     initProject(); // Fills the whole project with proper data
129 
130     // Generate solution file
131     if(project->first("TEMPLATE") == "vcsubdirs") {
132         if (!project->isActiveConfig("build_pass")) {
133             debug_msg(1, "Generator: MSVC.NET: Writing solution file");
134             writeSubDirs(t);
135         } else {
136             debug_msg(1, "Generator: MSVC.NET: Not writing solution file for build_pass configs");
137         }
138         return true;
139     } else
140     // Generate single configuration project file
141     if (project->first("TEMPLATE") == "vcapp" ||
142         project->first("TEMPLATE") == "vclib") {
143         if(!project->isActiveConfig("build_pass")) {
144             debug_msg(1, "Generator: MSVC.NET: Writing single configuration project file");
145             XmlOutput xmlOut(t);
146             projectWriter->write(xmlOut, vcProject);
147         }
148         return true;
149     }
150     return project->isActiveConfig("build_pass");
151 }
152 
writeProjectMakefile()153 bool VcprojGenerator::writeProjectMakefile()
154 {
155     QTextStream t(&Option::output);
156 
157     // Check if all requirements are fulfilled
158     if(!project->values("QMAKE_FAILED_REQUIREMENTS").isEmpty()) {
159         fprintf(stderr, "Project file not generated because all requirements not met:\n\t%s\n",
160                 var("QMAKE_FAILED_REQUIREMENTS").toLatin1().constData());
161         return true;
162     }
163 
164     // Generate project file
165     if(project->first("TEMPLATE") == "vcapp" ||
166        project->first("TEMPLATE") == "vclib") {
167         if (!mergedProjects.count()) {
168             warn_msg(WarnLogic, "Generator: MSVC.NET: no single configuration created, cannot output project!");
169             return false;
170         }
171 
172         debug_msg(1, "Generator: MSVC.NET: Writing project file");
173         VCProject mergedProject;
174         for (int i = 0; i < mergedProjects.count(); ++i) {
175             VCProjectSingleConfig *singleProject = &(mergedProjects.at(i)->vcProject);
176             mergedProject.SingleProjects += *singleProject;
177             for (int j = 0; j < singleProject->ExtraCompilersFiles.count(); ++j) {
178                 const QString &compilerName = singleProject->ExtraCompilersFiles.at(j).Name;
179                 if (!mergedProject.ExtraCompilers.contains(compilerName))
180                     mergedProject.ExtraCompilers += compilerName;
181             }
182         }
183 
184         if(mergedProjects.count() > 1 &&
185            mergedProjects.at(0)->vcProject.Name ==
186            mergedProjects.at(1)->vcProject.Name)
187             mergedProjects.at(0)->writePrlFile();
188         mergedProject.Name = project->first("QMAKE_PROJECT_NAME").toQString();
189         mergedProject.Version = mergedProjects.at(0)->vcProject.Version;
190         mergedProject.SdkVersion = mergedProjects.at(0)->vcProject.SdkVersion;
191         mergedProject.ProjectGUID = project->isEmpty("QMAKE_UUID") ? getProjectUUID().toString().toUpper() : project->first("QMAKE_UUID").toQString();
192         mergedProject.Keyword = project->first("VCPROJ_KEYWORD").toQString();
193         mergedProject.SccProjectName = mergedProjects.at(0)->vcProject.SccProjectName;
194         mergedProject.SccLocalPath = mergedProjects.at(0)->vcProject.SccLocalPath;
195         mergedProject.PlatformName = mergedProjects.at(0)->vcProject.PlatformName;
196         mergedProject.WindowsTargetPlatformVersion =
197                 project->first("WINDOWS_TARGET_PLATFORM_VERSION").toQString();
198         mergedProject.WindowsTargetPlatformMinVersion =
199                 project->first("WINDOWS_TARGET_PLATFORM_MIN_VERSION").toQString();
200 
201         XmlOutput xmlOut(t);
202         projectWriter->write(xmlOut, mergedProject);
203         return true;
204     } else if(project->first("TEMPLATE") == "vcsubdirs") {
205         return writeMakefile(t);
206     }
207     return false;
208 }
209 
210 struct VcsolutionDepend {
211     QString uuid;
212     QString vcprojFile;
213     QString projectName;
214     QString target;
215     Target targetType;
216     QStringList dependencies;
217 };
218 
219 /* Disable optimization in getProjectUUID() due to a compiler
220  * bug in MSVC 2015 that causes ASSERT: "&other != this" in the QString
221  * copy constructor for non-empty file names at:
222  * filename.isEmpty()?project->first("QMAKE_MAKEFILE"):filename */
223 
224 #if defined(Q_CC_MSVC) && !defined(Q_CC_CLANG)
225 #   pragma optimize( "g", off )
226 #   pragma warning ( disable : 4748 )
227 #endif
228 
getProjectUUID(const QString & filename)229 QUuid VcprojGenerator::getProjectUUID(const QString &filename)
230 {
231     bool validUUID = true;
232 
233     // Read GUID from variable-space
234     auto uuid = QUuid::fromString(project->first("GUID").toQStringView());
235 
236     // If none, create one based on the MD5 of absolute project path
237     if(uuid.isNull() || !filename.isEmpty()) {
238         QString abspath = Option::fixPathToTargetOS(
239                     filename.isEmpty() ? project->first("QMAKE_MAKEFILE").toQString() : filename);
240         QByteArray digest = QCryptographicHash::hash(abspath.toUtf8(), QCryptographicHash::Sha1);
241         memcpy((unsigned char*)(&uuid), digest.constData(), sizeof(QUuid));
242         validUUID = !uuid.isNull();
243         uuid.data4[0] = (uuid.data4[0] & 0x3F) | 0x80; // UV_DCE variant
244         uuid.data3 = (uuid.data3 & 0x0FFF) | (QUuid::Name<<12);
245     }
246 
247     // If still not valid, generate new one, and suggest adding to .pro
248     if(uuid.isNull() || !validUUID) {
249         uuid = QUuid::createUuid();
250         fprintf(stderr,
251                 "qmake couldn't create a GUID based on filepath, and we couldn't\nfind a valid GUID in the .pro file (Consider adding\n'GUID = %s'  to the .pro file)\n",
252                 uuid.toString().toUpper().toLatin1().constData());
253     }
254 
255     // Store GUID in variable-space
256     project->values("GUID") = ProStringList(uuid.toString().toUpper());
257     return uuid;
258 }
259 
260 #if defined(Q_CC_MSVC) && !defined(Q_CC_CLANG)
261 #   pragma optimize( "g", on )
262 #endif
263 
increaseUUID(const QUuid & id)264 QUuid VcprojGenerator::increaseUUID(const QUuid &id)
265 {
266     QUuid result(id);
267     qint64 dataFirst = (result.data4[0] << 24) +
268                        (result.data4[1] << 16) +
269                        (result.data4[2] << 8) +
270                         result.data4[3];
271     qint64 dataLast =  (result.data4[4] << 24) +
272                        (result.data4[5] << 16) +
273                        (result.data4[6] <<  8) +
274                         result.data4[7];
275 
276     if(!(dataLast++))
277         dataFirst++;
278 
279     result.data4[0] = uchar((dataFirst >> 24) & 0xff);
280     result.data4[1] = uchar((dataFirst >> 16) & 0xff);
281     result.data4[2] = uchar((dataFirst >>  8) & 0xff);
282     result.data4[3] = uchar(dataFirst         & 0xff);
283     result.data4[4] = uchar((dataLast  >> 24) & 0xff);
284     result.data4[5] = uchar((dataLast  >> 16) & 0xff);
285     result.data4[6] = uchar((dataLast  >>  8) & 0xff);
286     result.data4[7] = uchar(dataLast          & 0xff);
287     return result;
288 }
289 
retrievePlatformToolSet() const290 QString VcprojGenerator::retrievePlatformToolSet() const
291 {
292     // The PlatformToolset string corresponds to the name of a directory in
293     // $(VCTargetsPath)\Platforms\{Win32,x64,...}\PlatformToolsets
294     // e.g. v90, v100, v110, v110_xp, v120_CTP_Nov, v120, or WindowsSDK7.1
295 
296     // This environment variable may be set by a commandline build
297     // environment such as the Windows SDK command prompt
298     QByteArray envVar = qgetenv("PlatformToolset");
299     if (!envVar.isEmpty())
300         return envVar;
301 
302     switch (vcProject.Configuration.CompilerVersion)
303     {
304     case NET2012:
305         return QStringLiteral("v110");
306     case NET2013:
307         return QStringLiteral("v120");
308     case NET2015:
309         return QStringLiteral("v140");
310     case NET2017:
311         return QStringLiteral("v141");
312     case NET2019:
313         return QStringLiteral("v142");
314     default:
315         return QString();
316     }
317 }
318 
isStandardSuffix(const QString & suffix) const319 bool VcprojGenerator::isStandardSuffix(const QString &suffix) const
320 {
321     if (!project->values("QMAKE_APP_FLAG").isEmpty()) {
322         if (suffix.compare("exe", Qt::CaseInsensitive) == 0)
323             return true;
324     } else if (project->isActiveConfig("shared")) {
325         if (suffix.compare("dll", Qt::CaseInsensitive) == 0)
326             return true;
327     } else {
328         if (suffix.compare("lib", Qt::CaseInsensitive) == 0)
329             return true;
330     }
331     return false;
332 }
333 
firstInputFileName(const ProString & extraCompilerName) const334 ProString VcprojGenerator::firstInputFileName(const ProString &extraCompilerName) const
335 {
336     for (const ProString &var : project->values(ProKey(extraCompilerName + ".input"))) {
337         const ProStringList &files = project->values(var.toKey());
338         if (!files.isEmpty())
339             return files.first();
340     }
341     return ProString();
342 }
343 
firstExpandedOutputFileName(const ProString & extraCompilerName)344 QString VcprojGenerator::firstExpandedOutputFileName(const ProString &extraCompilerName)
345 {
346     const ProString firstOutput = project->first(ProKey(extraCompilerName + ".output"));
347     return replaceExtraCompilerVariables(firstOutput.toQString(),
348                                          firstInputFileName(extraCompilerName).toQString(),
349                                          QString(), NoShell);
350 }
351 
collectDependencies(QMakeProject * proj,QHash<QString,QString> & projLookup,QHash<QString,QString> & projGuids,QHash<VcsolutionDepend *,QStringList> & extraSubdirs,QHash<QString,VcsolutionDepend * > & solution_depends,QList<VcsolutionDepend * > & solution_cleanup,QTextStream & t,QHash<QString,ProStringList> & subdirProjectLookup,const ProStringList & allDependencies)352 ProStringList VcprojGenerator::collectDependencies(QMakeProject *proj, QHash<QString, QString> &projLookup,
353                                                    QHash<QString, QString> &projGuids,
354                                                    QHash<VcsolutionDepend *, QStringList> &extraSubdirs,
355                                                    QHash<QString, VcsolutionDepend*> &solution_depends,
356                                                    QList<VcsolutionDepend*> &solution_cleanup,
357                                                    QTextStream &t,
358                                                    QHash<QString, ProStringList> &subdirProjectLookup,
359                                                    const ProStringList &allDependencies)
360 {
361     QVector<QPair<QString, ProStringList> > collectedSubdirs;
362     ProStringList tmp_proj_subdirs = proj->values("SUBDIRS");
363     ProStringList projectsInProject;
364     const int numSubdirs = tmp_proj_subdirs.size();
365     collectedSubdirs.reserve(numSubdirs);
366     for (int x = 0; x < numSubdirs; ++x) {
367         ProString tmpdir = tmp_proj_subdirs.at(x);
368         const ProKey tmpdirConfig(tmpdir + ".CONFIG");
369         if (!proj->isEmpty(tmpdirConfig)) {
370             const ProStringList config = proj->values(tmpdirConfig);
371             if (config.contains(QStringLiteral("no_default_target")))
372                 continue; // Ignore this sub-dir
373         }
374         const ProKey fkey(tmpdir + ".file");
375         const ProKey skey(tmpdir + ".subdir");
376         if (!proj->isEmpty(fkey)) {
377             if (!proj->isEmpty(skey))
378                 warn_msg(WarnLogic, "Cannot assign both file and subdir for subdir %s",
379                          tmpdir.toLatin1().constData());
380             tmpdir = proj->first(fkey);
381         } else if (!proj->isEmpty(skey)) {
382             tmpdir = proj->first(skey);
383         }
384         projectsInProject.append(tmpdir);
385         collectedSubdirs.append(qMakePair(tmpdir.toQString(), proj->values(ProKey(tmp_proj_subdirs.at(x) + ".depends"))));
386         projLookup.insert(tmp_proj_subdirs.at(x).toQString(), tmpdir.toQString());
387     }
388     for (const auto &subdir : qAsConst(collectedSubdirs)) {
389         QString profile = subdir.first;
390         QFileInfo fi(fileInfo(Option::normalizePath(profile)));
391         if (fi.exists()) {
392             if (fi.isDir()) {
393                 if (!profile.endsWith(Option::dir_sep))
394                     profile += Option::dir_sep;
395                 profile += fi.baseName() + Option::pro_ext;
396                 QString profileKey = fi.absoluteFilePath();
397                 fi = QFileInfo(fileInfo(Option::normalizePath(profile)));
398                 if (!fi.exists())
399                     continue;
400                 projLookup.insert(profileKey, fi.absoluteFilePath());
401             }
402             QString oldpwd = qmake_getpwd();
403             QString oldoutpwd = Option::output_dir;
404             QMakeProject tmp_proj;
405             QString dir = fi.absolutePath(), fn = fi.fileName();
406             if (!dir.isEmpty()) {
407                 if (!qmake_setpwd(dir))
408                     fprintf(stderr, "Cannot find directory: %s", dir.toLatin1().constData());
409             }
410             Option::output_dir = Option::globals->shadowedPath(QDir::cleanPath(dir));
411             if (tmp_proj.read(fn)) {
412                 // Check if all requirements are fulfilled
413                 if (!tmp_proj.isEmpty("QMAKE_FAILED_REQUIREMENTS")) {
414                     fprintf(stderr, "Project file(%s) not added to Solution because all requirements not met:\n\t%s\n",
415                             fn.toLatin1().constData(),
416                             tmp_proj.values("QMAKE_FAILED_REQUIREMENTS").join(' ').toLatin1().constData());
417                     qmake_setpwd(oldpwd);
418                     Option::output_dir = oldoutpwd;
419                     continue;
420                 }
421                 if (tmp_proj.first("TEMPLATE") == "vcsubdirs") {
422                     ProStringList tmpList = collectDependencies(&tmp_proj, projLookup, projGuids, extraSubdirs, solution_depends, solution_cleanup, t, subdirProjectLookup, subdir.second);
423                     subdirProjectLookup.insert(subdir.first, tmpList);
424                 } else {
425                     ProStringList tmpList;
426                     tmpList += subdir.second;
427                     tmpList += allDependencies;
428                     // Initialize a 'fake' project to get the correct variables
429                     // and to be able to extract all the dependencies
430                     Option::QMAKE_MODE old_mode = Option::qmake_mode;
431                     Option::qmake_mode = Option::QMAKE_GENERATE_NOTHING;
432                     VcprojGenerator tmp_vcproj;
433                     tmp_vcproj.setNoIO(true);
434                     tmp_vcproj.setProjectFile(&tmp_proj);
435                     Option::qmake_mode = old_mode;
436 
437                     // We assume project filename is [QMAKE_PROJECT_NAME].vcproj
438                     const ProString projectName = tmp_vcproj.project->first("QMAKE_PROJECT_NAME");
439                     const QString vcproj = projectName + project->first("VCPROJ_EXTENSION");
440                     QString vcprojDir = Option::output_dir;
441 
442                     // If file doesn't exsist, then maybe the users configuration
443                     // doesn't allow it to be created. Skip to next...
444                     if (!exists(vcprojDir + Option::dir_sep + vcproj)) {
445                         warn_msg(WarnLogic, "Ignored (not found) '%s'", QString(vcprojDir + Option::dir_sep + vcproj).toLatin1().constData());
446                         goto nextfile; // # Dirty!
447                     }
448 
449                     VcsolutionDepend *newDep = new VcsolutionDepend;
450                     newDep->vcprojFile = vcprojDir + Option::dir_sep + vcproj;
451                     newDep->projectName = projectName.toQString();
452                     newDep->target = tmp_proj.first("MSVCPROJ_TARGET").toQString().section(Option::dir_sep, -1);
453                     newDep->targetType = tmp_vcproj.projectTarget;
454                     newDep->uuid = tmp_proj.isEmpty("QMAKE_UUID") ? getProjectUUID(Option::fixPathToLocalOS(vcprojDir + QDir::separator() + vcproj)).toString().toUpper(): tmp_proj.first("QMAKE_UUID").toQString();
455                     // We want to store it as the .lib name.
456                     if (newDep->target.endsWith(".dll"))
457                         newDep->target = newDep->target.left(newDep->target.length()-3) + "lib";
458                     projGuids.insert(newDep->projectName, newDep->target);
459 
460                     if (tmpList.size()) {
461                         const ProStringList depends = tmpList;
462                         for (const ProString &dep : depends) {
463                             QString depend = dep.toQString();
464                             if (!projGuids[depend].isEmpty()) {
465                                 newDep->dependencies << projGuids[depend];
466                             } else if (subdirProjectLookup[projLookup[depend]].size() > 0) {
467                                 const ProStringList tmpLst = subdirProjectLookup[projLookup[depend]];
468                                 for (const ProString &tDep : tmpLst) {
469                                     QString tmpDep = tDep.toQString();
470                                     newDep->dependencies << projGuids[projLookup[tmpDep]];
471                                 }
472                             } else {
473                                 extraSubdirs.insert(newDep, tmpList.toQStringList());
474                                 newDep->dependencies.clear();
475                                 break;
476                             }
477                         }
478                     }
479 
480                     // All ActiveQt Server projects are dependent on idc.exe
481                     if (tmp_proj.values("CONFIG").contains("qaxserver"))
482                         newDep->dependencies << "idc.exe";
483 
484                     // Add all unknown libs to the deps
485                     QStringList where = QStringList() << "LIBS" << "LIBS_PRIVATE"
486                                                       << "QMAKE_LIBS" << "QMAKE_LIBS_PRIVATE";
487                     for (QStringList::ConstIterator wit = where.cbegin();
488                         wit != where.cend(); ++wit) {
489                             const ProStringList &l = tmp_proj.values(ProKey(*wit));
490                             for (ProStringList::ConstIterator it = l.begin(); it != l.end(); ++it) {
491                                 const QString opt = fixLibFlag(*it).toQString();
492                                 if (!opt.startsWith("/") &&   // Not a switch
493                                     opt != newDep->target && // Not self
494                                     opt != "opengl32.lib" && // We don't care about these libs
495                                     opt != "glu32.lib" &&    // to make depgen alittle faster
496                                     opt != "kernel32.lib" &&
497                                     opt != "user32.lib" &&
498                                     opt != "gdi32.lib" &&
499                                     opt != "comdlg32.lib" &&
500                                     opt != "advapi32.lib" &&
501                                     opt != "shell32.lib" &&
502                                     opt != "ole32.lib" &&
503                                     opt != "oleaut32.lib" &&
504                                     opt != "uuid.lib" &&
505                                     opt != "imm32.lib" &&
506                                     opt != "winmm.lib" &&
507                                     opt != "wsock32.lib" &&
508                                     opt != "ws2_32.lib" &&
509                                     opt != "winspool.lib" &&
510                                     opt != "delayimp.lib")
511                                 {
512                                     newDep->dependencies << opt.section(Option::dir_sep, -1);
513                                 }
514                             }
515                     }
516 #ifdef DEBUG_SOLUTION_GEN
517                     qDebug("Deps for %20s: [%s]", newDep->target.toLatin1().constData(), newDep->dependencies.join(" :: ").toLatin1().constData());
518 #endif
519                     solution_cleanup.append(newDep);
520                     solution_depends.insert(newDep->target, newDep);
521                 }
522 nextfile:
523                 qmake_setpwd(oldpwd);
524                 Option::output_dir = oldoutpwd;
525             }
526         }
527     }
528     return projectsInProject;
529 }
530 
writeSubDirs(QTextStream & t)531 void VcprojGenerator::writeSubDirs(QTextStream &t)
532 {
533     // Check if all requirements are fulfilled
534     if(!project->values("QMAKE_FAILED_REQUIREMENTS").isEmpty()) {
535         fprintf(stderr, "Project file not generated because all requirements not met:\n\t%s\n",
536                 var("QMAKE_FAILED_REQUIREMENTS").toLatin1().constData());
537         return;
538     }
539 
540     switch (vcProject.Configuration.CompilerVersion) {
541     case NET2019:
542         t << _slnHeader142;
543         break;
544     case NET2017:
545         t << _slnHeader141;
546         break;
547     case NET2015:
548         t << _slnHeader140;
549         break;
550     case NET2013:
551         t << _slnHeader120;
552         break;
553     case NET2012:
554         t << _slnHeader110;
555         break;
556     case NET2010:
557         t << _slnHeader100;
558         break;
559     case NET2008:
560         t << _slnHeader90;
561         break;
562     case NET2005:
563         t << _slnHeader80;
564         break;
565     case NET2003:
566         t << _slnHeader71;
567         break;
568     case NET2002:
569         t << _slnHeader70;
570         break;
571     default:
572         t << _slnHeader70;
573         warn_msg(WarnLogic, "Generator: MSVC.NET: Unknown version (%d) of MSVC detected for .sln",
574                  vcProject.Configuration.CompilerVersion);
575         break;
576     }
577 
578     QHash<QString, VcsolutionDepend*> solution_depends;
579     QList<VcsolutionDepend*> solution_cleanup;
580 
581     // Make sure that all temp projects are configured
582     // for release so that the depends are created
583     // without the debug <lib>dxxx.lib name mangling
584     QString old_after_vars = Option::globals->extra_cmds[QMakeEvalAfter];
585     Option::globals->extra_cmds[QMakeEvalAfter].append("\nCONFIG+=release");
586 
587     QHash<QString, QString> profileLookup;
588     QHash<QString, QString> projGuids;
589     QHash<VcsolutionDepend *, QStringList> extraSubdirs;
590     QHash<QString, ProStringList> subdirProjectLookup;
591     collectDependencies(project, profileLookup, projGuids, extraSubdirs, solution_depends, solution_cleanup, t, subdirProjectLookup);
592 
593     // write out projects
594     for (QList<VcsolutionDepend*>::Iterator it = solution_cleanup.begin(); it != solution_cleanup.end(); ++it) {
595         // ### quoting rules?
596         t << _slnProjectBeg << _slnMSVCvcprojGUID << _slnProjectMid
597             << "\"" << (*it)->projectName << "\", \"" << (*it)->vcprojFile
598             << "\", \"" << (*it)->uuid << "\"";
599 
600         debug_msg(1, "Project %s has dependencies: %s", (*it)->target.toLatin1().constData(), (*it)->dependencies.join(" ").toLatin1().constData());
601 
602         bool hasDependency = false;
603         for (QStringList::iterator dit = (*it)->dependencies.begin();  dit != (*it)->dependencies.end(); ++dit) {
604             if (VcsolutionDepend *vc = solution_depends[*dit]) {
605                 if (!hasDependency) {
606                     hasDependency = true;
607                     t << _slnProjDepBeg;
608                 }
609                 t << "\n\t\t" << vc->uuid << " = " << vc->uuid;
610             }
611         }
612         if (hasDependency)
613             t << _slnProjDepEnd;
614 
615         t << _slnProjectEnd;
616     }
617 
618     t << _slnGlobalBeg;
619 
620     for (auto extraIt = extraSubdirs.cbegin(), end = extraSubdirs.cend(); extraIt != end; ++extraIt) {
621         for (const QString &depend : extraIt.value()) {
622             if (!projGuids[depend].isEmpty()) {
623                 extraIt.key()->dependencies << projGuids[depend];
624             } else if (!profileLookup[depend].isEmpty()) {
625                 if (!projGuids[profileLookup[depend]].isEmpty())
626                     extraIt.key()->dependencies << projGuids[profileLookup[depend]];
627             }
628         }
629     }
630     QString slnConf = _slnSolutionConf;
631     if (!project->isEmpty("VCPROJ_ARCH")) {
632         slnConf.replace(QLatin1String("|Win32"), "|" + project->first("VCPROJ_ARCH"));
633     } else if (is64Bit) {
634         slnConf.replace(QLatin1String("|Win32"), QLatin1String("|x64"));
635     }
636     t << slnConf;
637 
638     // Restore previous after_user_var options
639     Option::globals->extra_cmds[QMakeEvalAfter] = old_after_vars;
640 
641     t << _slnProjConfBeg;
642     for(QList<VcsolutionDepend*>::Iterator it = solution_cleanup.begin(); it != solution_cleanup.end(); ++it) {
643         QString platform = is64Bit ? "x64" : "Win32";
644         QString xplatform = platform;
645         const bool isWinRT = project->isActiveConfig("winrt");
646         if (!project->isEmpty("VCPROJ_ARCH")) {
647             xplatform = project->first("VCPROJ_ARCH").toQString();
648         }
649         if (!project->isHostBuild())
650             platform = xplatform;
651         t << "\n\t\t" << (*it)->uuid << QString(_slnProjDbgConfTag1).arg(xplatform) << platform;
652         t << "\n\t\t" << (*it)->uuid << QString(_slnProjDbgConfTag2).arg(xplatform) << platform;
653         if (isWinRT)
654             t << "\n\t\t" << (*it)->uuid << QString(_slnProjDbgConfTag3).arg(xplatform) << platform;
655         t << "\n\t\t" << (*it)->uuid << QString(_slnProjRelConfTag1).arg(xplatform) << platform;
656         t << "\n\t\t" << (*it)->uuid << QString(_slnProjRelConfTag2).arg(xplatform) << platform;
657         if (isWinRT)
658             t << "\n\t\t" << (*it)->uuid << QString(_slnProjRelConfTag3).arg(xplatform) << platform;
659     }
660     t << _slnProjConfEnd;
661     t << _slnExtSections;
662     t << _slnGlobalEnd;
663 
664 
665     while (!solution_cleanup.isEmpty())
666         delete solution_cleanup.takeFirst();
667 }
668 
669 // ------------------------------------------------------------------------------------------------
670 // ------------------------------------------------------------------------------------------------
671 
hasBuiltinCompiler(const QString & file)672 bool VcprojGenerator::hasBuiltinCompiler(const QString &file)
673 {
674     // Source files
675     for (int i = 0; i < Option::cpp_ext.count(); ++i)
676         if (file.endsWith(Option::cpp_ext.at(i)))
677             return true;
678     for (int i = 0; i < Option::c_ext.count(); ++i)
679         if (file.endsWith(Option::c_ext.at(i)))
680             return true;
681     if (file.endsWith(".rc")
682         || file.endsWith(".idl"))
683         return true;
684     return false;
685 }
686 
createCustomBuildToolFakeFile(const QString & cbtFilePath,const QString & realOutFilePath)687 void VcprojGenerator::createCustomBuildToolFakeFile(const QString &cbtFilePath,
688                                                     const QString &realOutFilePath)
689 {
690     QFile file(fileFixify(cbtFilePath, FileFixifyFromOutdir | FileFixifyAbsolute));
691     if (file.exists())
692         return;
693     if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
694         warn_msg(WarnLogic, "Cannot create '%s'.", qPrintable(file.fileName()));
695         return;
696     }
697     file.write("This is a dummy file needed to create ");
698     file.write(qPrintable(realOutFilePath));
699     file.write("\n");
700 }
701 
init()702 void VcprojGenerator::init()
703 {
704     is64Bit = (project->first("QMAKE_TARGET.arch") == "x86_64");
705     projectWriter = createProjectWriter();
706 
707     if(project->first("TEMPLATE") == "vcsubdirs") //too much work for subdirs
708         return;
709 
710     debug_msg(1, "Generator: MSVC.NET: Initializing variables");
711 
712     // this should probably not be here, but I'm using it to wrap the .t files
713     if (project->first("TEMPLATE") == "vcapp")
714         project->values("QMAKE_APP_FLAG").append("1");
715     else if (project->first("TEMPLATE") == "vclib")
716         project->values("QMAKE_LIB_FLAG").append("1");
717 
718     processVars();
719 
720     // set /VERSION for EXE/DLL header
721     ProString major_minor = project->first("VERSION_PE_HEADER");
722     if (major_minor.isEmpty()) {
723         ProString version = project->first("VERSION");
724         if (!version.isEmpty()) {
725             int firstDot = version.indexOf(".");
726             int secondDot = version.indexOf(".", firstDot + 1);
727             major_minor = version.left(secondDot);
728         }
729     }
730     if (!major_minor.isEmpty())
731         project->values("QMAKE_LFLAGS").append("/VERSION:" + major_minor);
732 
733     MakefileGenerator::init();
734 
735     // $$QMAKE.. -> $$MSVCPROJ.. -------------------------------------
736     const ProStringList &incs = project->values("INCLUDEPATH");
737     for (ProStringList::ConstIterator incit = incs.begin(); incit != incs.end(); ++incit) {
738         QString inc = (*incit).toQString();
739         project->values("MSVCPROJ_INCPATH").append("-I" + escapeFilePath(inc));
740     }
741 
742     QString dest = Option::fixPathToTargetOS(project->first("TARGET").toQString()) + project->first("TARGET_EXT");
743     project->values("MSVCPROJ_TARGET") = ProStringList(dest);
744 
745     // DLL COPY ------------------------------------------------------
746     if (project->isActiveConfig("dll") && !project->values("DLLDESTDIR").isEmpty()) {
747         const ProStringList &dlldirs = project->values("DLLDESTDIR");
748         QString copydll("");
749         ProStringList::ConstIterator dlldir;
750         for (dlldir = dlldirs.begin(); dlldir != dlldirs.end(); ++dlldir) {
751             if (!copydll.isEmpty())
752                 copydll += " && ";
753             copydll += "copy \"$(TargetPath)\" " + escapeFilePath(*dlldir);
754         }
755 
756         QString deststr("Copy " + dest + " to ");
757         for (dlldir = dlldirs.begin(); dlldir != dlldirs.end();) {
758             deststr += *dlldir;
759             ++dlldir;
760             if (dlldir != dlldirs.end())
761                 deststr += ", ";
762         }
763 
764         project->values("MSVCPROJ_COPY_DLL").append(copydll);
765         project->values("MSVCPROJ_COPY_DLL_DESC").append(deststr);
766     }
767 
768 #if 0
769     // Verbose output if "-d -d"...
770     qDebug("Generator: MSVC.NET: List of current variables:");
771     for (ProValueMap::ConstIterator it = project->variables().begin(); it != project->variables().end(); ++it)
772         qDebug("Generator: MSVC.NET: %s => %s", qPrintable(it.key().toQString()), qPrintable(it.value().join(" | ")));
773 #endif
774 
775     // Figure out what we're trying to build
776     if(project->first("TEMPLATE") == "vcapp") {
777         projectTarget = Application;
778     } else if(project->first("TEMPLATE") == "vclib") {
779         if(project->isActiveConfig("staticlib")) {
780             project->values("LIBS") += project->values("RES_FILE");
781             projectTarget = StaticLib;
782         } else
783             projectTarget = SharedLib;
784     }
785 
786     // Setup PCH variables
787     precompH = project->first("PRECOMPILED_HEADER").toQString();
788     precompSource = project->first("PRECOMPILED_SOURCE").toQString();
789     pchIsCFile = project->isActiveConfig("precompile_header_c");
790     usePCH = !precompH.isEmpty() && (pchIsCFile || project->isActiveConfig("precompile_header"));
791     if (usePCH) {
792         precompHFilename = fileInfo(precompH).fileName();
793         // Created files
794         QString origTarget = project->first("QMAKE_ORIG_TARGET").toQString();
795         precompObj = origTarget + Option::obj_ext;
796         precompPch = origTarget + ".pch";
797         // Add PRECOMPILED_HEADER to HEADERS
798         if (!project->values("HEADERS").contains(precompH))
799             project->values("HEADERS") += precompH;
800         // Return to variable pool
801         project->values("PRECOMPILED_OBJECT") = ProStringList(precompObj);
802         project->values("PRECOMPILED_PCH")    = ProStringList(precompPch);
803 
804         autogenPrecompSource = precompSource.isEmpty() && project->isActiveConfig("autogen_precompile_source");
805         if (autogenPrecompSource) {
806             precompSource = precompH
807                     + (pchIsCFile
808                        ? (Option::c_ext.count() ? Option::c_ext.at(0) : QLatin1String(".c"))
809                        : (Option::cpp_ext.count() ? Option::cpp_ext.at(0) : QLatin1String(".cpp")));
810             project->values("GENERATED_SOURCES") += precompSource;
811         } else if (!precompSource.isEmpty()) {
812             project->values("SOURCES") += precompSource;
813         }
814     }
815 
816     // Add all input files for a custom compiler into a map for uniqueness,
817     // unless the compiler is configure as a combined stage, then use the first one
818     for (const ProString &quc : project->values("QMAKE_EXTRA_COMPILERS")) {
819         const ProStringList &invar = project->values(ProKey(quc + ".input"));
820         const QString compiler_out = project->first(ProKey(quc + ".output")).toQString();
821         for (ProStringList::ConstIterator iit = invar.constBegin(); iit != invar.constEnd(); ++iit) {
822             ProStringList fileList = project->values((*iit).toKey());
823             if (!fileList.isEmpty()) {
824                 if (project->values(ProKey(quc + ".CONFIG")).indexOf("combine") != -1)
825                     fileList.erase(fileList.begin() + 1, fileList.end());
826                 for (ProStringList::ConstIterator fit = fileList.constBegin(); fit != fileList.constEnd(); ++fit) {
827                     QString file = (*fit).toQString();
828                     if (verifyExtraCompiler(quc, file)) {
829                         if (!hasBuiltinCompiler(file)) {
830                             extraCompilerSources[file] += quc.toQString();
831                         } else {
832                             // Create a fake file foo.moc.cbt for the project view.
833                             // This prevents VS from complaining about a circular
834                             // dependency from foo.moc -> foo.moc.
835                             QString realOut = replaceExtraCompilerVariables(
836                                 compiler_out, file, QString(), NoShell);
837                             QString out = realOut + customBuildToolFilterFileSuffix;
838                             createCustomBuildToolFakeFile(out, realOut);
839                             out = Option::fixPathToTargetOS(out, false);
840                             extraCompilerSources[out] += quc.toQString();
841                             extraCompilerOutputs[out] = file;
842                         }
843                     }
844                 }
845             }
846         }
847     }
848 
849 #if 0 // Debugging
850     for (auto it = extraCompilerSources.cbegin(), end = extraCompilerSources.cend(); it != end; ++it)
851         qDebug("Extracompilers for %s are (%s)", it.key().toLatin1().constData(), it.value().join(", ").toLatin1().constData());
852     for (auto it = extraCompilerOutputs.cbegin(), end = extraCompilerOutputs.cend(); it != end; ++it)
853         qDebug("Object mapping for %s is (%s)", it.key().toLatin1().constData(), it.value().join(", ").toLatin1().constData());
854     qDebug("");
855 #endif
856 }
857 
mergeBuildProject(MakefileGenerator * other)858 bool VcprojGenerator::mergeBuildProject(MakefileGenerator *other)
859 {
860     if (!other || !other->projectFile()) {
861         warn_msg(WarnLogic, "VcprojGenerator: Cannot merge null project.");
862         return false;
863     }
864     if (other->projectFile()->first("MAKEFILE_GENERATOR") != project->first("MAKEFILE_GENERATOR")) {
865         warn_msg(WarnLogic, "VcprojGenerator: Cannot merge other types of projects! (ignored)");
866         return false;
867     }
868 
869     VcprojGenerator *otherVC = static_cast<VcprojGenerator*>(other);
870     mergedProjects += otherVC;
871     return true;
872 }
873 
initProject()874 void VcprojGenerator::initProject()
875 {
876     // Initialize XML sub elements
877     // - Do this first since project elements may need
878     // - to know of certain configuration options
879     initConfiguration();
880     initRootFiles();
881     initSourceFiles();
882     initHeaderFiles();
883     initGeneratedFiles();
884     initLexYaccFiles();
885     initTranslationFiles();
886     initFormFiles();
887     initResourceFiles();
888     initDistributionFiles();
889     initExtraCompilerOutputs();
890 
891     // Own elements -----------------------------
892     vcProject.Name = project->first("QMAKE_ORIG_TARGET").toQString();
893     switch (vcProject.Configuration.CompilerVersion) {
894     case NET2019:
895         vcProject.Version = "16.00";
896         break;
897     case NET2017:
898         vcProject.Version = "15.00";
899         break;
900     case NET2015:
901         vcProject.Version = "14.00";
902         break;
903     case NET2013:
904         vcProject.Version = "12.00";
905         break;
906     case NET2012:
907         vcProject.Version = "11.00";
908         break;
909     case NET2010:
910         vcProject.Version = "10.00";
911         break;
912     case NET2008:
913         vcProject.Version = "9,00";
914         break;
915     case NET2005:
916                 //### using ',' because of a bug in 2005 B2
917                 //### VS uses '.' or ',' depending on the regional settings! Using ',' always works.
918         vcProject.Version = "8,00";
919         break;
920     case NET2003:
921         vcProject.Version = "7.10";
922         break;
923     case NET2002:
924         vcProject.Version = "7.00";
925         break;
926     default:
927         vcProject.Version = "7.00";
928         warn_msg(WarnLogic, "Generator: MSVC.NET: Unknown version (%d) of MSVC detected for .vcproj", vcProject.Configuration.CompilerVersion);
929         break;
930     }
931 
932     vcProject.Keyword = project->first("VCPROJ_KEYWORD").toQString();
933     if (!project->isEmpty("VCPROJ_ARCH")) {
934         vcProject.PlatformName = project->first("VCPROJ_ARCH").toQString();
935     } else {
936         vcProject.PlatformName = (is64Bit ? "x64" : "Win32");
937     }
938     vcProject.SdkVersion = project->first("WINSDK_VER").toQString();
939     // These are not used by Qt, but may be used by customers
940     vcProject.SccProjectName = project->first("SCCPROJECTNAME").toQString();
941     vcProject.SccLocalPath = project->first("SCCLOCALPATH").toQString();
942     vcProject.flat_files = project->isActiveConfig("flat");
943 
944     // Set up the full target path for target conflict checking.
945     const QChar slash = QLatin1Char('/');
946     QString destdir = QDir::fromNativeSeparators(var("DESTDIR"));
947     if (!destdir.endsWith(slash))
948         destdir.append(slash);
949     project->values("DEST_TARGET") = ProStringList(destdir
950                                                    + project->first("TARGET")
951                                                    + project->first("TARGET_EXT"));
952 }
953 
initConfiguration()954 void VcprojGenerator::initConfiguration()
955 {
956     // Initialize XML sub elements
957     // - Do this first since main configuration elements may need
958     // - to know of certain compiler/linker options
959     VCConfiguration &conf = vcProject.Configuration;
960     conf.suppressUnknownOptionWarnings = project->isActiveConfig("suppress_vcproj_warnings");
961     conf.CompilerVersion = vsVersionFromString(project->first("MSVC_VER"));
962 
963     if (conf.CompilerVersion >= NET2012) {
964         conf.WinRT = project->isActiveConfig("winrt");
965         if (conf.WinRT) {
966             // Saner defaults
967             conf.compiler.UsePrecompiledHeader = pchNone;
968             conf.compiler.CompileAsWinRT = _False;
969             conf.linker.GenerateWindowsMetadata = _False;
970         }
971     }
972 
973     initCompilerTool();
974 
975     // Only on configuration per build
976     bool isDebug = project->isActiveConfig("debug");
977 
978     if(projectTarget == StaticLib)
979         initLibrarianTool();
980     else {
981         conf.linker.GenerateDebugInformation = project->isActiveConfig("debug_info") ? _True : _False;
982         initLinkerTool();
983     }
984     initManifestTool();
985     initResourceTool();
986     initIDLTool();
987 
988     // Own elements -----------------------------
989     ProString temp = project->first("BuildBrowserInformation");
990     switch (projectTarget) {
991     case SharedLib:
992         conf.ConfigurationType = typeDynamicLibrary;
993         break;
994     case StaticLib:
995         conf.ConfigurationType = typeStaticLibrary;
996         break;
997     case Application:
998     default:
999         conf.ConfigurationType = typeApplication;
1000         break;
1001     }
1002 
1003     conf.OutputDirectory = project->first("DESTDIR").toQString();
1004     if (conf.OutputDirectory.isEmpty())
1005         conf.OutputDirectory = ".\\";
1006     if (!conf.OutputDirectory.endsWith("\\"))
1007         conf.OutputDirectory += '\\';
1008     if (conf.CompilerVersion >= NET2010) {
1009         conf.PlatformToolSet = retrievePlatformToolSet();
1010 
1011         const QFileInfo targetInfo = fileInfo(project->first("MSVCPROJ_TARGET").toQString());
1012         conf.PrimaryOutput = targetInfo.completeBaseName();
1013 
1014         const QString targetSuffix = targetInfo.suffix();
1015         if (!isStandardSuffix(targetSuffix))
1016             conf.PrimaryOutputExtension = '.' + targetSuffix;
1017     }
1018 
1019     conf.Name = project->values("BUILD_NAME").join(' ');
1020     if (conf.Name.isEmpty())
1021         conf.Name = isDebug ? "Debug" : "Release";
1022     conf.ConfigurationName = conf.Name;
1023     if (!project->isEmpty("VCPROJ_ARCH")) {
1024         conf.Name += "|" + project->first("VCPROJ_ARCH");
1025     } else {
1026         conf.Name += (is64Bit ? "|x64" : "|Win32");
1027     }
1028     conf.ATLMinimizesCRunTimeLibraryUsage = (project->first("ATLMinimizesCRunTimeLibraryUsage").isEmpty() ? _False : _True);
1029     conf.BuildBrowserInformation = triState(temp.isEmpty() ? (short)unset : temp.toShort());
1030     temp = project->first("CharacterSet");
1031     conf.CharacterSet = charSet(temp.isEmpty() ? short(conf.WinRT ? charSetUnicode : charSetNotSet) : temp.toShort());
1032     conf.DeleteExtensionsOnClean = project->first("DeleteExtensionsOnClean").toQString();
1033     conf.ImportLibrary = conf.linker.ImportLibrary;
1034     conf.IntermediateDirectory = project->first("OBJECTS_DIR").toQString();
1035     conf.WholeProgramOptimization = conf.compiler.WholeProgramOptimization;
1036     temp = project->first("UseOfATL");
1037     if(!temp.isEmpty())
1038         conf.UseOfATL = useOfATL(temp.toShort());
1039     temp = project->first("UseOfMfc");
1040     if(!temp.isEmpty())
1041         conf.UseOfMfc = useOfMfc(temp.toShort());
1042 
1043     // Configuration does not need parameters from
1044     // these sub XML items;
1045     initCustomBuildTool();
1046     initPreBuildEventTools();
1047     initPostBuildEventTools();
1048     // Only deploy for crosscompiled projects
1049     if (!project->isHostBuild() || conf.WinRT)
1050         initDeploymentTool();
1051     initWinDeployQtTool();
1052     initPreLinkEventTools();
1053 }
1054 
initCompilerTool()1055 void VcprojGenerator::initCompilerTool()
1056 {
1057     QString placement = project->first("OBJECTS_DIR").toQString();
1058     if(placement.isEmpty())
1059         placement = ".\\";
1060 
1061     VCConfiguration &conf = vcProject.Configuration;
1062     if (conf.CompilerVersion >= NET2010) {
1063         // adjust compiler tool defaults for VS 2010 and above
1064         conf.compiler.Optimization = optimizeDisabled;
1065     }
1066     conf.compiler.AssemblerListingLocation = placement ;
1067     conf.compiler.ObjectFile = placement ;
1068     conf.compiler.ExceptionHandling = ehNone;
1069     // PCH
1070     if (usePCH) {
1071         conf.compiler.UsePrecompiledHeader     = pchUseUsingSpecific;
1072         conf.compiler.PrecompiledHeaderFile    = "$(IntDir)\\" + precompPch;
1073         conf.compiler.PrecompiledHeaderThrough = project->first("PRECOMPILED_HEADER").toQString();
1074         conf.compiler.ForcedIncludeFiles       = project->values("PRECOMPILED_HEADER").toQStringList();
1075     }
1076 
1077     conf.compiler.parseOptions(project->values("QMAKE_CXXFLAGS"));
1078 
1079     if (project->isActiveConfig("windows"))
1080         conf.compiler.PreprocessorDefinitions += "_WINDOWS";
1081     else if (project->isActiveConfig("console"))
1082         conf.compiler.PreprocessorDefinitions += "_CONSOLE";
1083 
1084     conf.compiler.PreprocessorDefinitions += project->values("DEFINES").toQStringList();
1085     conf.compiler.PreprocessorDefinitions += project->values("PRL_EXPORT_DEFINES").toQStringList();
1086     conf.compiler.parseOptions(project->values("MSVCPROJ_INCPATH"));
1087 }
1088 
initLibrarianTool()1089 void VcprojGenerator::initLibrarianTool()
1090 {
1091     VCConfiguration &conf = vcProject.Configuration;
1092     conf.librarian.OutputFile = "$(OutDir)\\";
1093     conf.librarian.OutputFile += project->first("MSVCPROJ_TARGET").toQString();
1094     conf.librarian.AdditionalOptions += project->values("QMAKE_LIBFLAGS").toQStringList();
1095 }
1096 
initManifestTool()1097 void VcprojGenerator::initManifestTool()
1098 {
1099     VCManifestTool &tool = vcProject.Configuration.manifestTool;
1100     const ProString tmplt = project->first("TEMPLATE");
1101     if ((tmplt == "vclib"
1102          && !project->isActiveConfig("embed_manifest_dll")
1103          && !project->isActiveConfig("static"))
1104         || (tmplt == "vcapp"
1105             && !project->isActiveConfig("embed_manifest_exe"))) {
1106         tool.EmbedManifest = _False;
1107     }
1108 }
1109 
initLinkerTool()1110 void VcprojGenerator::initLinkerTool()
1111 {
1112     VCConfiguration &conf = vcProject.Configuration;
1113     conf.linker.parseOptions(project->values("QMAKE_LFLAGS"));
1114 
1115     if (!project->values("DEF_FILE").isEmpty())
1116         conf.linker.ModuleDefinitionFile = project->first("DEF_FILE").toQString();
1117 
1118     static const char * const lflags[] = { "LIBS", "LIBS_PRIVATE",
1119                                            "QMAKE_LIBS", "QMAKE_LIBS_PRIVATE", nullptr };
1120     for (int i = 0; lflags[i]; i++) {
1121         const auto libs = fixLibFlags(lflags[i]);
1122         for (const ProString &lib : libs) {
1123             if (lib.startsWith("/LIBPATH:"))
1124                 conf.linker.AdditionalLibraryDirectories << lib.mid(9).toQString();
1125             else
1126                 conf.linker.AdditionalDependencies << lib.toQString();
1127         }
1128     }
1129 
1130     conf.linker.OutputFile = "$(OutDir)\\";
1131     conf.linker.OutputFile += project->first("MSVCPROJ_TARGET").toQString();
1132 }
1133 
initResourceTool()1134 void VcprojGenerator::initResourceTool()
1135 {
1136     VCConfiguration &conf = vcProject.Configuration;
1137 
1138     ProStringList rcDefines = project->values("RC_DEFINES");
1139     if (rcDefines.size() > 0)
1140         conf.resource.PreprocessorDefinitions = rcDefines.toQStringList();
1141     else
1142         conf.resource.PreprocessorDefinitions = conf.compiler.PreprocessorDefinitions;
1143 
1144     for (const ProString &path : project->values("RC_INCLUDEPATH")) {
1145         QString fixedPath = fileFixify(path.toQString());
1146         if (fileInfo(fixedPath).isRelative()) {
1147             if (fixedPath == QLatin1String("."))
1148                 fixedPath = QStringLiteral("$(ProjectDir)");
1149             else
1150                 fixedPath.prepend(QStringLiteral("$(ProjectDir)\\"));
1151         }
1152         conf.resource.AdditionalIncludeDirectories << escapeFilePath(fixedPath);
1153     }
1154 
1155     // We need to add _DEBUG for the debug version of the project, since the normal compiler defines
1156     // do not contain it. (The compiler defines this symbol automatically, which is wy we don't need
1157     // to add it for the compiler) However, the resource tool does not do this.
1158     if(project->isActiveConfig("debug"))
1159         conf.resource.PreprocessorDefinitions += "_DEBUG";
1160     if (conf.CompilerVersion < NET2010 && project->isActiveConfig("staticlib"))
1161         conf.resource.ResourceOutputFileName = "$(OutDir)\\$(InputName).res";
1162 }
1163 
initIDLTool()1164 void VcprojGenerator::initIDLTool()
1165 {
1166 }
1167 
initCustomBuildTool()1168 void VcprojGenerator::initCustomBuildTool()
1169 {
1170 }
1171 
initPreBuildEventTools()1172 void VcprojGenerator::initPreBuildEventTools()
1173 {
1174 }
1175 
initPostBuildEventTools()1176 void VcprojGenerator::initPostBuildEventTools()
1177 {
1178     VCConfiguration &conf = vcProject.Configuration;
1179     if (!project->values("QMAKE_POST_LINK").isEmpty()) {
1180         QStringList cmdline = VCToolBase::fixCommandLine(var("QMAKE_POST_LINK"));
1181         conf.postBuild.CommandLine = cmdline;
1182         conf.postBuild.Description = cmdline.join(QLatin1String("\r\n"));
1183         conf.postBuild.ExcludedFromBuild = _False;
1184     }
1185     if (!project->values("MSVCPROJ_COPY_DLL").isEmpty()) {
1186         conf.postBuild.Description += var("MSVCPROJ_COPY_DLL_DESC");
1187         conf.postBuild.CommandLine += var("MSVCPROJ_COPY_DLL");
1188         conf.postBuild.ExcludedFromBuild = _False;
1189     }
1190 }
1191 
initDeploymentTool()1192 void VcprojGenerator::initDeploymentTool()
1193 {
1194     VCConfiguration &conf = vcProject.Configuration;
1195     QString targetPath;
1196     if (conf.WinRT) {
1197         vcProject.DeploymentFiles.Name = "Deployment Files";
1198         vcProject.DeploymentFiles.ParseFiles = _False;
1199         vcProject.DeploymentFiles.Filter = "deploy";
1200         vcProject.DeploymentFiles.Guid = _GUIDDeploymentFiles;
1201     } else {
1202         targetPath = project->values("deploy.path").join(' ');
1203         if (targetPath.isEmpty())
1204             targetPath = QString("%CSIDL_PROGRAM_FILES%\\") + project->first("TARGET");
1205         if (targetPath.endsWith("/") || targetPath.endsWith("\\"))
1206             targetPath.chop(1);
1207         conf.deployment.RemoteDirectory = targetPath;
1208     }
1209     const ProStringList dllPaths = project->values("QMAKE_DLL_PATHS");
1210     // Only deploy Qt libs for shared build
1211     if (!dllPaths.isEmpty() &&
1212         !(conf.WinRT && project->first("MSVC_VER").toQString() == "14.0")) {
1213         // FIXME: This code should actually resolve the libraries from all Qt modules.
1214         ProStringList arg = project->values("LIBS") + project->values("LIBS_PRIVATE")
1215                 + project->values("QMAKE_LIBS") + project->values("QMAKE_LIBS_PRIVATE");
1216         bool qpaPluginDeployed = false;
1217         for (ProStringList::ConstIterator it = arg.constBegin(); it != arg.constEnd(); ++it) {
1218             QString dllName = (*it).toQString();
1219             dllName.replace(QLatin1Char('\\'), QLatin1Char('/'));
1220             // LIBPATH isn't relevant for deployment
1221             if (dllName.startsWith(QLatin1String("/LIBPATH:")))
1222                 continue;
1223             // We want to deploy .dlls not .libs
1224             if (dllName.endsWith(QLatin1String(".lib")))
1225                 dllName.replace(dllName.length() - 3, 3, QLatin1String("dll"));
1226             // Use only the file name and check in Qt's install path and LIBPATHs to check for existence
1227             dllName.remove(0, dllName.lastIndexOf(QLatin1Char('/')) + 1);
1228             QFileInfo info;
1229             for (const ProString &dllPath : dllPaths) {
1230                 QString absoluteDllFilePath = dllPath.toQString();
1231                 if (!absoluteDllFilePath.endsWith(QLatin1Char('/')))
1232                     absoluteDllFilePath += QLatin1Char('/');
1233                 absoluteDllFilePath += dllName;
1234                 info = QFileInfo(absoluteDllFilePath);
1235                 if (info.exists())
1236                     break;
1237             }
1238 
1239             if (!info.exists())
1240                 continue;
1241             if (conf.WinRT) {
1242                 QString absoluteFilePath(QDir::toNativeSeparators(info.absoluteFilePath()));
1243                 vcProject.DeploymentFiles.addFile(absoluteFilePath);
1244             } else {
1245                 conf.deployment.AdditionalFiles += info.fileName()
1246                         + "|" + QDir::toNativeSeparators(info.absolutePath())
1247                         + "|" + targetPath
1248                         + "|0;";
1249                 if (!qpaPluginDeployed) {
1250                     QString debugInfix;
1251                     bool foundGuid = dllName.contains(QLatin1String("Guid"));
1252                     if (foundGuid)
1253                         debugInfix = QLatin1Char('d');
1254 
1255                     if (foundGuid || dllName.contains(QLatin1String("Gui"))) {
1256                         QFileInfo info2;
1257                         for (const ProString &dllPath : dllPaths) {
1258                             QString absoluteDllFilePath = dllPath.toQString();
1259                             if (!absoluteDllFilePath.endsWith(QLatin1Char('/')))
1260                                 absoluteDllFilePath += QLatin1Char('/');
1261                             absoluteDllFilePath += QLatin1String("../plugins/platforms/qwindows")
1262                                     + debugInfix + QLatin1String(".dll");
1263                             info2 = QFileInfo(absoluteDllFilePath);
1264                             if (info2.exists())
1265                                 break;
1266                         }
1267                         if (info2.exists()) {
1268                             conf.deployment.AdditionalFiles += QLatin1String("qwindows") + debugInfix + QLatin1String(".dll")
1269                                                         + QLatin1Char('|') + QDir::toNativeSeparators(info2.absolutePath())
1270                                                         + QLatin1Char('|') + targetPath + QLatin1String("\\platforms")
1271                                                         + QLatin1String("|0;");
1272                             qpaPluginDeployed = true;
1273                         }
1274                     }
1275                 }
1276             }
1277         }
1278     }
1279 
1280     for (const ProString &item : project->values("INSTALLS")) {
1281         // get item.path
1282         QString devicePath = project->first(ProKey(item + ".path")).toQString();
1283         if (!conf.WinRT) {
1284             if (devicePath.isEmpty())
1285                 devicePath = targetPath;
1286             // check if item.path is relative (! either /,\ or %)
1287             if (!(devicePath.at(0) == QLatin1Char('/')
1288                 || devicePath.at(0) == QLatin1Char('\\')
1289                 || devicePath.at(0) == QLatin1Char('%'))) {
1290                 // create output path
1291                 devicePath = Option::fixPathToTargetOS(targetPath + QLatin1Char('\\') + devicePath);
1292             }
1293         }
1294         // foreach d in item.files
1295         for (const ProString &src : project->values(ProKey(item + ".files"))) {
1296             QString itemDevicePath = devicePath;
1297             QString source = Option::normalizePath(src.toQString());
1298             QString nameFilter;
1299             QFileInfo info(source);
1300             QString searchPath;
1301             if (info.isDir()) {
1302                 nameFilter = QLatin1String("*");
1303                 itemDevicePath += "\\" + info.fileName();
1304                 searchPath = info.absoluteFilePath();
1305             } else {
1306                 nameFilter = info.fileName();
1307                 searchPath = info.absolutePath();
1308             }
1309 
1310             int pathSize = searchPath.size();
1311             QDirIterator iterator(searchPath, QStringList() << nameFilter
1312                                   , QDir::Files | QDir::NoDotAndDotDot | QDir::NoSymLinks
1313                                   , QDirIterator::Subdirectories);
1314             // foreach dirIterator-entry in d
1315             while(iterator.hasNext()) {
1316                 iterator.next();
1317                 if (conf.WinRT) {
1318                     QString absoluteItemFilePath = Option::fixPathToTargetOS(QFileInfo(iterator.filePath()).absoluteFilePath());
1319                     vcProject.DeploymentFiles.addFile(absoluteItemFilePath);
1320                 } else {
1321                     QString absoluteItemPath = Option::fixPathToTargetOS(QFileInfo(iterator.filePath()).absolutePath());
1322                     // Identify if it is just another subdir
1323                     int diffSize = absoluteItemPath.size() - pathSize;
1324                     // write out rules
1325                     conf.deployment.AdditionalFiles += iterator.fileName()
1326                             + "|" + absoluteItemPath
1327                             + "|" + itemDevicePath + (diffSize ? (absoluteItemPath.right(diffSize)) : QLatin1String(""))
1328                             + "|0;";
1329                 }
1330             }
1331         }
1332 
1333         if (conf.WinRT) {
1334             vcProject.DeploymentFiles.Project = this;
1335             vcProject.DeploymentFiles.Config = &(vcProject.Configuration);
1336         }
1337     }
1338 }
1339 
initWinDeployQtTool()1340 void VcprojGenerator::initWinDeployQtTool()
1341 {
1342     VCConfiguration &conf = vcProject.Configuration;
1343     conf.windeployqt.ExcludedFromBuild = true;
1344     if (project->isActiveConfig("windeployqt")) {
1345         conf.windeployqt.Record = QStringLiteral("$(TargetName).windeployqt.$(Platform).$(Configuration)");
1346         const QString commandLine = MakefileGenerator::shellQuote(QDir::toNativeSeparators(project->first("QMAKE_WINDEPLOYQT").toQString()))
1347                 + QLatin1Char(' ') + project->values("WINDEPLOYQT_OPTIONS").join(QLatin1Char(' '));
1348 
1349         //  Visual Studio copies all files to be deployed into the MSIL directory
1350         //  and then invokes MDILXapCompile on it, which checks for managed code and
1351         //  translates it into native code. The problem is that all entries of the
1352         //  package will be copied into the MSIL directly, losing the subdirectory
1353         //  structure (for instance for plugins). However, the MDILXapCompile call
1354         //  itself contains the original subdirectories as parameters and hence the
1355         //  call fails.
1356         //  Hence the only way to get a build done is to recreate the directory
1357         //  structure manually by invoking windeployqt a second time, so that
1358         //  the MDILXapCompile call succeeds and deployment continues.
1359         conf.windeployqt.CommandLine += commandLine
1360                 + QStringLiteral(" -list relative -dir \"$(MSBuildProjectDirectory)\" \"$(OutDir)\\$(TargetFileName)\" > ")
1361                 + MakefileGenerator::shellQuote(conf.windeployqt.Record);
1362         conf.windeployqt.config = &vcProject.Configuration;
1363         conf.windeployqt.ExcludedFromBuild = false;
1364     }
1365 }
1366 
initPreLinkEventTools()1367 void VcprojGenerator::initPreLinkEventTools()
1368 {
1369     VCConfiguration &conf = vcProject.Configuration;
1370     if(!project->values("QMAKE_PRE_LINK").isEmpty()) {
1371         QStringList cmdline = VCToolBase::fixCommandLine(var("QMAKE_PRE_LINK"));
1372         conf.preLink.CommandLine = cmdline;
1373         conf.preLink.Description = cmdline.join(QLatin1String("\r\n"));
1374         conf.preLink.ExcludedFromBuild = _False;
1375     }
1376 }
1377 
initRootFiles()1378 void VcprojGenerator::initRootFiles()
1379 {
1380     // Note: Root files do _not_ have any filter name, filter nor GUID!
1381     vcProject.RootFiles.addFiles(project->values("RC_FILE"));
1382 
1383     vcProject.RootFiles.Project = this;
1384     vcProject.RootFiles.Config = &(vcProject.Configuration);
1385 }
1386 
initSourceFiles()1387 void VcprojGenerator::initSourceFiles()
1388 {
1389     vcProject.SourceFiles.Name = "Source Files";
1390     vcProject.SourceFiles.Filter = "cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx";
1391     vcProject.SourceFiles.Guid = _GUIDSourceFiles;
1392 
1393     vcProject.SourceFiles.addFiles(project->values("SOURCES"));
1394 
1395     vcProject.SourceFiles.Project = this;
1396     vcProject.SourceFiles.Config = &(vcProject.Configuration);
1397 }
1398 
initHeaderFiles()1399 void VcprojGenerator::initHeaderFiles()
1400 {
1401     vcProject.HeaderFiles.Name = "Header Files";
1402     vcProject.HeaderFiles.Filter = "h;hpp;hxx;hm;inl;inc;xsd";
1403     vcProject.HeaderFiles.Guid = _GUIDHeaderFiles;
1404 
1405     vcProject.HeaderFiles.addFiles(project->values("HEADERS"));
1406     if (usePCH) // Generated PCH cpp file
1407         vcProject.HeaderFiles.addFile(precompH);
1408 
1409     vcProject.HeaderFiles.Project = this;
1410     vcProject.HeaderFiles.Config = &(vcProject.Configuration);
1411 //    vcProject.HeaderFiles.CustomBuild = mocHdr;
1412 //    addMocArguments(vcProject.HeaderFiles);
1413 }
1414 
initGeneratedFiles()1415 void VcprojGenerator::initGeneratedFiles()
1416 {
1417     vcProject.GeneratedFiles.Name = "Generated Files";
1418     vcProject.GeneratedFiles.Filter = "cpp;c;cxx;moc;h;def;odl;idl;res;";
1419     vcProject.GeneratedFiles.Guid = _GUIDGeneratedFiles;
1420 
1421     // ### These cannot have CustomBuild (mocSrc)!!
1422     vcProject.GeneratedFiles.addFiles(project->values("GENERATED_SOURCES"));
1423     vcProject.GeneratedFiles.addFiles(project->values("GENERATED_FILES"));
1424     vcProject.GeneratedFiles.addFiles(project->values("IDLSOURCES"));
1425     if (project->values("RC_FILE").isEmpty())
1426         vcProject.GeneratedFiles.addFiles(project->values("RES_FILE"));
1427     if(!extraCompilerOutputs.isEmpty())
1428         vcProject.GeneratedFiles.addFiles(extraCompilerOutputs.keys());
1429 
1430     vcProject.GeneratedFiles.Project = this;
1431     vcProject.GeneratedFiles.Config = &(vcProject.Configuration);
1432 //    vcProject.GeneratedFiles.CustomBuild = mocSrc;
1433 }
1434 
initLexYaccFiles()1435 void VcprojGenerator::initLexYaccFiles()
1436 {
1437     vcProject.LexYaccFiles.Name = "Lex / Yacc Files";
1438     vcProject.LexYaccFiles.ParseFiles = _False;
1439     vcProject.LexYaccFiles.Filter = "l;y";
1440     vcProject.LexYaccFiles.Guid = _GUIDLexYaccFiles;
1441 
1442     vcProject.LexYaccFiles.addFiles(project->values("LEXSOURCES"));
1443     vcProject.LexYaccFiles.addFiles(project->values("YACCSOURCES"));
1444 
1445     vcProject.LexYaccFiles.Project = this;
1446     vcProject.LexYaccFiles.Config = &(vcProject.Configuration);
1447 }
1448 
initTranslationFiles()1449 void VcprojGenerator::initTranslationFiles()
1450 {
1451     vcProject.TranslationFiles.Name = "Translation Files";
1452     vcProject.TranslationFiles.ParseFiles = _False;
1453     vcProject.TranslationFiles.Filter = "ts;xlf";
1454     vcProject.TranslationFiles.Guid = _GUIDTranslationFiles;
1455 
1456     vcProject.TranslationFiles.addFiles(project->values("TRANSLATIONS"));
1457     vcProject.TranslationFiles.addFiles(project->values("EXTRA_TRANSLATIONS"));
1458 
1459     vcProject.TranslationFiles.Project = this;
1460     vcProject.TranslationFiles.Config = &(vcProject.Configuration);
1461 }
1462 
initFormFiles()1463 void VcprojGenerator::initFormFiles()
1464 {
1465     vcProject.FormFiles.Name = "Form Files";
1466     vcProject.FormFiles.ParseFiles = _False;
1467     vcProject.FormFiles.Filter = "ui";
1468     vcProject.FormFiles.Guid = _GUIDFormFiles;
1469     vcProject.FormFiles.addFiles(project->values("FORMS"));
1470     vcProject.FormFiles.Project = this;
1471     vcProject.FormFiles.Config = &(vcProject.Configuration);
1472 }
1473 
initResourceFiles()1474 void VcprojGenerator::initResourceFiles()
1475 {
1476     vcProject.ResourceFiles.Name = "Resource Files";
1477     vcProject.ResourceFiles.ParseFiles = _False;
1478     vcProject.ResourceFiles.Filter = "qrc;*"; //"rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;ts;xlf;qrc";
1479     vcProject.ResourceFiles.Guid = _GUIDResourceFiles;
1480 
1481     // Bad hack, please look away -------------------------------------
1482     QString rcc_dep_cmd = project->values("rcc.depend_command").join(' ');
1483     if(!rcc_dep_cmd.isEmpty()) {
1484         const QStringList qrc_files = project->values("RESOURCES").toQStringList();
1485         QStringList deps;
1486         for (const QString &qrc_file : qrc_files) {
1487             callExtraCompilerDependCommand("rcc",
1488                                            rcc_dep_cmd,
1489                                            qrc_file,
1490                                            QString(),
1491                                            true,  // dep_lines
1492                                            &deps,
1493                                            false, // existingDepsOnly
1494                                            true   // checkCommandavailability
1495                                           );
1496         }
1497         vcProject.ResourceFiles.addFiles(deps);
1498     }
1499     // You may look again --------------------------------------------
1500 
1501     vcProject.ResourceFiles.addFiles(project->values("RESOURCES"));
1502 
1503     vcProject.ResourceFiles.Project = this;
1504     vcProject.ResourceFiles.Config = &(vcProject.Configuration);
1505 }
1506 
initDistributionFiles()1507 void VcprojGenerator::initDistributionFiles()
1508 {
1509     vcProject.DistributionFiles.Name = "Distribution Files";
1510     vcProject.DistributionFiles.ParseFiles = _False;
1511     vcProject.DistributionFiles.Filter = "*";
1512     vcProject.DistributionFiles.Guid = _GUIDDistributionFiles;
1513     vcProject.DistributionFiles.addFiles(project->values("DISTFILES"));
1514     vcProject.DistributionFiles.Project = this;
1515     vcProject.DistributionFiles.Config = &(vcProject.Configuration);
1516 }
1517 
extraCompilerName(const ProString & extraCompiler,const QStringList & inputs,const QStringList & outputs)1518 QString VcprojGenerator::extraCompilerName(const ProString &extraCompiler,
1519                                              const QStringList &inputs,
1520                                              const QStringList &outputs)
1521 {
1522     QString name = project->values(ProKey(extraCompiler + ".name")).join(' ');
1523     if (name.isEmpty())
1524         name = extraCompiler.toQString();
1525     else
1526         name = replaceExtraCompilerVariables(name, inputs, outputs, NoShell);
1527     return name;
1528 }
1529 
initExtraCompilerOutputs()1530 void VcprojGenerator::initExtraCompilerOutputs()
1531 {
1532     ProStringList otherFilters;
1533     otherFilters << "FORMS"
1534                  << "GENERATED_FILES"
1535                  << "GENERATED_SOURCES"
1536                  << "HEADERS"
1537                  << "IDLSOURCES"
1538                  << "LEXSOURCES"
1539                  << "RC_FILE"
1540                  << "RESOURCES"
1541                  << "RES_FILE"
1542                  << "SOURCES"
1543                  << "TRANSLATIONS"
1544                  << "YACCSOURCES";
1545     const ProStringList &quc = project->values("QMAKE_EXTRA_COMPILERS");
1546     for (ProStringList::ConstIterator it = quc.begin(); it != quc.end(); ++it) {
1547         const ProStringList &inputVars = project->values(ProKey(*it + ".input"));
1548         ProStringList inputFiles;
1549         for (auto var : inputVars)
1550             inputFiles.append(project->values(var.toKey()));
1551         const ProStringList &outputs = project->values(ProKey(*it + ".output"));
1552 
1553         // Create an extra compiler filter and add the files
1554         VCFilter extraCompile;
1555         extraCompile.Name = extraCompilerName(it->toQString(), inputFiles.toQStringList(),
1556                                               outputs.toQStringList());
1557         extraCompile.ParseFiles = _False;
1558         extraCompile.Filter = "";
1559         extraCompile.Guid = QString(_GUIDExtraCompilerFiles) + "-" + (*it);
1560 
1561         bool addOnInput = hasBuiltinCompiler(firstExpandedOutputFileName(*it));
1562         if (!addOnInput) {
1563             // If the extra compiler has a variable_out set that is already handled
1564             // some other place, ignore it.
1565             const ProString &outputVar = project->first(ProKey(*it + ".variable_out"));
1566             if (!outputVar.isEmpty() && otherFilters.contains(outputVar))
1567                 continue;
1568 
1569             QString tmp_out;
1570             if (!outputs.isEmpty())
1571                 tmp_out = outputs.first().toQString();
1572             if (project->values(ProKey(*it + ".CONFIG")).indexOf("combine") != -1) {
1573                 // Combined output, only one file result
1574                 extraCompile.addFile(Option::fixPathToTargetOS(
1575                         replaceExtraCompilerVariables(tmp_out, QString(), QString(), NoShell), false));
1576             } else if (!inputVars.isEmpty()) {
1577                 // One output file per input
1578                 const ProStringList &tmp_in = project->values(inputVars.first().toKey());
1579                 for (int i = 0; i < tmp_in.count(); ++i) {
1580                     const QString &filename = tmp_in.at(i).toQString();
1581                     if (extraCompilerSources.contains(filename) && !otherFiltersContain(filename))
1582                         extraCompile.addFile(Option::fixPathToTargetOS(
1583                                 replaceExtraCompilerVariables(filename, tmp_out, QString(), NoShell), false));
1584                 }
1585             }
1586         } else {
1587             // In this case we the outputs have a built-in compiler, so we cannot add the custom
1588             // build steps there. So, we turn it around and add it to the input files instead,
1589             // provided that the input file variable is not handled already (those in otherFilters
1590             // are handled, so we avoid them).
1591             for (const ProString &inputVar : inputVars) {
1592                 if (!otherFilters.contains(inputVar)) {
1593                     const ProStringList &tmp_in = project->values(inputVar.toKey());
1594                     for (int i = 0; i < tmp_in.count(); ++i) {
1595                         const QString &filename = tmp_in.at(i).toQString();
1596                         if (extraCompilerSources.contains(filename) && !otherFiltersContain(filename))
1597                             extraCompile.addFile(Option::fixPathToTargetOS(
1598                                     replaceExtraCompilerVariables(filename, QString(), QString(), NoShell), false));
1599                     }
1600                 }
1601             }
1602         }
1603         extraCompile.Project = this;
1604         extraCompile.Config = &(vcProject.Configuration);
1605 
1606         vcProject.ExtraCompilersFiles.append(extraCompile);
1607     }
1608 }
1609 
otherFiltersContain(const QString & fileName) const1610 bool VcprojGenerator::otherFiltersContain(const QString &fileName) const
1611 {
1612     auto filterFileMatches = [&fileName] (const VCFilterFile &ff)
1613     {
1614         return ff.file == fileName;
1615     };
1616     for (const VCFilter *filter : { &vcProject.RootFiles,
1617                                     &vcProject.SourceFiles,
1618                                     &vcProject.HeaderFiles,
1619                                     &vcProject.GeneratedFiles,
1620                                     &vcProject.LexYaccFiles,
1621                                     &vcProject.TranslationFiles,
1622                                     &vcProject.FormFiles,
1623                                     &vcProject.ResourceFiles,
1624                                     &vcProject.DeploymentFiles,
1625                                     &vcProject.DistributionFiles}) {
1626         if (std::any_of(filter->Files.cbegin(), filter->Files.cend(), filterFileMatches))
1627             return true;
1628     }
1629     return false;
1630 }
1631 
1632 // ------------------------------------------------------------------------------------------------
1633 // ------------------------------------------------------------------------------------------------
1634 
createProjectWriter()1635 VCProjectWriter *VcprojGenerator::createProjectWriter()
1636 {
1637     return new VCProjectWriter;
1638 }
1639 
replaceExtraCompilerVariables(const QString & var,const QStringList & in,const QStringList & out,ReplaceFor forShell)1640 QString VcprojGenerator::replaceExtraCompilerVariables(
1641         const QString &var, const QStringList &in, const QStringList &out, ReplaceFor forShell)
1642 {
1643     QString ret = MakefileGenerator::replaceExtraCompilerVariables(var, in, out, forShell);
1644 
1645     ProStringList &defines = project->values("VCPROJ_MAKEFILE_DEFINES");
1646     if(defines.isEmpty())
1647         defines.append(varGlue("PRL_EXPORT_DEFINES"," -D"," -D","") +
1648                        varGlue("DEFINES"," -D"," -D",""));
1649     ret.replace(QLatin1String("$(DEFINES)"), defines.first().toQString());
1650 
1651     ProStringList &incpath = project->values("VCPROJ_MAKEFILE_INCPATH");
1652     if(incpath.isEmpty() && !this->var("MSVCPROJ_INCPATH").isEmpty())
1653         incpath.append(this->var("MSVCPROJ_INCPATH"));
1654     ret.replace(QLatin1String("$(INCPATH)"), incpath.join(' '));
1655 
1656     return ret;
1657 }
1658 
openOutput(QFile & file,const QString &) const1659 bool VcprojGenerator::openOutput(QFile &file, const QString &/*build*/) const
1660 {
1661     ProString fileName = file.fileName();
1662     ProString extension = project->first("TEMPLATE") == "vcsubdirs"
1663             ? project->first("VCSOLUTION_EXTENSION") : project->first("VCPROJ_EXTENSION");
1664     if (!fileName.endsWith(extension)) {
1665         if (fileName.isEmpty()) {
1666             fileName = !project->first("MAKEFILE").isEmpty()
1667                     ? project->first("MAKEFILE") : project->first("TARGET");
1668         }
1669         file.setFileName(fileName + extension);
1670     }
1671     return Win32MakefileGenerator::openOutput(file, QString());
1672 }
1673 
1674 QT_END_NAMESPACE
1675