cmQtAutomoc.cxx 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086
  1. /*============================================================================
  2. CMake - Cross Platform Makefile Generator
  3. Copyright 2004-2011 Kitware, Inc.
  4. Copyright 2011 Alexander Neundorf ([email protected])
  5. Distributed under the OSI-approved BSD License (the "License");
  6. see accompanying file Copyright.txt for details.
  7. This software is distributed WITHOUT ANY WARRANTY; without even the
  8. implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  9. See the License for more information.
  10. ============================================================================*/
  11. #include "cmGlobalGenerator.h"
  12. #include "cmLocalGenerator.h"
  13. #include "cmMakefile.h"
  14. #include "cmSourceFile.h"
  15. #include "cmSystemTools.h"
  16. #include <cmsys/Terminal.h>
  17. #include <cmsys/ios/sstream>
  18. #include <string.h>
  19. #if defined(__APPLE__)
  20. #include <unistd.h>
  21. #endif
  22. #include "cmQtAutomoc.h"
  23. static bool containsQ_OBJECT(const std::string& text)
  24. {
  25. // this simple check is much much faster than the regexp
  26. if (strstr(text.c_str(), "Q_OBJECT") == NULL)
  27. {
  28. return false;
  29. }
  30. cmsys::RegularExpression qObjectRegExp("[\n][ \t]*Q_OBJECT[^a-zA-Z0-9_]");
  31. return qObjectRegExp.find(text);
  32. }
  33. static std::string findMatchingHeader(const std::string& absPath,
  34. const std::string& mocSubDir,
  35. const std::string& basename,
  36. const std::list<std::string>& headerExtensions)
  37. {
  38. std::string header;
  39. for(std::list<std::string>::const_iterator ext = headerExtensions.begin();
  40. ext != headerExtensions.end();
  41. ++ext)
  42. {
  43. std::string sourceFilePath = absPath + basename + (*ext);
  44. if (cmsys::SystemTools::FileExists(sourceFilePath.c_str()))
  45. {
  46. header = sourceFilePath;
  47. break;
  48. }
  49. if (!mocSubDir.empty())
  50. {
  51. sourceFilePath = mocSubDir + basename + (*ext);
  52. if (cmsys::SystemTools::FileExists(sourceFilePath.c_str()))
  53. {
  54. header = sourceFilePath;
  55. break;
  56. }
  57. }
  58. }
  59. return header;
  60. }
  61. static std::string extractSubDir(const std::string& absPath,
  62. const std::string& currentMoc)
  63. {
  64. std::string subDir;
  65. if (currentMoc.find_first_of('/') != std::string::npos)
  66. {
  67. subDir = absPath
  68. + cmsys::SystemTools::GetFilenamePath(currentMoc) + '/';
  69. }
  70. return subDir;
  71. }
  72. cmQtAutomoc::cmQtAutomoc()
  73. :Verbose(cmsys::SystemTools::GetEnv("VERBOSE") != 0)
  74. ,ColorOutput(true)
  75. ,RunMocFailed(false)
  76. ,GenerateAll(false)
  77. {
  78. std::string colorEnv = "";
  79. cmsys::SystemTools::GetEnv("COLOR", colorEnv);
  80. if(!colorEnv.empty())
  81. {
  82. if(cmSystemTools::IsOn(colorEnv.c_str()))
  83. {
  84. this->ColorOutput = true;
  85. }
  86. else
  87. {
  88. this->ColorOutput = false;
  89. }
  90. }
  91. }
  92. void cmQtAutomoc::SetupAutomocTarget(cmTarget* target)
  93. {
  94. cmMakefile* makefile = target->GetMakefile();
  95. const char* targetName = target->GetName();
  96. // don't do anything if there is no Qt4 or Qt5Core (which contains moc):
  97. std::string qtMajorVersion = makefile->GetSafeDefinition("QT_VERSION_MAJOR");
  98. if (qtMajorVersion == "")
  99. {
  100. qtMajorVersion = makefile->GetSafeDefinition("Qt5Core_VERSION_MAJOR");
  101. }
  102. if (qtMajorVersion != "4" && qtMajorVersion != "5")
  103. {
  104. return;
  105. }
  106. bool relaxedMode = makefile->IsOn("CMAKE_AUTOMOC_RELAXED_MODE");
  107. // create a custom target for running automoc at buildtime:
  108. std::string automocTargetName = targetName;
  109. automocTargetName += "_automoc";
  110. std::string targetDir = makefile->GetCurrentOutputDirectory();
  111. targetDir += makefile->GetCMakeInstance()->GetCMakeFilesDirectory();
  112. targetDir += "/";
  113. targetDir += automocTargetName;
  114. targetDir += ".dir/";
  115. cmCustomCommandLine currentLine;
  116. currentLine.push_back(makefile->GetSafeDefinition("CMAKE_COMMAND"));
  117. currentLine.push_back("-E");
  118. currentLine.push_back("cmake_automoc");
  119. currentLine.push_back(targetDir);
  120. cmCustomCommandLines commandLines;
  121. commandLines.push_back(currentLine);
  122. std::string workingDirectory = cmSystemTools::CollapseFullPath(
  123. "", makefile->GetCurrentOutputDirectory());
  124. std::vector<std::string> depends;
  125. std::string automocComment = "Automoc for target ";
  126. automocComment += targetName;
  127. makefile->AddUtilityCommand(automocTargetName.c_str(), true,
  128. workingDirectory.c_str(), depends,
  129. commandLines, false, automocComment.c_str());
  130. target->AddUtility(automocTargetName.c_str());
  131. // configure a file to get all information to automoc at buildtime:
  132. std::string _moc_files;
  133. std::string _moc_headers;
  134. const char* sepFiles = "";
  135. const char* sepHeaders = "";
  136. const std::vector<cmSourceFile*>& srcFiles = target->GetSourceFiles();
  137. for(std::vector<cmSourceFile*>::const_iterator fileIt = srcFiles.begin();
  138. fileIt != srcFiles.end();
  139. ++fileIt)
  140. {
  141. cmSourceFile* sf = *fileIt;
  142. std::string absFile = sf->GetFullPath();
  143. bool skip = cmSystemTools::IsOn(sf->GetPropertyForUser("SKIP_AUTOMOC"));
  144. bool generated = cmSystemTools::IsOn(sf->GetPropertyForUser("GENERATED"));
  145. if ((skip==false) && (generated == false))
  146. {
  147. std::string ext = sf->GetExtension();
  148. cmSystemTools::FileFormat fileType = cmSystemTools::GetFileFormat(
  149. ext.c_str());
  150. if (fileType == cmSystemTools::CXX_FILE_FORMAT)
  151. {
  152. _moc_files += sepFiles;
  153. _moc_files += absFile;
  154. sepFiles = ";";
  155. }
  156. else if (fileType == cmSystemTools::HEADER_FILE_FORMAT)
  157. {
  158. _moc_headers += sepHeaders;
  159. _moc_headers += absFile;
  160. sepHeaders = ";";
  161. }
  162. }
  163. }
  164. const char* tmp = makefile->GetProperty("INCLUDE_DIRECTORIES");
  165. std::string _moc_incs = (tmp!=0 ? tmp : "");
  166. tmp = makefile->GetProperty("DEFINITIONS");
  167. std::string _moc_defs = (tmp!=0 ? tmp : "");
  168. tmp = makefile->GetProperty("COMPILE_DEFINITIONS");
  169. std::string _moc_compile_defs = (tmp!=0 ? tmp : "");
  170. tmp = target->GetProperty("AUTOMOC_MOC_OPTIONS");
  171. std::string _moc_options = (tmp!=0 ? tmp : "");
  172. // forget the variables added here afterwards again:
  173. cmMakefile::ScopePushPop varScope(makefile);
  174. static_cast<void>(varScope);
  175. makefile->AddDefinition("_moc_target_name",
  176. cmLocalGenerator::EscapeForCMake(automocTargetName.c_str()).c_str());
  177. makefile->AddDefinition("_moc_incs",
  178. cmLocalGenerator::EscapeForCMake(_moc_incs.c_str()).c_str());
  179. makefile->AddDefinition("_moc_defs",
  180. cmLocalGenerator::EscapeForCMake(_moc_defs.c_str()).c_str());
  181. makefile->AddDefinition("_moc_compile_defs",
  182. cmLocalGenerator::EscapeForCMake(_moc_compile_defs.c_str()).c_str());
  183. makefile->AddDefinition("_moc_options",
  184. cmLocalGenerator::EscapeForCMake(_moc_options.c_str()).c_str());
  185. makefile->AddDefinition("_moc_files",
  186. cmLocalGenerator::EscapeForCMake(_moc_files.c_str()).c_str());
  187. makefile->AddDefinition("_moc_headers",
  188. cmLocalGenerator::EscapeForCMake(_moc_headers.c_str()).c_str());
  189. makefile->AddDefinition("_moc_relaxed_mode", relaxedMode ? "TRUE" : "FALSE");
  190. const char* cmakeRoot = makefile->GetSafeDefinition("CMAKE_ROOT");
  191. std::string inputFile = cmakeRoot;
  192. inputFile += "/Modules/AutomocInfo.cmake.in";
  193. std::string outputFile = targetDir;
  194. outputFile += "/AutomocInfo.cmake";
  195. makefile->ConfigureFile(inputFile.c_str(), outputFile.c_str(),
  196. false, true, false);
  197. std::string mocCppFile = makefile->GetCurrentOutputDirectory();
  198. mocCppFile += "/";
  199. mocCppFile += automocTargetName;
  200. mocCppFile += ".cpp";
  201. cmSourceFile* mocCppSource = makefile->GetOrCreateSource(mocCppFile.c_str(),
  202. true);
  203. target->AddSourceFile(mocCppSource);
  204. makefile->AppendProperty("ADDITIONAL_MAKE_CLEAN_FILES",
  205. mocCppFile.c_str(), false);
  206. }
  207. bool cmQtAutomoc::Run(const char* targetDirectory)
  208. {
  209. bool success = true;
  210. cmake cm;
  211. cmGlobalGenerator* gg = this->CreateGlobalGenerator(&cm, targetDirectory);
  212. cmMakefile* makefile = gg->GetCurrentLocalGenerator()->GetMakefile();
  213. this->ReadAutomocInfoFile(makefile, targetDirectory);
  214. this->ReadOldMocDefinitionsFile(makefile, targetDirectory);
  215. this->Init();
  216. if (this->QtMajorVersion == "4" || this->QtMajorVersion == "5")
  217. {
  218. success = this->RunAutomoc();
  219. }
  220. this->WriteOldMocDefinitionsFile(targetDirectory);
  221. delete gg;
  222. gg = NULL;
  223. makefile = NULL;
  224. return success;
  225. }
  226. cmGlobalGenerator* cmQtAutomoc::CreateGlobalGenerator(cmake* cm,
  227. const char* targetDirectory)
  228. {
  229. cmGlobalGenerator* gg = new cmGlobalGenerator();
  230. gg->SetCMakeInstance(cm);
  231. cmLocalGenerator* lg = gg->CreateLocalGenerator();
  232. lg->GetMakefile()->SetHomeOutputDirectory(targetDirectory);
  233. lg->GetMakefile()->SetStartOutputDirectory(targetDirectory);
  234. lg->GetMakefile()->SetHomeDirectory(targetDirectory);
  235. lg->GetMakefile()->SetStartDirectory(targetDirectory);
  236. gg->SetCurrentLocalGenerator(lg);
  237. return gg;
  238. }
  239. bool cmQtAutomoc::ReadAutomocInfoFile(cmMakefile* makefile,
  240. const char* targetDirectory)
  241. {
  242. std::string filename(cmSystemTools::CollapseFullPath(targetDirectory));
  243. cmSystemTools::ConvertToUnixSlashes(filename);
  244. filename += "/AutomocInfo.cmake";
  245. if (!makefile->ReadListFile(0, filename.c_str()))
  246. {
  247. cmSystemTools::Error("Error processing file:", filename.c_str());
  248. return false;
  249. }
  250. this->QtMajorVersion = makefile->GetSafeDefinition("AM_QT_VERSION_MAJOR");
  251. if (this->QtMajorVersion == "")
  252. {
  253. this->QtMajorVersion = makefile->GetSafeDefinition(
  254. "AM_Qt5Core_VERSION_MAJOR");
  255. }
  256. this->Sources = makefile->GetSafeDefinition("AM_SOURCES");
  257. this->Headers = makefile->GetSafeDefinition("AM_HEADERS");
  258. this->IncludeProjectDirsBefore = makefile->IsOn(
  259. "AM_CMAKE_INCLUDE_DIRECTORIES_PROJECT_BEFORE");
  260. this->Srcdir = makefile->GetSafeDefinition("AM_CMAKE_CURRENT_SOURCE_DIR");
  261. this->Builddir = makefile->GetSafeDefinition("AM_CMAKE_CURRENT_BINARY_DIR");
  262. this->MocExecutable = makefile->GetSafeDefinition("AM_QT_MOC_EXECUTABLE");
  263. this->MocCompileDefinitionsStr = makefile->GetSafeDefinition(
  264. "AM_MOC_COMPILE_DEFINITIONS");
  265. this->MocDefinitionsStr = makefile->GetSafeDefinition("AM_MOC_DEFINITIONS");
  266. this->MocIncludesStr = makefile->GetSafeDefinition("AM_MOC_INCLUDES");
  267. this->MocOptionsStr = makefile->GetSafeDefinition("AM_MOC_OPTIONS");
  268. this->ProjectBinaryDir = makefile->GetSafeDefinition("AM_CMAKE_BINARY_DIR");
  269. this->ProjectSourceDir = makefile->GetSafeDefinition("AM_CMAKE_SOURCE_DIR");
  270. this->TargetName = makefile->GetSafeDefinition("AM_TARGET_NAME");
  271. this->RelaxedMode = makefile->IsOn("AM_RELAXED_MODE");
  272. return true;
  273. }
  274. bool cmQtAutomoc::ReadOldMocDefinitionsFile(cmMakefile* makefile,
  275. const char* targetDirectory)
  276. {
  277. std::string filename(cmSystemTools::CollapseFullPath(targetDirectory));
  278. cmSystemTools::ConvertToUnixSlashes(filename);
  279. filename += "/AutomocOldMocDefinitions.cmake";
  280. if (makefile->ReadListFile(0, filename.c_str()))
  281. {
  282. this->OldMocDefinitionsStr =
  283. makefile->GetSafeDefinition("AM_OLD_MOC_DEFINITIONS");
  284. }
  285. return true;
  286. }
  287. void cmQtAutomoc::WriteOldMocDefinitionsFile(const char* targetDirectory)
  288. {
  289. std::string filename(cmSystemTools::CollapseFullPath(targetDirectory));
  290. cmSystemTools::ConvertToUnixSlashes(filename);
  291. filename += "/AutomocOldMocDefinitions.cmake";
  292. std::fstream outfile;
  293. outfile.open(filename.c_str(),
  294. std::ios::out | std::ios::trunc);
  295. outfile << "set(AM_OLD_MOC_DEFINITIONS "
  296. << cmLocalGenerator::EscapeForCMake(
  297. this->Join(this->MocDefinitions, ' ').c_str()) << ")\n";
  298. outfile.close();
  299. }
  300. void cmQtAutomoc::Init()
  301. {
  302. this->OutMocCppFilename = this->Builddir;
  303. this->OutMocCppFilename += this->TargetName;
  304. this->OutMocCppFilename += ".cpp";
  305. std::vector<std::string> cdefList;
  306. cmSystemTools::ExpandListArgument(this->MocCompileDefinitionsStr, cdefList);
  307. if (!cdefList.empty())
  308. {
  309. for(std::vector<std::string>::const_iterator it = cdefList.begin();
  310. it != cdefList.end();
  311. ++it)
  312. {
  313. this->MocDefinitions.push_back("-D" + (*it));
  314. }
  315. }
  316. else
  317. {
  318. std::string tmpMocDefs = this->MocDefinitionsStr;
  319. cmSystemTools::ReplaceString(tmpMocDefs, " ", ";");
  320. std::vector<std::string> defList;
  321. cmSystemTools::ExpandListArgument(tmpMocDefs, defList);
  322. for(std::vector<std::string>::const_iterator it = defList.begin();
  323. it != defList.end();
  324. ++it)
  325. {
  326. if (this->StartsWith(*it, "-D"))
  327. {
  328. this->MocDefinitions.push_back(*it);
  329. }
  330. }
  331. }
  332. cmSystemTools::ExpandListArgument(this->MocOptionsStr, this->MocOptions);
  333. std::vector<std::string> incPaths;
  334. cmSystemTools::ExpandListArgument(this->MocIncludesStr, incPaths);
  335. std::set<std::string> frameworkPaths;
  336. for(std::vector<std::string>::const_iterator it = incPaths.begin();
  337. it != incPaths.end();
  338. ++it)
  339. {
  340. const std::string &path = *it;
  341. this->MocIncludes.push_back("-I" + path);
  342. if (this->EndsWith(path, ".framework/Headers"))
  343. {
  344. // Go up twice to get to the framework root
  345. std::vector<std::string> pathComponents;
  346. cmsys::SystemTools::SplitPath(path.c_str(), pathComponents);
  347. std::string frameworkPath =cmsys::SystemTools::JoinPath(
  348. pathComponents.begin(), pathComponents.end() - 2);
  349. frameworkPaths.insert(frameworkPath);
  350. }
  351. }
  352. for (std::set<std::string>::const_iterator it = frameworkPaths.begin();
  353. it != frameworkPaths.end(); ++it)
  354. {
  355. this->MocIncludes.push_back("-F");
  356. this->MocIncludes.push_back(*it);
  357. }
  358. if (this->IncludeProjectDirsBefore)
  359. {
  360. const std::string &binDir = "-I" + this->ProjectBinaryDir;
  361. const std::string srcDir = "-I" + this->ProjectSourceDir;
  362. std::list<std::string> sortedMocIncludes;
  363. std::list<std::string>::iterator it = this->MocIncludes.begin();
  364. while (it != this->MocIncludes.end())
  365. {
  366. if (this->StartsWith(*it, binDir))
  367. {
  368. sortedMocIncludes.push_back(*it);
  369. it = this->MocIncludes.erase(it);
  370. }
  371. else
  372. {
  373. ++it;
  374. }
  375. }
  376. it = this->MocIncludes.begin();
  377. while (it != this->MocIncludes.end())
  378. {
  379. if (this->StartsWith(*it, srcDir))
  380. {
  381. sortedMocIncludes.push_back(*it);
  382. it = this->MocIncludes.erase(it);
  383. }
  384. else
  385. {
  386. ++it;
  387. }
  388. }
  389. sortedMocIncludes.insert(sortedMocIncludes.end(),
  390. this->MocIncludes.begin(), this->MocIncludes.end());
  391. this->MocIncludes = sortedMocIncludes;
  392. }
  393. }
  394. bool cmQtAutomoc::RunAutomoc()
  395. {
  396. if (!cmsys::SystemTools::FileExists(this->OutMocCppFilename.c_str())
  397. || (this->OldMocDefinitionsStr != this->Join(this->MocDefinitions, ' ')))
  398. {
  399. this->GenerateAll = true;
  400. }
  401. // the program goes through all .cpp files to see which moc files are
  402. // included. It is not really interesting how the moc file is named, but
  403. // what file the moc is created from. Once a moc is included the same moc
  404. // may not be included in the _automoc.cpp file anymore. OTOH if there's a
  405. // header containing Q_OBJECT where no corresponding moc file is included
  406. // anywhere a moc_<filename>.cpp file is created and included in
  407. // the _automoc.cpp file.
  408. // key = moc source filepath, value = moc output filepath
  409. std::map<std::string, std::string> includedMocs;
  410. // collect all headers which may need to be mocced
  411. std::set<std::string> headerFiles;
  412. std::vector<std::string> sourceFiles;
  413. cmSystemTools::ExpandListArgument(this->Sources, sourceFiles);
  414. std::list<std::string> headerExtensions;
  415. headerExtensions.push_back(".h");
  416. headerExtensions.push_back(".hpp");
  417. headerExtensions.push_back(".hxx");
  418. #if defined(_WIN32)
  419. // not case sensitive, don't add ".H"
  420. #elif defined(__APPLE__)
  421. // detect case-sensitive filesystem
  422. long caseSensitive = pathconf(this->Srcdir.c_str(), _PC_CASE_SENSITIVE);
  423. if (caseSensitive == 1)
  424. {
  425. headerExtensions.push_back(".H");
  426. }
  427. #else
  428. headerExtensions.push_back(".H");
  429. #endif
  430. for (std::vector<std::string>::const_iterator it = sourceFiles.begin();
  431. it != sourceFiles.end();
  432. ++it)
  433. {
  434. const std::string &absFilename = *it;
  435. if (this->Verbose)
  436. {
  437. std::cout << "AUTOMOC: Checking " << absFilename << std::endl;
  438. }
  439. if (this->RelaxedMode)
  440. {
  441. this->ParseCppFile(absFilename, headerExtensions, includedMocs);
  442. }
  443. else
  444. {
  445. this->StrictParseCppFile(absFilename, headerExtensions, includedMocs);
  446. }
  447. this->SearchHeadersForCppFile(absFilename, headerExtensions, headerFiles);
  448. }
  449. std::vector<std::string> headerFilesVec;
  450. cmSystemTools::ExpandListArgument(this->Headers, headerFilesVec);
  451. for (std::vector<std::string>::const_iterator it = headerFilesVec.begin();
  452. it != headerFilesVec.end();
  453. ++it)
  454. {
  455. headerFiles.insert(*it);
  456. }
  457. // key = moc source filepath, value = moc output filename
  458. std::map<std::string, std::string> notIncludedMocs;
  459. this->ParseHeaders(headerFiles, includedMocs, notIncludedMocs);
  460. // run moc on all the moc's that are #included in source files
  461. for(std::map<std::string, std::string>::const_iterator
  462. it = includedMocs.begin();
  463. it != includedMocs.end();
  464. ++it)
  465. {
  466. this->GenerateMoc(it->first, it->second);
  467. }
  468. cmsys_ios::stringstream outStream;
  469. outStream << "/* This file is autogenerated, do not edit*/\n";
  470. bool automocCppChanged = false;
  471. if (notIncludedMocs.empty())
  472. {
  473. outStream << "enum some_compilers { need_more_than_nothing };\n";
  474. }
  475. else
  476. {
  477. // run moc on the remaining headers and include them in
  478. // the _automoc.cpp file
  479. for(std::map<std::string, std::string>::const_iterator
  480. it = notIncludedMocs.begin();
  481. it != notIncludedMocs.end();
  482. ++it)
  483. {
  484. bool mocSuccess = this->GenerateMoc(it->first, it->second);
  485. if (mocSuccess)
  486. {
  487. automocCppChanged = true;
  488. }
  489. outStream << "#include \"" << it->second << "\"\n";
  490. }
  491. }
  492. if (this->RunMocFailed)
  493. {
  494. std::cerr << "moc failed..."<< std::endl;
  495. return false;
  496. }
  497. outStream.flush();
  498. std::string automocSource = outStream.str();
  499. if (!automocCppChanged)
  500. {
  501. // compare contents of the _automoc.cpp file
  502. const std::string oldContents = this->ReadAll(this->OutMocCppFilename);
  503. if (oldContents == automocSource)
  504. {
  505. // nothing changed: don't touch the _automoc.cpp file
  506. return true;
  507. }
  508. }
  509. // source file that includes all remaining moc files (_automoc.cpp file)
  510. std::fstream outfile;
  511. outfile.open(this->OutMocCppFilename.c_str(),
  512. std::ios::out | std::ios::trunc);
  513. outfile << automocSource;
  514. outfile.close();
  515. return true;
  516. }
  517. void cmQtAutomoc::ParseCppFile(const std::string& absFilename,
  518. const std::list<std::string>& headerExtensions,
  519. std::map<std::string, std::string>& includedMocs)
  520. {
  521. cmsys::RegularExpression mocIncludeRegExp(
  522. "[\n][ \t]*#[ \t]*include[ \t]+"
  523. "[\"<](([^ \">]+/)?moc_[^ \">/]+\\.cpp|[^ \">]+\\.moc)[\">]");
  524. const std::string contentsString = this->ReadAll(absFilename);
  525. if (contentsString.empty())
  526. {
  527. std::cerr << "AUTOMOC: warning: " << absFilename << ": file is empty\n"
  528. << std::endl;
  529. return;
  530. }
  531. const std::string absPath = cmsys::SystemTools::GetFilenamePath(
  532. cmsys::SystemTools::GetRealPath(absFilename.c_str())) + '/';
  533. const std::string scannedFileBasename = cmsys::SystemTools::
  534. GetFilenameWithoutLastExtension(absFilename);
  535. const bool cppContainsQ_OBJECT = containsQ_OBJECT(contentsString);
  536. bool dotMocIncluded = false;
  537. bool mocUnderscoreIncluded = false;
  538. std::string ownMocUnderscoreFile;
  539. std::string ownDotMocFile;
  540. std::string ownMocHeaderFile;
  541. std::string::size_type matchOffset = 0;
  542. // first a simply string check for "moc" is *much* faster than the regexp,
  543. // and if the string search already fails, we don't have to try the
  544. // expensive regexp
  545. if ((strstr(contentsString.c_str(), "moc") != NULL)
  546. && (mocIncludeRegExp.find(contentsString)))
  547. {
  548. // for every moc include in the file
  549. do
  550. {
  551. const std::string currentMoc = mocIncludeRegExp.match(1);
  552. //std::cout << "found moc include: " << currentMoc << std::endl;
  553. std::string basename = cmsys::SystemTools::
  554. GetFilenameWithoutLastExtension(currentMoc);
  555. const bool moc_style = this->StartsWith(basename, "moc_");
  556. // If the moc include is of the moc_foo.cpp style we expect
  557. // the Q_OBJECT class declaration in a header file.
  558. // If the moc include is of the foo.moc style we need to look for
  559. // a Q_OBJECT macro in the current source file, if it contains the
  560. // macro we generate the moc file from the source file.
  561. // Q_OBJECT
  562. if (moc_style)
  563. {
  564. // basename should be the part of the moc filename used for
  565. // finding the correct header, so we need to remove the moc_ part
  566. basename = basename.substr(4);
  567. std::string mocSubDir = extractSubDir(absPath, currentMoc);
  568. std::string headerToMoc = findMatchingHeader(
  569. absPath, mocSubDir, basename, headerExtensions);
  570. if (!headerToMoc.empty())
  571. {
  572. includedMocs[headerToMoc] = currentMoc;
  573. if (basename == scannedFileBasename)
  574. {
  575. mocUnderscoreIncluded = true;
  576. ownMocUnderscoreFile = currentMoc;
  577. ownMocHeaderFile = headerToMoc;
  578. }
  579. }
  580. else
  581. {
  582. std::cerr << "AUTOMOC: error: " << absFilename << " The file "
  583. << "includes the moc file \"" << currentMoc << "\", "
  584. << "but could not find header \"" << basename
  585. << '{' << this->Join(headerExtensions, ',') << "}\" ";
  586. if (mocSubDir.empty())
  587. {
  588. std::cerr << "in " << absPath << "\n" << std::endl;
  589. }
  590. else
  591. {
  592. std::cerr << "neither in " << absPath
  593. << " nor in " << mocSubDir << "\n" << std::endl;
  594. }
  595. ::exit(EXIT_FAILURE);
  596. }
  597. }
  598. else
  599. {
  600. std::string fileToMoc = absFilename;
  601. if ((basename != scannedFileBasename) || (cppContainsQ_OBJECT==false))
  602. {
  603. std::string mocSubDir = extractSubDir(absPath, currentMoc);
  604. std::string headerToMoc = findMatchingHeader(
  605. absPath, mocSubDir, basename, headerExtensions);
  606. if (!headerToMoc.empty())
  607. {
  608. // this is for KDE4 compatibility:
  609. fileToMoc = headerToMoc;
  610. if ((cppContainsQ_OBJECT==false) &&(basename==scannedFileBasename))
  611. {
  612. std::cerr << "AUTOMOC: warning: " << absFilename << ": The file "
  613. "includes the moc file \"" << currentMoc <<
  614. "\", but does not contain a Q_OBJECT macro. "
  615. "Running moc on "
  616. << "\"" << headerToMoc << "\" ! Include \"moc_"
  617. << basename << ".cpp\" for a compatiblity with "
  618. "strict mode (see CMAKE_AUTOMOC_RELAXED_MODE).\n"
  619. << std::endl;
  620. }
  621. else
  622. {
  623. std::cerr << "AUTOMOC: warning: " << absFilename << ": The file "
  624. "includes the moc file \"" << currentMoc <<
  625. "\" instead of \"moc_" << basename << ".cpp\". "
  626. "Running moc on "
  627. << "\"" << headerToMoc << "\" ! Include \"moc_"
  628. << basename << ".cpp\" for compatiblity with "
  629. "strict mode (see CMAKE_AUTOMOC_RELAXED_MODE).\n"
  630. << std::endl;
  631. }
  632. }
  633. else
  634. {
  635. std::cerr <<"AUTOMOC: error: " << absFilename << ": The file "
  636. "includes the moc file \"" << currentMoc <<
  637. "\", which seems to be the moc file from a different "
  638. "source file. CMake also could not find a matching "
  639. "header.\n" << std::endl;
  640. ::exit(EXIT_FAILURE);
  641. }
  642. }
  643. else
  644. {
  645. dotMocIncluded = true;
  646. ownDotMocFile = currentMoc;
  647. }
  648. includedMocs[fileToMoc] = currentMoc;
  649. }
  650. matchOffset += mocIncludeRegExp.end();
  651. } while(mocIncludeRegExp.find(contentsString.c_str() + matchOffset));
  652. }
  653. // In this case, check whether the scanned file itself contains a Q_OBJECT.
  654. // If this is the case, the moc_foo.cpp should probably be generated from
  655. // foo.cpp instead of foo.h, because otherwise it won't build.
  656. // But warn, since this is not how it is supposed to be used.
  657. if ((dotMocIncluded == false) && (cppContainsQ_OBJECT == true))
  658. {
  659. if (mocUnderscoreIncluded == true)
  660. {
  661. // this is for KDE4 compatibility:
  662. std::cerr << "AUTOMOC: warning: " << absFilename << ": The file "
  663. << "contains a Q_OBJECT macro, but does not include "
  664. << "\"" << scannedFileBasename << ".moc\", but instead "
  665. "includes "
  666. << "\"" << ownMocUnderscoreFile << "\". Running moc on "
  667. << "\"" << absFilename << "\" ! Better include \""
  668. << scannedFileBasename << ".moc\" for compatiblity with "
  669. "strict mode (see CMAKE_AUTOMOC_RELAXED_MODE).\n"
  670. << std::endl;
  671. includedMocs[absFilename] = ownMocUnderscoreFile;
  672. includedMocs.erase(ownMocHeaderFile);
  673. }
  674. else
  675. {
  676. // otherwise always error out since it will not compile:
  677. std::cerr << "AUTOMOC: error: " << absFilename << ": The file "
  678. << "contains a Q_OBJECT macro, but does not include "
  679. << "\"" << scannedFileBasename << ".moc\" !\n"
  680. << std::endl;
  681. ::exit(EXIT_FAILURE);
  682. }
  683. }
  684. }
  685. void cmQtAutomoc::StrictParseCppFile(const std::string& absFilename,
  686. const std::list<std::string>& headerExtensions,
  687. std::map<std::string, std::string>& includedMocs)
  688. {
  689. cmsys::RegularExpression mocIncludeRegExp(
  690. "[\n][ \t]*#[ \t]*include[ \t]+"
  691. "[\"<](([^ \">]+/)?moc_[^ \">/]+\\.cpp|[^ \">]+\\.moc)[\">]");
  692. const std::string contentsString = this->ReadAll(absFilename);
  693. if (contentsString.empty())
  694. {
  695. std::cerr << "AUTOMOC: warning: " << absFilename << ": file is empty\n"
  696. << std::endl;
  697. return;
  698. }
  699. const std::string absPath = cmsys::SystemTools::GetFilenamePath(
  700. cmsys::SystemTools::GetRealPath(absFilename.c_str())) + '/';
  701. const std::string scannedFileBasename = cmsys::SystemTools::
  702. GetFilenameWithoutLastExtension(absFilename);
  703. bool dotMocIncluded = false;
  704. std::string::size_type matchOffset = 0;
  705. // first a simply string check for "moc" is *much* faster than the regexp,
  706. // and if the string search already fails, we don't have to try the
  707. // expensive regexp
  708. if ((strstr(contentsString.c_str(), "moc") != NULL)
  709. && (mocIncludeRegExp.find(contentsString)))
  710. {
  711. // for every moc include in the file
  712. do
  713. {
  714. const std::string currentMoc = mocIncludeRegExp.match(1);
  715. std::string basename = cmsys::SystemTools::
  716. GetFilenameWithoutLastExtension(currentMoc);
  717. const bool mocUnderscoreStyle = this->StartsWith(basename, "moc_");
  718. // If the moc include is of the moc_foo.cpp style we expect
  719. // the Q_OBJECT class declaration in a header file.
  720. // If the moc include is of the foo.moc style we need to look for
  721. // a Q_OBJECT macro in the current source file, if it contains the
  722. // macro we generate the moc file from the source file.
  723. if (mocUnderscoreStyle)
  724. {
  725. // basename should be the part of the moc filename used for
  726. // finding the correct header, so we need to remove the moc_ part
  727. basename = basename.substr(4);
  728. std::string mocSubDir = extractSubDir(absPath, currentMoc);
  729. std::string headerToMoc = findMatchingHeader(
  730. absPath, mocSubDir, basename, headerExtensions);
  731. if (!headerToMoc.empty())
  732. {
  733. includedMocs[headerToMoc] = currentMoc;
  734. }
  735. else
  736. {
  737. std::cerr << "AUTOMOC: error: " << absFilename << " The file "
  738. << "includes the moc file \"" << currentMoc << "\", "
  739. << "but could not find header \"" << basename
  740. << '{' << this->Join(headerExtensions, ',') << "}\" ";
  741. if (mocSubDir.empty())
  742. {
  743. std::cerr << "in " << absPath << "\n" << std::endl;
  744. }
  745. else
  746. {
  747. std::cerr << "neither in " << absPath
  748. << " nor in " << mocSubDir << "\n" << std::endl;
  749. }
  750. ::exit(EXIT_FAILURE);
  751. }
  752. }
  753. else
  754. {
  755. if (basename != scannedFileBasename)
  756. {
  757. std::cerr <<"AUTOMOC: error: " << absFilename << ": The file "
  758. "includes the moc file \"" << currentMoc <<
  759. "\", which seems to be the moc file from a different "
  760. "source file. This is not supported. "
  761. "Include \"" << scannedFileBasename << ".moc\" to run "
  762. "moc on this source file.\n" << std::endl;
  763. ::exit(EXIT_FAILURE);
  764. }
  765. dotMocIncluded = true;
  766. includedMocs[absFilename] = currentMoc;
  767. }
  768. matchOffset += mocIncludeRegExp.end();
  769. } while(mocIncludeRegExp.find(contentsString.c_str() + matchOffset));
  770. }
  771. // In this case, check whether the scanned file itself contains a Q_OBJECT.
  772. // If this is the case, the moc_foo.cpp should probably be generated from
  773. // foo.cpp instead of foo.h, because otherwise it won't build.
  774. // But warn, since this is not how it is supposed to be used.
  775. if ((dotMocIncluded == false) && (containsQ_OBJECT(contentsString)))
  776. {
  777. // otherwise always error out since it will not compile:
  778. std::cerr << "AUTOMOC: error: " << absFilename << ": The file "
  779. << "contains a Q_OBJECT macro, but does not include "
  780. << "\"" << scannedFileBasename << ".moc\" !\n"
  781. << std::endl;
  782. ::exit(EXIT_FAILURE);
  783. }
  784. }
  785. void cmQtAutomoc::SearchHeadersForCppFile(const std::string& absFilename,
  786. const std::list<std::string>& headerExtensions,
  787. std::set<std::string>& absHeaders)
  788. {
  789. // search for header files and private header files we may need to moc:
  790. const std::string basename =
  791. cmsys::SystemTools::GetFilenameWithoutLastExtension(absFilename);
  792. const std::string absPath = cmsys::SystemTools::GetFilenamePath(
  793. cmsys::SystemTools::GetRealPath(absFilename.c_str())) + '/';
  794. for(std::list<std::string>::const_iterator ext = headerExtensions.begin();
  795. ext != headerExtensions.end();
  796. ++ext)
  797. {
  798. const std::string headerName = absPath + basename + (*ext);
  799. if (cmsys::SystemTools::FileExists(headerName.c_str()))
  800. {
  801. absHeaders.insert(headerName);
  802. break;
  803. }
  804. }
  805. for(std::list<std::string>::const_iterator ext = headerExtensions.begin();
  806. ext != headerExtensions.end();
  807. ++ext)
  808. {
  809. const std::string privateHeaderName = absPath+basename+"_p"+(*ext);
  810. if (cmsys::SystemTools::FileExists(privateHeaderName.c_str()))
  811. {
  812. absHeaders.insert(privateHeaderName);
  813. break;
  814. }
  815. }
  816. }
  817. void cmQtAutomoc::ParseHeaders(const std::set<std::string>& absHeaders,
  818. const std::map<std::string, std::string>& includedMocs,
  819. std::map<std::string, std::string>& notIncludedMocs)
  820. {
  821. for(std::set<std::string>::const_iterator hIt=absHeaders.begin();
  822. hIt!=absHeaders.end();
  823. ++hIt)
  824. {
  825. const std::string& headerName = *hIt;
  826. if (includedMocs.find(headerName) == includedMocs.end())
  827. {
  828. if (this->Verbose)
  829. {
  830. std::cout << "AUTOMOC: Checking " << headerName << std::endl;
  831. }
  832. const std::string basename = cmsys::SystemTools::
  833. GetFilenameWithoutLastExtension(headerName);
  834. const std::string currentMoc = "moc_" + basename + ".cpp";
  835. const std::string contents = this->ReadAll(headerName);
  836. if (containsQ_OBJECT(contents))
  837. {
  838. //std::cout << "header contains Q_OBJECT macro";
  839. notIncludedMocs[headerName] = currentMoc;
  840. }
  841. }
  842. }
  843. }
  844. bool cmQtAutomoc::GenerateMoc(const std::string& sourceFile,
  845. const std::string& mocFileName)
  846. {
  847. const std::string mocFilePath = this->Builddir + mocFileName;
  848. int sourceNewerThanMoc = 0;
  849. bool success = cmsys::SystemTools::FileTimeCompare(sourceFile.c_str(),
  850. mocFilePath.c_str(),
  851. &sourceNewerThanMoc);
  852. if (this->GenerateAll || !success || sourceNewerThanMoc >= 0)
  853. {
  854. // make sure the directory for the resulting moc file exists
  855. std::string mocDir = mocFilePath.substr(0, mocFilePath.rfind('/'));
  856. if (!cmsys::SystemTools::FileExists(mocDir.c_str(), false))
  857. {
  858. cmsys::SystemTools::MakeDirectory(mocDir.c_str());
  859. }
  860. std::string msg = "Generating ";
  861. msg += mocFileName;
  862. cmSystemTools::MakefileColorEcho(cmsysTerminal_Color_ForegroundBlue
  863. |cmsysTerminal_Color_ForegroundBold,
  864. msg.c_str(), true, this->ColorOutput);
  865. std::vector<cmStdString> command;
  866. command.push_back(this->MocExecutable);
  867. for (std::list<std::string>::const_iterator it = this->MocIncludes.begin();
  868. it != this->MocIncludes.end();
  869. ++it)
  870. {
  871. command.push_back(*it);
  872. }
  873. for(std::list<std::string>::const_iterator it=this->MocDefinitions.begin();
  874. it != this->MocDefinitions.end();
  875. ++it)
  876. {
  877. command.push_back(*it);
  878. }
  879. for(std::vector<std::string>::const_iterator it=this->MocOptions.begin();
  880. it != this->MocOptions.end();
  881. ++it)
  882. {
  883. command.push_back(*it);
  884. }
  885. #ifdef _WIN32
  886. command.push_back("-DWIN32");
  887. #endif
  888. command.push_back("-o");
  889. command.push_back(mocFilePath);
  890. command.push_back(sourceFile);
  891. if (this->Verbose)
  892. {
  893. for(std::vector<cmStdString>::const_iterator cmdIt = command.begin();
  894. cmdIt != command.end();
  895. ++cmdIt)
  896. {
  897. std::cout << *cmdIt << " ";
  898. }
  899. std::cout << std::endl;
  900. }
  901. std::string output;
  902. int retVal = 0;
  903. bool result = cmSystemTools::RunSingleCommand(command, &output, &retVal);
  904. if (!result || retVal)
  905. {
  906. std::cerr << "AUTOMOC: error: process for " << mocFilePath <<" failed:\n"
  907. << output << std::endl;
  908. this->RunMocFailed = true;
  909. cmSystemTools::RemoveFile(mocFilePath.c_str());
  910. }
  911. return true;
  912. }
  913. return false;
  914. }
  915. std::string cmQtAutomoc::Join(const std::list<std::string>& lst,char separator)
  916. {
  917. if (lst.empty())
  918. {
  919. return "";
  920. }
  921. std::string result;
  922. for (std::list<std::string>::const_iterator it = lst.begin();
  923. it != lst.end();
  924. ++it)
  925. {
  926. result += (*it) + separator;
  927. }
  928. result.erase(result.end() - 1);
  929. return result;
  930. }
  931. bool cmQtAutomoc::StartsWith(const std::string& str, const std::string& with)
  932. {
  933. return (str.substr(0, with.length()) == with);
  934. }
  935. bool cmQtAutomoc::EndsWith(const std::string& str, const std::string& with)
  936. {
  937. if (with.length() > (str.length()))
  938. {
  939. return false;
  940. }
  941. return (str.substr(str.length() - with.length(), with.length()) == with);
  942. }
  943. std::string cmQtAutomoc::ReadAll(const std::string& filename)
  944. {
  945. std::ifstream file(filename.c_str());
  946. cmsys_ios::stringstream stream;
  947. stream << file.rdbuf();
  948. file.close();
  949. return stream.str();
  950. }