cmQtAutomoc.cxx 38 KB

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