unifiy initialization of QMAKE_LIBS{,_PRIVATE} among windows generators
[profile/ivi/qtbase.git] / qmake / generators / win32 / winmakefile.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
5 **
6 ** This file is part of the qmake application of the Qt Toolkit.
7 **
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** GNU Lesser General Public License Usage
10 ** This file may be used under the terms of the GNU Lesser General Public
11 ** License version 2.1 as published by the Free Software Foundation and
12 ** appearing in the file LICENSE.LGPL included in the packaging of this
13 ** file. Please review the following information to ensure the GNU Lesser
14 ** General Public License version 2.1 requirements will be met:
15 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
16 **
17 ** In addition, as a special exception, Nokia gives you certain additional
18 ** rights. These rights are described in the Nokia Qt LGPL Exception
19 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
20 **
21 ** GNU General Public License Usage
22 ** Alternatively, this file may be used under the terms of the GNU General
23 ** Public License version 3.0 as published by the Free Software Foundation
24 ** and appearing in the file LICENSE.GPL included in the packaging of this
25 ** file. Please review the following information to ensure the GNU General
26 ** Public License version 3.0 requirements will be met:
27 ** http://www.gnu.org/copyleft/gpl.html.
28 **
29 ** Other Usage
30 ** Alternatively, this file may be used in accordance with the terms and
31 ** conditions contained in a signed written agreement between you and Nokia.
32 **
33 **
34 **
35 **
36 **
37 **
38 ** $QT_END_LICENSE$
39 **
40 ****************************************************************************/
41
42 #include "winmakefile.h"
43 #include "option.h"
44 #include "project.h"
45 #include "meta.h"
46 #include <qtextstream.h>
47 #include <qstring.h>
48 #include <qhash.h>
49 #include <qregexp.h>
50 #include <qstringlist.h>
51 #include <qdir.h>
52 #include <stdlib.h>
53
54 QT_BEGIN_NAMESPACE
55
56 Win32MakefileGenerator::Win32MakefileGenerator() : MakefileGenerator()
57 {
58 }
59
60 int
61 Win32MakefileGenerator::findHighestVersion(const QString &d, const QString &stem, const QString &ext)
62 {
63     QString bd = Option::fixPathToLocalOS(d, true);
64     if(!exists(bd))
65         return -1;
66
67     QMakeMetaInfo libinfo;
68     bool libInfoRead = libinfo.readLib(bd + Option::dir_sep + stem);
69
70     // If the library, for which we're trying to find the highest version
71     // number, is a static library
72     if (libInfoRead && libinfo.values("QMAKE_PRL_CONFIG").contains("staticlib"))
73         return -1;
74
75     if(!project->values("QMAKE_" + stem.toUpper() + "_VERSION_OVERRIDE").isEmpty())
76         return project->values("QMAKE_" + stem.toUpper() + "_VERSION_OVERRIDE").first().toInt();
77
78     int biggest=-1;
79     if(!project->isActiveConfig("no_versionlink")) {
80         static QHash<QString, QStringList> dirEntryListCache;
81         QStringList entries = dirEntryListCache.value(bd);
82         if (entries.isEmpty()) {
83             QDir dir(bd);
84             entries = dir.entryList();
85             dirEntryListCache.insert(bd, entries);
86         }
87
88         QRegExp regx(QString("((lib)?%1([0-9]*)).(%2|prl)$").arg(stem).arg(ext), Qt::CaseInsensitive);
89         for(QStringList::Iterator it = entries.begin(); it != entries.end(); ++it) {
90             if(regx.exactMatch((*it))) {
91                                 if (!regx.cap(3).isEmpty()) {
92                                         bool ok = true;
93                                         int num = regx.cap(3).toInt(&ok);
94                                         biggest = qMax(biggest, (!ok ? -1 : num));
95                                 }
96                         }
97         }
98     }
99     if(libInfoRead
100        && !libinfo.values("QMAKE_PRL_CONFIG").contains("staticlib")
101        && !libinfo.isEmpty("QMAKE_PRL_VERSION"))
102        biggest = qMax(biggest, libinfo.first("QMAKE_PRL_VERSION").replace(".", "").toInt());
103     return biggest;
104 }
105
106 bool
107 Win32MakefileGenerator::findLibraries()
108 {
109     QList<QMakeLocalFileName> dirs;
110     {
111         const QStringList &libpaths = project->values("QMAKE_LIBDIR");
112         for (QStringList::ConstIterator libpathit = libpaths.begin();
113             libpathit != libpaths.end(); ++libpathit)
114             dirs.append(QMakeLocalFileName((*libpathit)));
115     }
116   const QString lflags[] = { "QMAKE_LIBS", "QMAKE_LIBS_PRIVATE", QString() };
117   for (int i = 0; !lflags[i].isNull(); i++) {
118     QStringList &l = project->values(lflags[i]);
119     for(QStringList::Iterator it = l.begin(); it != l.end();) {
120         QChar quote;
121         bool modified_opt = false, remove = false;
122         QString opt = (*it).trimmed();
123         if((opt[0] == '\'' || opt[0] == '"') && opt[(int)opt.length()-1] == opt[0]) {
124             quote = opt[0];
125             opt = opt.mid(1, opt.length()-2);
126         }
127         if(opt.startsWith("/LIBPATH:")) {
128             dirs.append(QMakeLocalFileName(opt.mid(9)));
129         } else if(opt.startsWith("-L") || opt.startsWith("/L")) {
130             QString libpath = opt.mid(2);
131             QMakeLocalFileName l(libpath);
132             if(!dirs.contains(l)) {
133                 dirs.append(l);
134                 modified_opt = true;
135                 if (!quote.isNull()) {
136                     libpath = quote + libpath + quote;
137                     quote = QChar();
138                 }
139                 (*it) = "/LIBPATH:" + libpath;
140             } else {
141                 remove = true;
142             }
143         } else if(opt.startsWith("-l") || opt.startsWith("/l")) {
144             QString lib = opt.right(opt.length() - 2), out;
145             if(!lib.isEmpty()) {
146                 QString suffix;
147                 if(!project->isEmpty("QMAKE_" + lib.toUpper() + "_SUFFIX"))
148                     suffix = project->first("QMAKE_" + lib.toUpper() + "_SUFFIX");
149                 for(QList<QMakeLocalFileName>::Iterator it = dirs.begin();
150                     it != dirs.end(); ++it) {
151                     QString extension;
152                     int ver = findHighestVersion((*it).local(), lib);
153                     if(ver > 0)
154                         extension += QString::number(ver);
155                     extension += suffix;
156                     extension += ".lib";
157                     if(QMakeMetaInfo::libExists((*it).local() + Option::dir_sep + lib) ||
158                        exists((*it).local() + Option::dir_sep + lib + extension)) {
159                         out = (*it).real() + Option::dir_sep + lib + extension;
160                         if (out.contains(QLatin1Char(' '))) {
161                             out.prepend(QLatin1Char('\"'));
162                             out.append(QLatin1Char('\"'));
163                         }
164                         break;
165                     }
166                 }
167             }
168             if(out.isEmpty())
169                 out = lib + ".lib";
170             modified_opt = true;
171             (*it) = out;
172         } else if(!exists(Option::fixPathToLocalOS(opt))) {
173             QList<QMakeLocalFileName> lib_dirs;
174             QString file = opt;
175             int slsh = file.lastIndexOf(Option::dir_sep);
176             if(slsh != -1) {
177                 lib_dirs.append(QMakeLocalFileName(file.left(slsh+1)));
178                 file = file.right(file.length() - slsh - 1);
179             } else {
180                 lib_dirs = dirs;
181             }
182             if(file.endsWith(".lib")) {
183                 file = file.left(file.length() - 4);
184                 if(!file.at(file.length()-1).isNumber()) {
185                     QString suffix;
186                     if(!project->isEmpty("QMAKE_" + file.section(Option::dir_sep, -1).toUpper() + "_SUFFIX"))
187                         suffix = project->first("QMAKE_" + file.section(Option::dir_sep, -1).toUpper() + "_SUFFIX");
188                     for(QList<QMakeLocalFileName>::Iterator dep_it = lib_dirs.begin(); dep_it != lib_dirs.end(); ++dep_it) {
189                         QString lib_tmpl(file + "%1" + suffix + ".lib");
190                         int ver = findHighestVersion((*dep_it).local(), file);
191                         if(ver != -1) {
192                             if(ver)
193                                 lib_tmpl = lib_tmpl.arg(ver);
194                             else
195                                 lib_tmpl = lib_tmpl.arg("");
196                             if(slsh != -1) {
197                                 QString dir = (*dep_it).real();
198                                 if(!dir.endsWith(Option::dir_sep))
199                                     dir += Option::dir_sep;
200                                 lib_tmpl.prepend(dir);
201                             }
202                             modified_opt = true;
203                             (*it) = lib_tmpl;
204                             break;
205                         }
206                     }
207                 }
208             }
209         }
210         if(remove) {
211             it = l.erase(it);
212         } else {
213             if(!quote.isNull() && modified_opt)
214                 (*it) = quote + (*it) + quote;
215             ++it;
216         }
217     }
218   }
219     return true;
220 }
221
222 void
223 Win32MakefileGenerator::processPrlFiles()
224 {
225     QHash<QString, bool> processed;
226     QList<QMakeLocalFileName> libdirs;
227     {
228         const QStringList &libpaths = project->values("QMAKE_LIBDIR");
229         for (QStringList::ConstIterator libpathit = libpaths.begin(); libpathit != libpaths.end(); ++libpathit)
230             libdirs.append(QMakeLocalFileName((*libpathit)));
231     }
232     for(bool ret = false; true; ret = false) {
233         //read in any prl files included..
234         QStringList l_out;
235         QStringList l = project->values("QMAKE_LIBS");
236         for(QStringList::Iterator it = l.begin(); it != l.end(); ++it) {
237             QString opt = (*it).trimmed();
238             if((opt[0] == '\'' || opt[0] == '"') && opt[(int)opt.length()-1] == opt[0])
239                 opt = opt.mid(1, opt.length()-2);
240             if(opt.startsWith("/")) {
241                 if(opt.startsWith("/LIBPATH:")) {
242                     QMakeLocalFileName l(opt.mid(9));
243                     if(!libdirs.contains(l))
244                         libdirs.append(l);
245                 }
246             } else if(!processed.contains(opt)) {
247                 if(processPrlFile(opt)) {
248                     processed.insert(opt, true);
249                     ret = true;
250                 } else if(QDir::isRelativePath(opt) || opt.startsWith("-l")) {
251                     QString tmp;
252                     if (opt.startsWith("-l"))
253                         tmp = opt.mid(2);
254                     else
255                         tmp = opt;
256                     for(QList<QMakeLocalFileName>::Iterator it = libdirs.begin(); it != libdirs.end(); ++it) {
257                         QString prl = (*it).local() + Option::dir_sep + tmp;
258                         // the original is used as the key
259                         QString orgprl = prl;
260                         if(processed.contains(prl)) {
261                             break;
262                         } else if(processPrlFile(prl)) {
263                             processed.insert(orgprl, true);
264                             ret = true;
265                             break;
266                         }
267                     }
268                 }
269             }
270             if(!opt.isEmpty())
271                 l_out.append(opt);
272         }
273         if(ret)
274             l = l_out;
275         else
276             break;
277     }
278 }
279
280
281 void Win32MakefileGenerator::processVars()
282 {
283     //If the TARGET looks like a path split it into DESTDIR and the resulting TARGET
284     if(!project->isEmpty("TARGET")) {
285         QString targ = project->first("TARGET");
286         int slsh = qMax(targ.lastIndexOf('/'), targ.lastIndexOf(Option::dir_sep));
287         if(slsh != -1) {
288             if(project->isEmpty("DESTDIR"))
289                 project->values("DESTDIR").append("");
290             else if(project->first("DESTDIR").right(1) != Option::dir_sep)
291                 project->values("DESTDIR") = QStringList(project->first("DESTDIR") + Option::dir_sep);
292             project->values("DESTDIR") = QStringList(project->first("DESTDIR") + targ.left(slsh+1));
293             project->values("TARGET") = QStringList(targ.mid(slsh+1));
294         }
295     }
296
297     project->values("QMAKE_ORIG_TARGET") = project->values("TARGET");
298     if (project->isEmpty("QMAKE_PROJECT_NAME"))
299         project->values("QMAKE_PROJECT_NAME") = project->values("QMAKE_ORIG_TARGET");
300     else if (project->first("TEMPLATE").startsWith("vc"))
301         project->values("MAKEFILE") = project->values("QMAKE_PROJECT_NAME");
302
303     if (!project->values("QMAKE_INCDIR").isEmpty())
304         project->values("INCLUDEPATH") += project->values("QMAKE_INCDIR");
305
306     if (!project->values("VERSION").isEmpty()) {
307         QStringList l = project->first("VERSION").split('.');
308         if (l.size() > 0)
309             project->values("VER_MAJ").append(l[0]);
310         if (l.size() > 1)
311             project->values("VER_MIN").append(l[1]);
312     }
313
314     // TARGET_VERSION_EXT will be used to add a version number onto the target name
315     if (project->values("TARGET_VERSION_EXT").isEmpty()
316         && !project->values("VER_MAJ").isEmpty())
317         project->values("TARGET_VERSION_EXT").append(project->values("VER_MAJ").first());
318
319     if(project->isEmpty("QMAKE_COPY_FILE"))
320         project->values("QMAKE_COPY_FILE").append("$(COPY)");
321     if(project->isEmpty("QMAKE_COPY_DIR"))
322         project->values("QMAKE_COPY_DIR").append("xcopy /s /q /y /i");
323     if(project->isEmpty("QMAKE_INSTALL_FILE"))
324         project->values("QMAKE_INSTALL_FILE").append("$(COPY_FILE)");
325     if(project->isEmpty("QMAKE_INSTALL_PROGRAM"))
326         project->values("QMAKE_INSTALL_PROGRAM").append("$(COPY_FILE)");
327     if(project->isEmpty("QMAKE_INSTALL_DIR"))
328         project->values("QMAKE_INSTALL_DIR").append("$(COPY_DIR)");
329
330     fixTargetExt();
331     processRcFileVar();
332     processFileTagsVar();
333
334     QStringList &incDir = project->values("INCLUDEPATH");
335     for(QStringList::Iterator incDir_it = incDir.begin(); incDir_it != incDir.end(); ++incDir_it) {
336     if(!(*incDir_it).isEmpty())
337         (*incDir_it) = Option::fixPathToTargetOS((*incDir_it), false, false);
338     }
339     QStringList &libDir = project->values("QMAKE_LIBDIR");
340     for(QStringList::Iterator libDir_it = libDir.begin(); libDir_it != libDir.end(); ++libDir_it) {
341     if(!(*libDir_it).isEmpty())
342         (*libDir_it) = Option::fixPathToTargetOS((*libDir_it), false, false);
343     }
344
345     project->values("QMAKE_LIBS") += escapeFilePaths(project->values("LIBS"));
346     project->values("QMAKE_LIBS_PRIVATE") += escapeFilePaths(project->values("LIBS_PRIVATE"));
347
348     if (project->values("TEMPLATE").contains("app")) {
349         project->values("QMAKE_CFLAGS") += project->values("QMAKE_CFLAGS_APP");
350         project->values("QMAKE_CXXFLAGS") += project->values("QMAKE_CXXFLAGS_APP");
351         project->values("QMAKE_LFLAGS") += project->values("QMAKE_LFLAGS_APP");
352     } else if (project->values("TEMPLATE").contains("lib") && project->isActiveConfig("dll")) {
353         if(!project->isActiveConfig("plugin") || !project->isActiveConfig("plugin_no_share_shlib_cflags")) {
354             project->values("QMAKE_CFLAGS") += project->values("QMAKE_CFLAGS_SHLIB");
355             project->values("QMAKE_CXXFLAGS") += project->values("QMAKE_CXXFLAGS_SHLIB");
356         }
357         if (project->isActiveConfig("plugin")) {
358             project->values("QMAKE_CFLAGS") += project->values("QMAKE_CFLAGS_PLUGIN");
359             project->values("QMAKE_CXXFLAGS") += project->values("QMAKE_CXXFLAGS_PLUGIN");
360             project->values("QMAKE_LFLAGS") += project->values("QMAKE_LFLAGS_PLUGIN");
361         } else {
362             project->values("QMAKE_LFLAGS") += project->values("QMAKE_LFLAGS_SHLIB");
363         }
364     }
365 }
366
367 void Win32MakefileGenerator::fixTargetExt()
368 {
369     if (project->isEmpty("QMAKE_EXTENSION_STATICLIB"))
370         project->values("QMAKE_EXTENSION_STATICLIB").append("lib");
371     if (project->isEmpty("QMAKE_EXTENSION_SHLIB"))
372         project->values("QMAKE_EXTENSION_SHLIB").append("dll");
373
374     if (!project->values("QMAKE_APP_FLAG").isEmpty()) {
375         project->values("TARGET_EXT").append(".exe");
376     } else if (project->isActiveConfig("shared")) {
377         project->values("TARGET_EXT").append(project->first("TARGET_VERSION_EXT") + "."
378                 + project->first("QMAKE_EXTENSION_SHLIB"));
379         project->values("TARGET").first() = project->first("QMAKE_PREFIX_SHLIB") + project->first("TARGET");
380     } else {
381         project->values("TARGET_EXT").append("." + project->first("QMAKE_EXTENSION_STATICLIB"));
382         project->values("TARGET").first() = project->first("QMAKE_PREFIX_STATICLIB") + project->first("TARGET");
383     }
384 }
385
386 void Win32MakefileGenerator::processRcFileVar()
387 {
388     if (Option::qmake_mode == Option::QMAKE_GENERATE_NOTHING)
389         return;
390
391     if (((!project->values("VERSION").isEmpty())
392         && project->values("RC_FILE").isEmpty()
393         && project->values("RES_FILE").isEmpty()
394         && !project->isActiveConfig("no_generated_target_info")
395         && (project->isActiveConfig("shared") || !project->values("QMAKE_APP_FLAG").isEmpty()))
396         || !project->values("QMAKE_WRITE_DEFAULT_RC").isEmpty()){
397
398         QByteArray rcString;
399         QTextStream ts(&rcString, QFile::WriteOnly);
400
401         QStringList vers = project->values("VERSION").first().split(".");
402         for (int i = vers.size(); i < 4; i++)
403             vers += "0";
404         QString versionString = vers.join(".");
405
406         QString companyName;
407         if (!project->values("QMAKE_TARGET_COMPANY").isEmpty())
408             companyName = project->values("QMAKE_TARGET_COMPANY").join(" ");
409
410         QString description;
411         if (!project->values("QMAKE_TARGET_DESCRIPTION").isEmpty())
412             description = project->values("QMAKE_TARGET_DESCRIPTION").join(" ");
413
414         QString copyright;
415         if (!project->values("QMAKE_TARGET_COPYRIGHT").isEmpty())
416             copyright = project->values("QMAKE_TARGET_COPYRIGHT").join(" ");
417
418         QString productName;
419         if (!project->values("QMAKE_TARGET_PRODUCT").isEmpty())
420             productName = project->values("QMAKE_TARGET_PRODUCT").join(" ");
421         else
422             productName = project->values("TARGET").first();
423
424         QString originalName = project->values("TARGET").first() + project->values("TARGET_EXT").first();
425         int rcLang = project->intValue("RC_LANG", 1033);            // default: English(USA)
426         int rcCodePage = project->intValue("RC_CODEPAGE", 1200);    // default: Unicode
427
428         ts << "# if defined(UNDER_CE)" << endl;
429         ts << "#  include <winbase.h>" << endl;
430         ts << "# else" << endl;
431         ts << "#  include <winver.h>" << endl;
432         ts << "# endif" << endl;
433         ts << endl;
434         ts << "VS_VERSION_INFO VERSIONINFO" << endl;
435         ts << "\tFILEVERSION " << QString(versionString).replace(".", ",") << endl;
436         ts << "\tPRODUCTVERSION " << QString(versionString).replace(".", ",") << endl;
437         ts << "\tFILEFLAGSMASK 0x3fL" << endl;
438         ts << "#ifdef _DEBUG" << endl;
439         ts << "\tFILEFLAGS VS_FF_DEBUG" << endl;
440         ts << "#else" << endl;
441         ts << "\tFILEFLAGS 0x0L" << endl;
442         ts << "#endif" << endl;
443         ts << "\tFILEOS VOS__WINDOWS32" << endl;
444         if (project->isActiveConfig("shared"))
445             ts << "\tFILETYPE VFT_DLL" << endl;
446         else
447             ts << "\tFILETYPE VFT_APP" << endl;
448         ts << "\tFILESUBTYPE 0x0L" << endl;
449         ts << "\tBEGIN" << endl;
450         ts << "\t\tBLOCK \"StringFileInfo\"" << endl;
451         ts << "\t\tBEGIN" << endl;
452         ts << "\t\t\tBLOCK \""
453            << QString("%1%2").arg(rcLang, 4, 16, QLatin1Char('0')).arg(rcCodePage, 4, 16, QLatin1Char('0'))
454            << "\"" << endl;
455         ts << "\t\t\tBEGIN" << endl;
456         ts << "\t\t\t\tVALUE \"CompanyName\", \"" << companyName << "\\0\"" << endl;
457         ts << "\t\t\t\tVALUE \"FileDescription\", \"" <<  description << "\\0\"" << endl;
458         ts << "\t\t\t\tVALUE \"FileVersion\", \"" << versionString << "\\0\"" << endl;
459         ts << "\t\t\t\tVALUE \"LegalCopyright\", \"" << copyright << "\\0\"" << endl;
460         ts << "\t\t\t\tVALUE \"OriginalFilename\", \"" << originalName << "\\0\"" << endl;
461         ts << "\t\t\t\tVALUE \"ProductName\", \"" << productName << "\\0\"" << endl;
462         ts << "\t\t\tEND" << endl;
463         ts << "\t\tEND" << endl;
464         ts << "\t\tBLOCK \"VarFileInfo\"" << endl;
465         ts << "\t\tBEGIN" << endl;
466         ts << "\t\t\tVALUE \"Translation\", "
467            << QString("0x%1").arg(rcLang, 4, 16, QLatin1Char('0'))
468            << ", " << QString("%1").arg(rcCodePage, 4) << endl;
469         ts << "\t\tEND" << endl;
470         ts << "\t\tBLOCK \"VarFileInfo\"" << endl;
471         ts << "\t\tBEGIN" << endl;
472         ts << "\t\t\tVALUE \"Translation\", 0x409, 1200" << endl;
473         ts << "\t\tEND" << endl;
474         ts << "\tEND" << endl;
475         ts << "/* End of Version info */" << endl;
476         ts << endl;
477
478         ts.flush();
479
480
481         QString rcFilename = project->values("OUT_PWD").first()
482                            + "/"
483                            + project->values("TARGET").first()
484                            + "_resource"
485                            + ".rc";
486         QFile rcFile(QDir::cleanPath(rcFilename));
487
488         bool writeRcFile = true;
489         if (rcFile.exists() && rcFile.open(QFile::ReadOnly)) {
490             writeRcFile = rcFile.readAll() != rcString;
491             rcFile.close();
492         }
493         if (writeRcFile) {
494             bool ok;
495             ok = rcFile.open(QFile::WriteOnly);
496             if (!ok) {
497                 // The file can't be opened... try creating the containing
498                 // directory first (needed for clean shadow builds)
499                 QDir().mkpath(QFileInfo(rcFile).path());
500                 ok = rcFile.open(QFile::WriteOnly);
501             }
502             if (!ok) {
503                 ::fprintf(stderr, "Cannot open for writing: %s", rcFile.fileName().toLatin1().constData());
504                 ::exit(1);
505             }
506             rcFile.write(rcString);
507             rcFile.close();
508         }
509         if (project->values("QMAKE_WRITE_DEFAULT_RC").isEmpty())
510             project->values("RC_FILE").insert(0, rcFile.fileName());
511     }
512     if (!project->values("RC_FILE").isEmpty()) {
513         if (!project->values("RES_FILE").isEmpty()) {
514             fprintf(stderr, "Both rc and res file specified.\n");
515             fprintf(stderr, "Please specify one of them, not both.");
516             exit(1);
517         }
518         QString resFile = project->values("RC_FILE").first();
519
520         // if this is a shadow build then use the absolute path of the rc file
521         if (Option::output_dir != qmake_getpwd()) {
522             QFileInfo fi(resFile);
523             project->values("RC_FILE").first() = fi.absoluteFilePath();
524         }
525
526         resFile.replace(".rc", Option::res_ext);
527         project->values("RES_FILE").prepend(fileInfo(resFile).fileName());
528         if (!project->values("OBJECTS_DIR").isEmpty()) {
529             QString resDestDir;
530             if (project->isActiveConfig("staticlib"))
531                 resDestDir = fileInfo(project->first("DESTDIR")).absoluteFilePath();
532             else
533                 resDestDir = project->first("OBJECTS_DIR");
534             resDestDir.append(Option::dir_sep);
535             project->values("RES_FILE").first().prepend(resDestDir);
536         }
537         project->values("RES_FILE").first() = Option::fixPathToTargetOS(project->values("RES_FILE").first(), false, false);
538         project->values("POST_TARGETDEPS") += project->values("RES_FILE");
539         project->values("CLEAN_FILES") += project->values("RES_FILE");
540     }
541 }
542
543 void Win32MakefileGenerator::processFileTagsVar()
544 {
545     QStringList tags;
546     tags << "SOURCES" << "GENERATED_SOURCES" << "DEF_FILE" << "RC_FILE"
547          << "TARGET" << "QMAKE_LIBS" << "DESTDIR" << "DLLDESTDIR" << "INCLUDEPATH";
548     if(!project->isEmpty("QMAKE_EXTRA_COMPILERS")) {
549         const QStringList &quc = project->values("QMAKE_EXTRA_COMPILERS");
550         for(QStringList::ConstIterator it = quc.begin(); it != quc.end(); ++it)
551             tags += project->values((*it)+".input");
552     }
553
554     //clean path
555     QStringList &filetags = project->values("QMAKE_FILETAGS");
556     for(int i = 0; i < tags.size(); ++i)
557         filetags += Option::fixPathToTargetOS(tags.at(i), false);
558 }
559
560 void Win32MakefileGenerator::writeCleanParts(QTextStream &t)
561 {
562     t << "clean: compiler_clean " << var("CLEAN_DEPS");
563     {
564         const char *clean_targets[] = { "OBJECTS", "QMAKE_CLEAN", "CLEAN_FILES", 0 };
565         for(int i = 0; clean_targets[i]; ++i) {
566             const QStringList &list = project->values(clean_targets[i]);
567             const QString del_statement("-$(DEL_FILE)");
568             if(project->isActiveConfig("no_delete_multiple_files")) {
569                 for(QStringList::ConstIterator it = list.begin(); it != list.end(); ++it)
570                     t << "\n\t" << del_statement << " " << escapeFilePath((*it));
571             } else {
572                 QString files, file;
573                 const int commandlineLimit = 2047; // NT limit, expanded
574                 for(QStringList::ConstIterator it = list.begin(); it != list.end(); ++it) {
575                     file = " " + escapeFilePath((*it));
576                     if(del_statement.length() + files.length() +
577                        qMax(fixEnvVariables(file).length(), file.length()) > commandlineLimit) {
578                         t << "\n\t" << del_statement << files;
579                         files.clear();
580                     }
581                     files += file;
582                 }
583                 if(!files.isEmpty())
584                     t << "\n\t" << del_statement << files;
585             }
586         }
587     }
588     t << endl << endl;
589
590     t << "distclean: clean";
591     {
592         const char *clean_targets[] = { "QMAKE_DISTCLEAN", 0 };
593         for(int i = 0; clean_targets[i]; ++i) {
594             const QStringList &list = project->values(clean_targets[i]);
595             const QString del_statement("-$(DEL_FILE)");
596             if(project->isActiveConfig("no_delete_multiple_files")) {
597                 for(QStringList::ConstIterator it = list.begin(); it != list.end(); ++it)
598                     t << "\n\t" << del_statement << " "
599                       << escapeFilePath(Option::fixPathToTargetOS(*it));
600             } else {
601                 QString files, file;
602                 const int commandlineLimit = 2047; // NT limit, expanded
603                 for(QStringList::ConstIterator it = list.begin(); it != list.end(); ++it) {
604                     file = " " + escapeFilePath(Option::fixPathToTargetOS(*it));
605                     if(del_statement.length() + files.length() +
606                        qMax(fixEnvVariables(file).length(), file.length()) > commandlineLimit) {
607                         t << "\n\t" << del_statement << files;
608                         files.clear();
609                     }
610                     files += file;
611                 }
612                 if(!files.isEmpty())
613                     t << "\n\t" << del_statement << files;
614             }
615         }
616     }
617     t << "\n\t-$(DEL_FILE) $(DESTDIR_TARGET)" << endl;
618     {
619         QString ofile = Option::fixPathToTargetOS(fileFixify(Option::output.fileName()));
620         if(!ofile.isEmpty())
621             t << "\t-$(DEL_FILE) " << ofile << endl;
622     }
623     t << endl;
624 }
625
626 void Win32MakefileGenerator::writeIncPart(QTextStream &t)
627 {
628     t << "INCPATH       = ";
629
630     const QStringList &incs = project->values("INCLUDEPATH");
631     for(int i = 0; i < incs.size(); ++i) {
632         QString inc = incs.at(i);
633         inc.replace(QRegExp("\\\\$"), "");
634         inc.replace(QRegExp("\""), "");
635         if(!inc.isEmpty())
636             t << "-I" << "\"" << inc << "\" ";
637     }
638     t << "-I\"" << specdir() << "\""
639       << endl;
640 }
641
642 void Win32MakefileGenerator::writeStandardParts(QTextStream &t)
643 {
644     t << "####### Compiler, tools and options" << endl << endl;
645     t << "CC            = " << var("QMAKE_CC") << endl;
646     t << "CXX           = " << var("QMAKE_CXX") << endl;
647     t << "DEFINES       = "
648       << varGlue("PRL_EXPORT_DEFINES","-D"," -D"," ")
649       << varGlue("DEFINES","-D"," -D","") << endl;
650     t << "CFLAGS        = " << var("QMAKE_CFLAGS") << " $(DEFINES)" << endl;
651     t << "CXXFLAGS      = " << var("QMAKE_CXXFLAGS") << " $(DEFINES)" << endl;
652
653     writeIncPart(t);
654     writeLibsPart(t);
655
656     t << "QMAKE         = " << var("QMAKE_QMAKE") << endl;
657     t << "IDC           = " << (project->isEmpty("QMAKE_IDC") ? QString("idc") :
658                               Option::fixPathToTargetOS(var("QMAKE_IDC"), false)) << endl;
659     t << "IDL           = " << (project->isEmpty("QMAKE_IDL") ? QString("midl") :
660                               Option::fixPathToTargetOS(var("QMAKE_IDL"), false)) << endl;
661     t << "ZIP           = " << var("QMAKE_ZIP") << endl;
662     t << "DEF_FILE      = " << varList("DEF_FILE") << endl;
663     t << "RES_FILE      = " << varList("RES_FILE") << endl; // Not on mingw, can't see why not though...
664     t << "COPY          = " << var("QMAKE_COPY") << endl;
665     t << "SED           = " << var("QMAKE_STREAM_EDITOR") << endl;
666     t << "COPY_FILE     = " << var("QMAKE_COPY_FILE") << endl;
667     t << "COPY_DIR      = " << var("QMAKE_COPY_DIR") << endl;
668     t << "DEL_FILE      = " << var("QMAKE_DEL_FILE") << endl;
669     t << "DEL_DIR       = " << var("QMAKE_DEL_DIR") << endl;
670     t << "MOVE          = " << var("QMAKE_MOVE") << endl;
671     t << "CHK_DIR_EXISTS= " << var("QMAKE_CHK_DIR_EXISTS") << endl;
672     t << "MKDIR         = " << var("QMAKE_MKDIR") << endl;
673     t << "INSTALL_FILE    = " << var("QMAKE_INSTALL_FILE") << endl;
674     t << "INSTALL_PROGRAM = " << var("QMAKE_INSTALL_PROGRAM") << endl;
675     t << "INSTALL_DIR     = " << var("QMAKE_INSTALL_DIR") << endl;
676     t << endl;
677
678     t << "####### Output directory" << endl << endl;
679     if(!project->values("OBJECTS_DIR").isEmpty())
680         t << "OBJECTS_DIR   = " << var("OBJECTS_DIR").replace(QRegExp("\\\\$"),"") << endl;
681     else
682         t << "OBJECTS_DIR   = . " << endl;
683     t << endl;
684
685     t << "####### Files" << endl << endl;
686     t << "SOURCES       = " << valList(escapeFilePaths(project->values("SOURCES")))
687       << " " << valList(escapeFilePaths(project->values("GENERATED_SOURCES"))) << endl;
688
689     // do this here so we can set DEST_TARGET to be the complete path to the final target if it is needed.
690     QString orgDestDir = var("DESTDIR");
691     QString destDir = Option::fixPathToTargetOS(orgDestDir, false);
692     if (!destDir.isEmpty() && (orgDestDir.endsWith('/') || orgDestDir.endsWith(Option::dir_sep)))
693         destDir += Option::dir_sep;
694     QString target = QString(project->first("TARGET")+project->first("TARGET_EXT"));
695     target.remove("\"");
696     project->values("DEST_TARGET").prepend(destDir + target);
697
698     writeObjectsPart(t);
699
700     writeExtraCompilerVariables(t);
701     writeExtraVariables(t);
702
703     t << "DIST          = " << varList("DISTFILES") << endl;
704     t << "QMAKE_TARGET  = " << var("QMAKE_ORIG_TARGET") << endl;
705     // The comment is important to maintain variable compatibility with Unix
706     // Makefiles, while not interpreting a trailing-slash as a linebreak
707     t << "DESTDIR        = " << escapeFilePath(destDir) << " #avoid trailing-slash linebreak" << endl;
708     t << "TARGET         = " << escapeFilePath(target) << endl;
709     t << "DESTDIR_TARGET = " << escapeFilePath(var("DEST_TARGET")) << endl;
710     t << endl;
711
712     t << "####### Implicit rules" << endl << endl;
713     writeImplicitRulesPart(t);
714
715     t << "####### Build rules" << endl << endl;
716     writeBuildRulesPart(t);
717
718     if(project->isActiveConfig("shared") && !project->values("DLLDESTDIR").isEmpty()) {
719         QStringList dlldirs = project->values("DLLDESTDIR");
720         for (QStringList::Iterator dlldir = dlldirs.begin(); dlldir != dlldirs.end(); ++dlldir) {
721             t << "\t" << "-$(COPY_FILE) \"$(DESTDIR_TARGET)\" " << Option::fixPathToTargetOS(*dlldir, false) << endl;
722         }
723     }
724     t << endl;
725
726     writeRcFilePart(t);
727
728     writeMakeQmake(t);
729
730     QStringList dist_files = fileFixify(Option::mkfile::project_files);
731     if(!project->isEmpty("QMAKE_INTERNAL_INCLUDED_FILES"))
732         dist_files += project->values("QMAKE_INTERNAL_INCLUDED_FILES");
733     if(!project->isEmpty("TRANSLATIONS"))
734         dist_files << var("TRANSLATIONS");
735     if(!project->isEmpty("FORMS")) {
736         const QStringList &forms = project->values("FORMS");
737         for (QStringList::ConstIterator formit = forms.begin(); formit != forms.end(); ++formit) {
738             QString ui_h = fileFixify((*formit) + Option::h_ext.first());
739             if(exists(ui_h))
740                 dist_files << ui_h;
741         }
742     }
743     t << "dist:" << "\n\t"
744       << "$(ZIP) " << var("QMAKE_ORIG_TARGET") << ".zip " << "$(SOURCES) $(DIST) "
745       << dist_files.join(" ") << " " << var("TRANSLATIONS") << " ";
746     if(!project->isEmpty("QMAKE_EXTRA_COMPILERS")) {
747         const QStringList &quc = project->values("QMAKE_EXTRA_COMPILERS");
748         for(QStringList::ConstIterator it = quc.begin(); it != quc.end(); ++it) {
749             const QStringList &inputs = project->values((*it)+".input");
750             for(QStringList::ConstIterator input = inputs.begin(); input != inputs.end(); ++input) {
751                 t << (*input) << " ";
752             }
753         }
754     }
755     t << endl << endl;
756
757     writeCleanParts(t);
758     writeExtraTargets(t);
759     writeExtraCompilerTargets(t);
760     t << endl << endl;
761 }
762
763 void Win32MakefileGenerator::writeLibsPart(QTextStream &t)
764 {
765     if(project->isActiveConfig("staticlib") && project->first("TEMPLATE") == "lib") {
766         t << "LIBAPP        = " << var("QMAKE_LIB") << endl;
767         t << "LIBFLAGS      = " << var("QMAKE_LIBFLAGS") << endl;
768     } else {
769         t << "LINK          = " << var("QMAKE_LINK") << endl;
770         t << "LFLAGS        = " << var("QMAKE_LFLAGS") << endl;
771         t << "LIBS          = ";
772         if(!project->values("QMAKE_LIBDIR").isEmpty())
773             writeLibDirPart(t);
774         t << var("QMAKE_LIBS") << " " << var("QMAKE_LIBS_PRIVATE") << endl;
775     }
776 }
777
778 void Win32MakefileGenerator::writeLibDirPart(QTextStream &t)
779 {
780     QStringList libDirs = project->values("QMAKE_LIBDIR");
781     for (int i = 0; i < libDirs.size(); ++i)
782         libDirs[i].remove("\"");
783     t << valGlue(libDirs,"-L\"","\" -L\"","\"") << " ";
784 }
785
786 void Win32MakefileGenerator::writeObjectsPart(QTextStream &t)
787 {
788     t << "OBJECTS       = " << valList(escapeDependencyPaths(project->values("OBJECTS"))) << endl;
789 }
790
791 void Win32MakefileGenerator::writeImplicitRulesPart(QTextStream &t)
792 {
793     t << ".SUFFIXES:";
794     for(QStringList::Iterator cppit = Option::cpp_ext.begin(); cppit != Option::cpp_ext.end(); ++cppit)
795         t << " " << (*cppit);
796     for(QStringList::Iterator cit = Option::c_ext.begin(); cit != Option::c_ext.end(); ++cit)
797         t << " " << (*cit);
798     t << endl << endl;
799     for(QStringList::Iterator cppit = Option::cpp_ext.begin(); cppit != Option::cpp_ext.end(); ++cppit)
800         t << (*cppit) << Option::obj_ext << ":\n\t" << var("QMAKE_RUN_CXX_IMP") << endl << endl;
801     for(QStringList::Iterator cit = Option::c_ext.begin(); cit != Option::c_ext.end(); ++cit)
802         t << (*cit) << Option::obj_ext << ":\n\t" << var("QMAKE_RUN_CC_IMP") << endl << endl;
803 }
804
805 void Win32MakefileGenerator::writeBuildRulesPart(QTextStream &)
806 {
807 }
808
809 void Win32MakefileGenerator::writeRcFilePart(QTextStream &t)
810 {
811     if(!project->values("RC_FILE").isEmpty()) {
812         const QString res_file = project->first("RES_FILE"),
813                        rc_file = fileFixify(project->first("RC_FILE"));
814         // The resource tool needs to have the same defines passed in as the compiler, since you may
815         // use these defines in the .rc file itself. Also, we need to add the _DEBUG define manually
816         // since the compiler defines this symbol by itself, and we use it in the automatically
817         // created rc file when VERSION is define the .pro file.
818         t << res_file << ": " << rc_file << "\n\t"
819           << var("QMAKE_RC") << (project->isActiveConfig("debug") ? " -D_DEBUG" : "") << " $(DEFINES) -fo " << res_file << " " << rc_file;
820         t << endl << endl;
821     }
822 }
823
824 QString Win32MakefileGenerator::getLibTarget()
825 {
826     return QString(project->first("TARGET") + project->first("TARGET_VERSION_EXT") + ".lib");
827 }
828
829 QString Win32MakefileGenerator::defaultInstall(const QString &t)
830 {
831     if((t != "target" && t != "dlltarget") ||
832        (t == "dlltarget" && (project->first("TEMPLATE") != "lib" || !project->isActiveConfig("shared"))) ||
833         project->first("TEMPLATE") == "subdirs")
834        return QString();
835
836     const QString root = "$(INSTALL_ROOT)";
837     QStringList &uninst = project->values(t + ".uninstall");
838     QString ret;
839     QString targetdir = Option::fixPathToTargetOS(project->first(t + ".path"), false);
840     targetdir = fileFixify(targetdir, FileFixifyAbsolute);
841     if(targetdir.right(1) != Option::dir_sep)
842         targetdir += Option::dir_sep;
843
844     if(t == "target" && project->first("TEMPLATE") == "lib") {
845         if(project->isActiveConfig("create_prl") && !project->isActiveConfig("no_install_prl") &&
846            !project->isEmpty("QMAKE_INTERNAL_PRL_FILE")) {
847             QString dst_prl = Option::fixPathToTargetOS(project->first("QMAKE_INTERNAL_PRL_FILE"));
848             int slsh = dst_prl.lastIndexOf(Option::dir_sep);
849             if(slsh != -1)
850                 dst_prl = dst_prl.right(dst_prl.length() - slsh - 1);
851             dst_prl = filePrefixRoot(root, targetdir + dst_prl);
852             ret += "-$(INSTALL_FILE) \"" + project->first("QMAKE_INTERNAL_PRL_FILE") + "\" \"" + dst_prl + "\"";
853             if(!uninst.isEmpty())
854                 uninst.append("\n\t");
855             uninst.append("-$(DEL_FILE) \"" + dst_prl + "\"");
856         }
857         if(project->isActiveConfig("create_pc")) {
858             QString dst_pc = pkgConfigFileName(false);
859             if (!dst_pc.isEmpty()) {
860                 dst_pc = filePrefixRoot(root, targetdir + dst_pc);
861                 const QString dst_pc_dir = fileInfo(dst_pc).path();
862                 if (!dst_pc_dir.isEmpty()) {
863                     if (!ret.isEmpty())
864                         ret += "\n\t";
865                     ret += mkdir_p_asstring(dst_pc_dir, true);
866                 }
867                 if(!ret.isEmpty())
868                     ret += "\n\t";
869                 const QString replace_rule("QMAKE_PKGCONFIG_INSTALL_REPLACE");
870                 if (project->isEmpty(replace_rule)
871                     || project->isActiveConfig("no_sed_meta_install")
872                     || project->isEmpty("QMAKE_STREAM_EDITOR")) {
873                     ret += "-$(INSTALL_FILE) \"" + pkgConfigFileName(true) + "\" \"" + dst_pc + "\"";
874                 } else {
875                     ret += "-$(SED)";
876                     QStringList replace_rules = project->values(replace_rule);
877                     for (int r = 0; r < replace_rules.size(); ++r) {
878                         const QString match = project->first(replace_rules.at(r) + ".match"),
879                                     replace = project->first(replace_rules.at(r) + ".replace");
880                         if (!match.isEmpty() /*&& match != replace*/)
881                             ret += " -e \"s," + match + "," + replace + ",g\"";
882                     }
883                     ret += " \"" + pkgConfigFileName(true) + "\" >\"" + dst_pc + "\"";
884                 }
885                 if(!uninst.isEmpty())
886                     uninst.append("\n\t");
887                 uninst.append("-$(DEL_FILE) \"" + dst_pc + "\"");
888             }
889         }
890         if(project->isActiveConfig("shared") && !project->isActiveConfig("plugin")) {
891             QString lib_target = getLibTarget();
892             lib_target.remove('"');
893             QString src_targ = (project->isEmpty("DESTDIR") ? QString("$(DESTDIR)") : project->first("DESTDIR")) + lib_target;
894             QString dst_targ = filePrefixRoot(root, fileFixify(targetdir + lib_target, FileFixifyAbsolute));
895             if(!ret.isEmpty())
896                 ret += "\n\t";
897             ret += QString("-$(INSTALL_FILE)") + " \"" + src_targ + "\" \"" + dst_targ + "\"";
898             if(!uninst.isEmpty())
899                 uninst.append("\n\t");
900             uninst.append("-$(DEL_FILE) \"" + dst_targ + "\"");
901         }
902     }
903
904     if(t == "dlltarget" || project->values(t + ".CONFIG").indexOf("no_dll") == -1) {
905         QString src_targ = "$(DESTDIR_TARGET)";
906         QString dst_targ = filePrefixRoot(root, fileFixify(targetdir + "$(TARGET)", FileFixifyAbsolute));
907         if(!ret.isEmpty())
908             ret += "\n\t";
909         ret += QString("-$(INSTALL_FILE)") + " \"" + src_targ + "\" \"" + dst_targ + "\"";
910         if(!uninst.isEmpty())
911             uninst.append("\n\t");
912         uninst.append("-$(DEL_FILE) \"" + dst_targ + "\"");
913     }
914     return ret;
915 }
916
917 QString Win32MakefileGenerator::escapeFilePath(const QString &path) const
918 {
919     QString ret = path;
920     if(!ret.isEmpty()) {
921         ret = unescapeFilePath(ret);
922         if(ret.contains(" "))
923             ret = "\"" + ret + "\"";
924         debug_msg(2, "EscapeFilePath: %s -> %s", path.toLatin1().constData(), ret.toLatin1().constData());
925     }
926     return ret;
927 }
928
929 QT_END_NAMESPACE