cmQtAutomoc.cxx 40 KB

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