1
0

cmQtAutomoc.cxx 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961
  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. std::list<std::string> headerExtensions;
  393. headerExtensions.push_back(".h");
  394. headerExtensions.push_back(".hpp");
  395. headerExtensions.push_back(".hxx");
  396. #if defined(_WIN32)
  397. // not case sensitive, don't add ".H"
  398. #elif defined(__APPLE__)
  399. // detect case-sensitive filesystem
  400. long caseSensitive = pathconf(this->Srcdir.c_str(), _PC_CASE_SENSITIVE);
  401. if (caseSensitive == 1)
  402. {
  403. headerExtensions.push_back(".H");
  404. }
  405. #else
  406. headerExtensions.push_back(".H");
  407. #endif
  408. for (std::vector<std::string>::const_iterator it = sourceFiles.begin();
  409. it != sourceFiles.end();
  410. ++it)
  411. {
  412. const std::string &absFilename = *it;
  413. if (this->Verbose)
  414. {
  415. std::cout << "AUTOMOC: Checking " << absFilename << std::endl;
  416. }
  417. this->ParseCppFile(absFilename, headerExtensions, includedMocs);
  418. this->SearchHeadersForCppFile(absFilename, headerExtensions, headerFiles);
  419. }
  420. std::vector<std::string> headerFilesVec;
  421. cmSystemTools::ExpandListArgument(this->Headers, headerFilesVec);
  422. for (std::vector<std::string>::const_iterator it = headerFilesVec.begin();
  423. it != headerFilesVec.end();
  424. ++it)
  425. {
  426. headerFiles.insert(*it);
  427. }
  428. // key = moc source filepath, value = moc output filename
  429. std::map<std::string, std::string> notIncludedMocs;
  430. this->ParseHeaders(headerFiles, includedMocs, notIncludedMocs);
  431. // run moc on all the moc's that are #included in source files
  432. for(std::map<std::string, std::string>::const_iterator
  433. it = includedMocs.begin();
  434. it != includedMocs.end();
  435. ++it)
  436. {
  437. this->GenerateMoc(it->first, it->second);
  438. }
  439. std::stringstream outStream(std::stringstream::out);
  440. outStream << "/* This file is autogenerated, do not edit*/\n";
  441. bool automocCppChanged = false;
  442. if (notIncludedMocs.empty())
  443. {
  444. outStream << "enum some_compilers { need_more_than_nothing };\n";
  445. }
  446. else
  447. {
  448. // run moc on the remaining headers and include them in
  449. // the _automoc.cpp file
  450. for(std::map<std::string, std::string>::const_iterator
  451. it = notIncludedMocs.begin();
  452. it != notIncludedMocs.end();
  453. ++it)
  454. {
  455. bool mocSuccess = this->GenerateMoc(it->first, it->second);
  456. if (mocSuccess)
  457. {
  458. automocCppChanged = true;
  459. }
  460. outStream << "#include \"" << it->second << "\"\n";
  461. }
  462. }
  463. if (this->RunMocFailed)
  464. {
  465. std::cerr << "returning failed.."<< std::endl;
  466. return false;
  467. }
  468. outStream.flush();
  469. std::string automocSource = outStream.str();
  470. if (!automocCppChanged)
  471. {
  472. // compare contents of the _automoc.cpp file
  473. const std::string oldContents = this->ReadAll(this->OutMocCppFilename);
  474. if (oldContents == automocSource)
  475. {
  476. // nothing changed: don't touch the _automoc.cpp file
  477. return true;
  478. }
  479. }
  480. // source file that includes all remaining moc files (_automoc.cpp file)
  481. std::fstream outfile;
  482. outfile.open(this->OutMocCppFilename.c_str(),
  483. std::ios::out | std::ios::trunc);
  484. outfile << automocSource;
  485. outfile.close();
  486. return true;
  487. }
  488. void cmQtAutomoc::ParseCppFile(const std::string& absFilename,
  489. const std::list<std::string>& headerExtensions,
  490. std::map<std::string, std::string>& includedMocs)
  491. {
  492. cmsys::RegularExpression mocIncludeRegExp(
  493. "[\n][ \t]*#[ \t]*include[ \t]+"
  494. "[\"<](([^ \">]+/)?moc_[^ \">/]+\\.cpp|[^ \">]+\\.moc)[\">]");
  495. const std::string contentsString = this->ReadAll(absFilename);
  496. if (contentsString.empty())
  497. {
  498. std::cerr << "AUTOMOC: warning: " << absFilename << ": file is empty\n"
  499. << std::endl;
  500. return;
  501. }
  502. const std::string absPath = cmsys::SystemTools::GetFilenamePath(
  503. cmsys::SystemTools::GetRealPath(absFilename.c_str())) + '/';
  504. const std::string scannedFileBasename = cmsys::SystemTools::
  505. GetFilenameWithoutLastExtension(absFilename);
  506. bool dotMocIncluded = false;
  507. bool mocUnderscoreIncluded = false;
  508. std::string ownMocUnderscoreFile;
  509. std::string ownDotMocFile;
  510. std::string ownMocHeaderFile;
  511. std::string::size_type matchOffset = 0;
  512. // first a simply string check for "moc" is *much* faster than the regexp,
  513. // and if the string search already fails, we don't have to try the
  514. // expensive regexp
  515. if ((strstr(contentsString.c_str(), "moc") != NULL)
  516. && (mocIncludeRegExp.find(contentsString)))
  517. {
  518. // for every moc include in the file
  519. do
  520. {
  521. const std::string currentMoc = mocIncludeRegExp.match(1);
  522. //std::cout << "found moc include: " << currentMoc << std::endl;
  523. std::string basename = cmsys::SystemTools::
  524. GetFilenameWithoutLastExtension(currentMoc);
  525. const bool moc_style = this->StartsWith(basename, "moc_");
  526. // If the moc include is of the moc_foo.cpp style we expect
  527. // the Q_OBJECT class declaration in a header file.
  528. // If the moc include is of the foo.moc style we need to look for
  529. // a Q_OBJECT macro in the current source file, if it contains the
  530. // macro we generate the moc file from the source file.
  531. // Q_OBJECT
  532. if (moc_style)
  533. {
  534. // basename should be the part of the moc filename used for
  535. // finding the correct header, so we need to remove the moc_ part
  536. basename = basename.substr(4);
  537. std::string mocSubDir = extractSubDir(absPath, currentMoc);
  538. std::string headerToMoc = findMatchingHeader(
  539. absPath, mocSubDir, basename, headerExtensions);
  540. if (!headerToMoc.empty())
  541. {
  542. includedMocs[headerToMoc] = currentMoc;
  543. if (basename == scannedFileBasename)
  544. {
  545. mocUnderscoreIncluded = true;
  546. ownMocUnderscoreFile = currentMoc;
  547. ownMocHeaderFile = headerToMoc;
  548. }
  549. }
  550. else
  551. {
  552. std::cerr << "AUTOMOC: error: " << absFilename << " The file "
  553. << "includes the moc file \"" << currentMoc << "\", "
  554. << "but could not find header \"" << basename
  555. << '{' << this->Join(headerExtensions, ',') << "}\" ";
  556. if (mocSubDir.empty())
  557. {
  558. std::cerr << "in " << absPath << "\n" << std::endl;
  559. }
  560. else
  561. {
  562. std::cerr << "neither in " << absPath
  563. << " nor in " << mocSubDir << "\n" << std::endl;
  564. }
  565. ::exit(EXIT_FAILURE);
  566. }
  567. }
  568. else
  569. {
  570. std::string fileToMoc = absFilename;
  571. if (basename != scannedFileBasename)
  572. {
  573. bool fail = true;
  574. if ((this->QtMajorVersion == "4")
  575. && (basename == scannedFileBasename +"_p"))
  576. {
  577. std::string mocSubDir = extractSubDir(absPath, currentMoc);
  578. std::string headerToMoc = findMatchingHeader(
  579. absPath, mocSubDir, basename, headerExtensions);
  580. if (!headerToMoc.empty())
  581. {
  582. // this is for KDE4 compatibility:
  583. fail = false;
  584. fileToMoc = headerToMoc;
  585. std::cerr << "AUTOMOC: warning: " << absFilename << ": The file "
  586. "includes the moc file \"" << currentMoc <<
  587. "\" instead of \"moc_" << basename << ".cpp\". "
  588. "Running moc on "
  589. << "\"" << headerToMoc << "\" ! Better include \"moc_"
  590. << basename << ".cpp\" for a robust build.\n"
  591. << std::endl;
  592. }
  593. }
  594. if (fail)
  595. {
  596. std::cerr <<"AUTOMOC: error: " << absFilename << ": The file "
  597. "includes the moc file \"" << currentMoc <<
  598. "\", which seems to be the moc file from a different "
  599. "source file. This is not supported. "
  600. "Include \"" << scannedFileBasename << ".moc\" to run "
  601. "moc on this source file.\n" << std::endl;
  602. ::exit(EXIT_FAILURE);
  603. }
  604. }
  605. else
  606. {
  607. dotMocIncluded = true;
  608. ownDotMocFile = currentMoc;
  609. }
  610. includedMocs[fileToMoc] = currentMoc;
  611. }
  612. matchOffset += mocIncludeRegExp.end();
  613. } while(mocIncludeRegExp.find(contentsString.c_str() + matchOffset));
  614. }
  615. // In this case, check whether the scanned file itself contains a Q_OBJECT.
  616. // If this is the case, the moc_foo.cpp should probably be generated from
  617. // foo.cpp instead of foo.h, because otherwise it won't build.
  618. // But warn, since this is not how it is supposed to be used.
  619. if ((dotMocIncluded == false) && (containsQ_OBJECT(contentsString)))
  620. {
  621. if ((this->QtMajorVersion == "4") && (mocUnderscoreIncluded == true))
  622. {
  623. // this is for KDE4 compatibility:
  624. std::cerr << "AUTOMOC: warning: " << absFilename << ": The file "
  625. << "contains a Q_OBJECT macro, but does not include "
  626. << "\"" << scannedFileBasename << ".moc\", but instead "
  627. "includes "
  628. << "\"" << ownMocUnderscoreFile << "\". Running moc on "
  629. << "\"" << absFilename << "\" ! Better include \""
  630. << scannedFileBasename << ".moc\" for a robust build.\n"
  631. << std::endl;
  632. includedMocs[absFilename] = ownMocUnderscoreFile;
  633. includedMocs.erase(ownMocHeaderFile);
  634. }
  635. else
  636. {
  637. // otherwise always error out since it will not compile:
  638. std::cerr << "AUTOMOC: error: " << absFilename << ": The file "
  639. << "contains a Q_OBJECT macro, but does not include "
  640. << "\"" << scannedFileBasename << ".moc\" !\n"
  641. << std::endl;
  642. ::exit(EXIT_FAILURE);
  643. }
  644. }
  645. // if only the .moc file is included and we are in compatibility mode,
  646. // check whether maybe the header must actually be mocced, e.g. because it
  647. // might use the Q_PRIVATE_SLOT macro:
  648. if ((dotMocIncluded == true) && (mocUnderscoreIncluded == false)
  649. && (this->QtMajorVersion == "4"))
  650. {
  651. std::string ownHeader=findMatchingHeader(absPath, "", scannedFileBasename,
  652. headerExtensions);
  653. if (ownHeader.size() > 0)
  654. {
  655. const std::string ownHeaderContents = this->ReadAll(ownHeader);
  656. if (containsQ_PRIVATE_SLOT(ownHeaderContents))
  657. {
  658. // this is for KDE4 compatibility:
  659. std::cerr << "AUTOMOC: warning: " << absFilename << ": The file "
  660. << "includes \"" << ownDotMocFile << "\", but the "
  661. << "header \"" << ownHeader << "\" contains a "
  662. << "Q_PRIVATE_SLOT macro. "
  663. << "Running moc on " << "\"" << absFilename << "\" ! "
  664. << "Better include \"moc_" << scannedFileBasename << ".cpp\""
  665. << " for a robust build.\n"
  666. << std::endl;
  667. includedMocs[ownHeader] = ownDotMocFile;
  668. includedMocs.erase(absFilename);
  669. }
  670. }
  671. }
  672. }
  673. void cmQtAutomoc::SearchHeadersForCppFile(const std::string& absFilename,
  674. const std::list<std::string>& headerExtensions,
  675. std::set<std::string>& absHeaders)
  676. {
  677. // search for header files and private header files we may need to moc:
  678. const std::string basename =
  679. cmsys::SystemTools::GetFilenameWithoutLastExtension(absFilename);
  680. const std::string absPath = cmsys::SystemTools::GetFilenamePath(
  681. cmsys::SystemTools::GetRealPath(absFilename.c_str())) + '/';
  682. for(std::list<std::string>::const_iterator ext = headerExtensions.begin();
  683. ext != headerExtensions.end();
  684. ++ext)
  685. {
  686. const std::string headerName = absPath + basename + (*ext);
  687. if (cmsys::SystemTools::FileExists(headerName.c_str()))
  688. {
  689. absHeaders.insert(headerName);
  690. break;
  691. }
  692. }
  693. for(std::list<std::string>::const_iterator ext = headerExtensions.begin();
  694. ext != headerExtensions.end();
  695. ++ext)
  696. {
  697. const std::string privateHeaderName = absPath+basename+"_p"+(*ext);
  698. if (cmsys::SystemTools::FileExists(privateHeaderName.c_str()))
  699. {
  700. absHeaders.insert(privateHeaderName);
  701. break;
  702. }
  703. }
  704. }
  705. void cmQtAutomoc::ParseHeaders(const std::set<std::string>& absHeaders,
  706. const std::map<std::string, std::string>& includedMocs,
  707. std::map<std::string, std::string>& notIncludedMocs)
  708. {
  709. for(std::set<std::string>::const_iterator hIt=absHeaders.begin();
  710. hIt!=absHeaders.end();
  711. ++hIt)
  712. {
  713. const std::string& headerName = *hIt;
  714. if (includedMocs.find(headerName) == includedMocs.end())
  715. {
  716. if (this->Verbose)
  717. {
  718. std::cout << "AUTOMOC: Checking " << headerName << std::endl;
  719. }
  720. const std::string basename = cmsys::SystemTools::
  721. GetFilenameWithoutLastExtension(headerName);
  722. const std::string currentMoc = "moc_" + basename + ".cpp";
  723. const std::string contents = this->ReadAll(headerName);
  724. if (containsQ_OBJECT(contents))
  725. {
  726. //std::cout << "header contains Q_OBJECT macro";
  727. notIncludedMocs[headerName] = currentMoc;
  728. }
  729. }
  730. }
  731. }
  732. bool cmQtAutomoc::GenerateMoc(const std::string& sourceFile,
  733. const std::string& mocFileName)
  734. {
  735. const std::string mocFilePath = this->Builddir + mocFileName;
  736. int sourceNewerThanMoc = 0;
  737. bool success = cmsys::SystemTools::FileTimeCompare(sourceFile.c_str(),
  738. mocFilePath.c_str(),
  739. &sourceNewerThanMoc);
  740. if (this->GenerateAll || !success || sourceNewerThanMoc >= 0)
  741. {
  742. // make sure the directory for the resulting moc file exists
  743. std::string mocDir = mocFilePath.substr(0, mocFilePath.rfind('/'));
  744. if (!cmsys::SystemTools::FileExists(mocDir.c_str(), false))
  745. {
  746. cmsys::SystemTools::MakeDirectory(mocDir.c_str());
  747. }
  748. std::string msg = "Generating ";
  749. msg += mocFileName;
  750. cmSystemTools::MakefileColorEcho(cmsysTerminal_Color_ForegroundBlue
  751. |cmsysTerminal_Color_ForegroundBold,
  752. msg.c_str(), true, this->ColorOutput);
  753. std::vector<cmStdString> command;
  754. command.push_back(this->MocExecutable);
  755. for (std::list<std::string>::const_iterator it = this->MocIncludes.begin();
  756. it != this->MocIncludes.end();
  757. ++it)
  758. {
  759. command.push_back(*it);
  760. }
  761. for(std::list<std::string>::const_iterator it=this->MocDefinitions.begin();
  762. it != this->MocDefinitions.end();
  763. ++it)
  764. {
  765. command.push_back(*it);
  766. }
  767. #ifdef _WIN32
  768. command.push_back("-DWIN32");
  769. #endif
  770. command.push_back("-o");
  771. command.push_back(mocFilePath);
  772. command.push_back(sourceFile);
  773. if (this->Verbose)
  774. {
  775. for(std::vector<cmStdString>::const_iterator cmdIt = command.begin();
  776. cmdIt != command.end();
  777. ++cmdIt)
  778. {
  779. std::cout << *cmdIt << " ";
  780. }
  781. std::cout << std::endl;
  782. }
  783. std::string output;
  784. int retVal = 0;
  785. bool result = cmSystemTools::RunSingleCommand(command, &output, &retVal);
  786. if (!result || retVal)
  787. {
  788. std::cerr << "AUTOMOC: error: process for " << mocFilePath <<" failed:\n"
  789. << output << std::endl;
  790. this->RunMocFailed = true;
  791. cmSystemTools::RemoveFile(mocFilePath.c_str());
  792. }
  793. return true;
  794. }
  795. return false;
  796. }
  797. std::string cmQtAutomoc::Join(const std::list<std::string>& lst,char separator)
  798. {
  799. if (lst.empty())
  800. {
  801. return "";
  802. }
  803. std::string result;
  804. for (std::list<std::string>::const_iterator it = lst.begin();
  805. it != lst.end();
  806. ++it)
  807. {
  808. result += (*it) + separator;
  809. }
  810. result.erase(result.end() - 1);
  811. return result;
  812. }
  813. bool cmQtAutomoc::StartsWith(const std::string& str, const std::string& with)
  814. {
  815. return (str.substr(0, with.length()) == with);
  816. }
  817. bool cmQtAutomoc::EndsWith(const std::string& str, const std::string& with)
  818. {
  819. if (with.length() > (str.length()))
  820. {
  821. return false;
  822. }
  823. return (str.substr(str.length() - with.length(), with.length()) == with);
  824. }
  825. std::string cmQtAutomoc::ReadAll(const std::string& filename)
  826. {
  827. std::ifstream file(filename.c_str());
  828. std::stringstream stream;
  829. stream << file.rdbuf();
  830. file.close();
  831. return stream.str();
  832. }