cmQtAutomoc.cxx 36 KB

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