cmQtAutomoc.cxx 31 KB

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