cmQtAutomoc.cxx 36 KB

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