cmQtAutomoc.cxx 28 KB

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