cmQtAutomoc.cxx 36 KB

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