cmQtAutomoc.cxx 38 KB

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