cmQtAutomoc.cxx 38 KB

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