cmQtAutoMocUic.cxx 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing for details. */
  3. #include "cmQtAutoMocUic.h"
  4. #include <algorithm>
  5. #include <array>
  6. #include <list>
  7. #include <set>
  8. #include <sstream>
  9. #include <utility>
  10. #include "cm_memory.hxx"
  11. #include "cmAlgorithms.h"
  12. #include "cmCryptoHash.h"
  13. #include "cmGeneratedFileStream.h"
  14. #include "cmMakefile.h"
  15. #include "cmQtAutoGen.h"
  16. #include "cmStringAlgorithms.h"
  17. #include "cmSystemTools.h"
  18. #include "cmake.h"
  19. #include "cmsys/FStream.hxx"
  20. #if defined(__APPLE__)
  21. # include <unistd.h>
  22. #endif
  23. static constexpr std::size_t MocUnderscoreLength = 4; // Length of "moc_"
  24. static constexpr std::size_t UiUnderscoreLength = 3; // Length of "ui_"
  25. cmQtAutoMocUic::IncludeKeyT::IncludeKeyT(std::string const& key,
  26. std::size_t basePrefixLength)
  27. : Key(key)
  28. , Dir(SubDirPrefix(key))
  29. , Base(cmSystemTools::GetFilenameWithoutLastExtension(key))
  30. {
  31. if (basePrefixLength != 0) {
  32. Base = Base.substr(basePrefixLength);
  33. }
  34. }
  35. void cmQtAutoMocUic::ParseCacheT::FileT::Clear()
  36. {
  37. Moc.Macro.clear();
  38. Moc.Include.Underscore.clear();
  39. Moc.Include.Dot.clear();
  40. Moc.Depends.clear();
  41. Uic.Include.clear();
  42. Uic.Depends.clear();
  43. }
  44. cmQtAutoMocUic::ParseCacheT::FileHandleT cmQtAutoMocUic::ParseCacheT::Get(
  45. std::string const& fileName) const
  46. {
  47. auto it = Map_.find(fileName);
  48. if (it != Map_.end()) {
  49. return it->second;
  50. }
  51. return FileHandleT();
  52. }
  53. cmQtAutoMocUic::ParseCacheT::GetOrInsertT
  54. cmQtAutoMocUic::ParseCacheT::GetOrInsert(std::string const& fileName)
  55. {
  56. // Find existing entry
  57. {
  58. auto it = Map_.find(fileName);
  59. if (it != Map_.end()) {
  60. return GetOrInsertT{ it->second, false };
  61. }
  62. }
  63. // Insert new entry
  64. return GetOrInsertT{
  65. Map_.emplace(fileName, std::make_shared<FileT>()).first->second, true
  66. };
  67. }
  68. cmQtAutoMocUic::ParseCacheT::ParseCacheT() = default;
  69. cmQtAutoMocUic::ParseCacheT::~ParseCacheT() = default;
  70. void cmQtAutoMocUic::ParseCacheT::Clear()
  71. {
  72. Map_.clear();
  73. }
  74. bool cmQtAutoMocUic::ParseCacheT::ReadFromFile(std::string const& fileName)
  75. {
  76. cmsys::ifstream fin(fileName.c_str());
  77. if (!fin) {
  78. return false;
  79. }
  80. FileHandleT fileHandle;
  81. std::string line;
  82. while (std::getline(fin, line)) {
  83. // Check if this an empty or a comment line
  84. if (line.empty() || line.front() == '#') {
  85. continue;
  86. }
  87. // Drop carriage return character at the end
  88. if (line.back() == '\r') {
  89. line.pop_back();
  90. if (line.empty()) {
  91. continue;
  92. }
  93. }
  94. // Check if this a file name line
  95. if (line.front() != ' ') {
  96. fileHandle = GetOrInsert(line).first;
  97. continue;
  98. }
  99. // Bad line or bad file handle
  100. if (!fileHandle || (line.size() < 6)) {
  101. continue;
  102. }
  103. constexpr std::size_t offset = 5;
  104. if (cmHasLiteralPrefix(line, " mmc:")) {
  105. fileHandle->Moc.Macro = line.substr(offset);
  106. continue;
  107. }
  108. if (cmHasLiteralPrefix(line, " miu:")) {
  109. fileHandle->Moc.Include.Underscore.emplace_back(line.substr(offset),
  110. MocUnderscoreLength);
  111. continue;
  112. }
  113. if (cmHasLiteralPrefix(line, " mid:")) {
  114. fileHandle->Moc.Include.Dot.emplace_back(line.substr(offset), 0);
  115. continue;
  116. }
  117. if (cmHasLiteralPrefix(line, " mdp:")) {
  118. fileHandle->Moc.Depends.emplace_back(line.substr(offset));
  119. continue;
  120. }
  121. if (cmHasLiteralPrefix(line, " uic:")) {
  122. fileHandle->Uic.Include.emplace_back(line.substr(offset),
  123. UiUnderscoreLength);
  124. continue;
  125. }
  126. if (cmHasLiteralPrefix(line, " udp:")) {
  127. fileHandle->Uic.Depends.emplace_back(line.substr(offset));
  128. continue;
  129. }
  130. }
  131. return true;
  132. }
  133. bool cmQtAutoMocUic::ParseCacheT::WriteToFile(std::string const& fileName)
  134. {
  135. cmGeneratedFileStream ofs(fileName);
  136. if (!ofs) {
  137. return false;
  138. }
  139. ofs << "# Generated by CMake. Changes will be overwritten." << std::endl;
  140. for (auto const& pair : Map_) {
  141. ofs << pair.first << std::endl;
  142. FileT const& file = *pair.second;
  143. if (!file.Moc.Macro.empty()) {
  144. ofs << " mmc:" << file.Moc.Macro << std::endl;
  145. }
  146. for (IncludeKeyT const& item : file.Moc.Include.Underscore) {
  147. ofs << " miu:" << item.Key << std::endl;
  148. }
  149. for (IncludeKeyT const& item : file.Moc.Include.Dot) {
  150. ofs << " mid:" << item.Key << std::endl;
  151. }
  152. for (std::string const& item : file.Moc.Depends) {
  153. ofs << " mdp:" << item << std::endl;
  154. }
  155. for (IncludeKeyT const& item : file.Uic.Include) {
  156. ofs << " uic:" << item.Key << std::endl;
  157. }
  158. for (std::string const& item : file.Uic.Depends) {
  159. ofs << " udp:" << item << std::endl;
  160. }
  161. }
  162. return ofs.Close();
  163. }
  164. cmQtAutoMocUic::BaseSettingsT::BaseSettingsT() = default;
  165. cmQtAutoMocUic::BaseSettingsT::~BaseSettingsT() = default;
  166. cmQtAutoMocUic::MocSettingsT::MocSettingsT()
  167. {
  168. RegExpInclude.compile(
  169. "(^|\n)[ \t]*#[ \t]*include[ \t]+"
  170. "[\"<](([^ \">]+/)?moc_[^ \">/]+\\.cpp|[^ \">]+\\.moc)[\">]");
  171. }
  172. cmQtAutoMocUic::MocSettingsT::~MocSettingsT() = default;
  173. bool cmQtAutoMocUic::MocSettingsT::skipped(std::string const& fileName) const
  174. {
  175. return (!Enabled || (SkipList.find(fileName) != SkipList.end()));
  176. }
  177. std::string cmQtAutoMocUic::MocSettingsT::MacrosString() const
  178. {
  179. std::string res;
  180. const auto itB = MacroFilters.cbegin();
  181. const auto itE = MacroFilters.cend();
  182. const auto itL = itE - 1;
  183. auto itC = itB;
  184. for (; itC != itE; ++itC) {
  185. // Separator
  186. if (itC != itB) {
  187. if (itC != itL) {
  188. res += ", ";
  189. } else {
  190. res += " or ";
  191. }
  192. }
  193. // Key
  194. res += itC->Key;
  195. }
  196. return res;
  197. }
  198. cmQtAutoMocUic::UicSettingsT::UicSettingsT()
  199. {
  200. RegExpInclude.compile("(^|\n)[ \t]*#[ \t]*include[ \t]+"
  201. "[\"<](([^ \">]+/)?ui_[^ \">/]+\\.h)[\">]");
  202. }
  203. cmQtAutoMocUic::UicSettingsT::~UicSettingsT() = default;
  204. bool cmQtAutoMocUic::UicSettingsT::skipped(std::string const& fileName) const
  205. {
  206. return (!Enabled || (SkipList.find(fileName) != SkipList.end()));
  207. }
  208. void cmQtAutoMocUic::JobT::LogError(GenT genType,
  209. std::string const& message) const
  210. {
  211. Gen()->AbortError();
  212. Gen()->Log().Error(genType, message);
  213. }
  214. void cmQtAutoMocUic::JobT::LogFileError(GenT genType,
  215. std::string const& filename,
  216. std::string const& message) const
  217. {
  218. Gen()->AbortError();
  219. Gen()->Log().ErrorFile(genType, filename, message);
  220. }
  221. void cmQtAutoMocUic::JobT::LogCommandError(
  222. GenT genType, std::string const& message,
  223. std::vector<std::string> const& command, std::string const& output) const
  224. {
  225. Gen()->AbortError();
  226. Gen()->Log().ErrorCommand(genType, message, command, output);
  227. }
  228. bool cmQtAutoMocUic::JobT::RunProcess(GenT genType,
  229. cmWorkerPool::ProcessResultT& result,
  230. std::vector<std::string> const& command,
  231. std::string* infoMessage)
  232. {
  233. // Log command
  234. if (Log().Verbose()) {
  235. std::string msg;
  236. if ((infoMessage != nullptr) && !infoMessage->empty()) {
  237. msg = *infoMessage;
  238. if (msg.back() != '\n') {
  239. msg += '\n';
  240. }
  241. }
  242. msg += QuotedCommand(command);
  243. msg += '\n';
  244. Log().Info(genType, msg);
  245. }
  246. return cmWorkerPool::JobT::RunProcess(result, command,
  247. BaseConst().AutogenBuildDir);
  248. }
  249. void cmQtAutoMocUic::JobMocPredefsT::Process()
  250. {
  251. // (Re)generate moc_predefs.h on demand
  252. std::unique_ptr<std::string> reason;
  253. if (Log().Verbose()) {
  254. reason = cm::make_unique<std::string>();
  255. }
  256. if (!Update(reason.get())) {
  257. return;
  258. }
  259. std::string const& predefsFileRel = MocConst().PredefsFileRel;
  260. std::string const& predefsFileAbs = MocConst().PredefsFileAbs;
  261. {
  262. cmWorkerPool::ProcessResultT result;
  263. {
  264. // Compose command
  265. std::vector<std::string> cmd = MocConst().PredefsCmd;
  266. // Add includes
  267. cmAppend(cmd, MocConst().Includes);
  268. // Add definitions
  269. for (std::string const& def : MocConst().Definitions) {
  270. cmd.emplace_back("-D" + def);
  271. }
  272. // Execute command
  273. if (!RunProcess(GenT::MOC, result, cmd, reason.get())) {
  274. std::string msg =
  275. cmStrCat("The content generation command for ",
  276. Quoted(predefsFileRel), " failed.\n", result.ErrorMessage);
  277. LogCommandError(GenT::MOC, msg, cmd, result.StdOut);
  278. return;
  279. }
  280. }
  281. // (Re)write predefs file only on demand
  282. if (cmQtAutoGenerator::FileDiffers(predefsFileAbs, result.StdOut)) {
  283. if (!cmQtAutoGenerator::FileWrite(predefsFileAbs, result.StdOut)) {
  284. std::string msg =
  285. cmStrCat("Writing ", Quoted(predefsFileRel), " failed.");
  286. LogFileError(GenT::MOC, predefsFileAbs, msg);
  287. return;
  288. }
  289. } else {
  290. // Touch to update the time stamp
  291. if (Log().Verbose()) {
  292. Log().Info(GenT::MOC, "Touching " + Quoted(predefsFileRel));
  293. }
  294. if (!cmSystemTools::Touch(predefsFileAbs, false)) {
  295. std::string msg =
  296. cmStrCat("Touching ", Quoted(predefsFileAbs), " failed.");
  297. LogFileError(GenT::MOC, predefsFileAbs, msg);
  298. return;
  299. }
  300. }
  301. }
  302. // Read file time afterwards
  303. if (!MocEval().PredefsTime.Load(predefsFileAbs)) {
  304. LogFileError(GenT::MOC, predefsFileAbs, "File time reading failed.");
  305. return;
  306. }
  307. }
  308. bool cmQtAutoMocUic::JobMocPredefsT::Update(std::string* reason) const
  309. {
  310. // Test if the file exists
  311. if (!MocEval().PredefsTime.Load(MocConst().PredefsFileAbs)) {
  312. if (reason != nullptr) {
  313. *reason = "Generating ";
  314. *reason += Quoted(MocConst().PredefsFileRel);
  315. *reason += ", because it doesn't exist.";
  316. }
  317. return true;
  318. }
  319. // Test if the settings changed
  320. if (MocConst().SettingsChanged) {
  321. if (reason != nullptr) {
  322. *reason = "Generating ";
  323. *reason += Quoted(MocConst().PredefsFileRel);
  324. *reason += ", because the moc settings changed.";
  325. }
  326. return true;
  327. }
  328. // Test if the executable is newer
  329. {
  330. std::string const& exec = MocConst().PredefsCmd.at(0);
  331. cmFileTime execTime;
  332. if (execTime.Load(exec)) {
  333. if (MocEval().PredefsTime.Older(execTime)) {
  334. if (reason != nullptr) {
  335. *reason = "Generating ";
  336. *reason += Quoted(MocConst().PredefsFileRel);
  337. *reason += " because it is older than ";
  338. *reason += Quoted(exec);
  339. *reason += ".";
  340. }
  341. return true;
  342. }
  343. }
  344. }
  345. return false;
  346. }
  347. bool cmQtAutoMocUic::JobParseT::ReadFile()
  348. {
  349. // Clear old parse information
  350. FileHandle->ParseData->Clear();
  351. std::string const& fileName = FileHandle->FileName;
  352. // Write info
  353. if (Log().Verbose()) {
  354. Log().Info(GenT::GEN, "Parsing " + Quoted(fileName));
  355. }
  356. // Read file content
  357. {
  358. std::string error;
  359. if (!cmQtAutoGenerator::FileRead(Content, fileName, &error)) {
  360. LogFileError(GenT::GEN, fileName, "Could not read the file: " + error);
  361. return false;
  362. }
  363. }
  364. // Warn if empty
  365. if (Content.empty()) {
  366. Log().WarningFile(GenT::GEN, fileName, "The file is empty.");
  367. return false;
  368. }
  369. return true;
  370. }
  371. void cmQtAutoMocUic::JobParseT::CreateKeys(std::vector<IncludeKeyT>& container,
  372. std::set<std::string> const& source,
  373. std::size_t basePrefixLength)
  374. {
  375. if (source.empty()) {
  376. return;
  377. }
  378. container.reserve(source.size());
  379. for (std::string const& src : source) {
  380. container.emplace_back(src, basePrefixLength);
  381. }
  382. }
  383. void cmQtAutoMocUic::JobParseT::MocMacro()
  384. {
  385. for (KeyExpT const& filter : MocConst().MacroFilters) {
  386. // Run a simple find string check
  387. if (Content.find(filter.Key) == std::string::npos) {
  388. continue;
  389. }
  390. // Run the expensive regular expression check loop
  391. cmsys::RegularExpressionMatch match;
  392. if (filter.Exp.find(Content.c_str(), match)) {
  393. // Keep detected macro name
  394. FileHandle->ParseData->Moc.Macro = filter.Key;
  395. return;
  396. }
  397. }
  398. }
  399. void cmQtAutoMocUic::JobParseT::MocDependecies()
  400. {
  401. if (MocConst().DependFilters.empty()) {
  402. return;
  403. }
  404. // Find dependency strings
  405. std::set<std::string> parseDepends;
  406. for (KeyExpT const& filter : MocConst().DependFilters) {
  407. // Run a simple find string check
  408. if (Content.find(filter.Key) == std::string::npos) {
  409. continue;
  410. }
  411. // Run the expensive regular expression check loop
  412. const char* contentChars = Content.c_str();
  413. cmsys::RegularExpressionMatch match;
  414. while (filter.Exp.find(contentChars, match)) {
  415. {
  416. std::string dep = match.match(1);
  417. if (!dep.empty()) {
  418. parseDepends.emplace(std::move(dep));
  419. }
  420. }
  421. contentChars += match.end();
  422. }
  423. }
  424. // Store dependency strings
  425. {
  426. auto& Depends = FileHandle->ParseData->Moc.Depends;
  427. Depends.reserve(parseDepends.size());
  428. for (std::string const& item : parseDepends) {
  429. Depends.emplace_back(item);
  430. // Replace end of line characters in filenames
  431. std::string& path = Depends.back();
  432. std::replace(path.begin(), path.end(), '\n', ' ');
  433. std::replace(path.begin(), path.end(), '\r', ' ');
  434. }
  435. }
  436. }
  437. void cmQtAutoMocUic::JobParseT::MocIncludes()
  438. {
  439. if (Content.find("moc") == std::string::npos) {
  440. return;
  441. }
  442. std::set<std::string> underscore;
  443. std::set<std::string> dot;
  444. {
  445. const char* contentChars = Content.c_str();
  446. cmsys::RegularExpression const& regExp = MocConst().RegExpInclude;
  447. cmsys::RegularExpressionMatch match;
  448. while (regExp.find(contentChars, match)) {
  449. std::string incString = match.match(2);
  450. std::string const incBase =
  451. cmSystemTools::GetFilenameWithoutLastExtension(incString);
  452. if (cmHasLiteralPrefix(incBase, "moc_")) {
  453. // moc_<BASE>.cpp
  454. // Remove the moc_ part from the base name
  455. underscore.emplace(std::move(incString));
  456. } else {
  457. // <BASE>.moc
  458. dot.emplace(std::move(incString));
  459. }
  460. // Forward content pointer
  461. contentChars += match.end();
  462. }
  463. }
  464. auto& Include = FileHandle->ParseData->Moc.Include;
  465. CreateKeys(Include.Underscore, underscore, MocUnderscoreLength);
  466. CreateKeys(Include.Dot, dot, 0);
  467. }
  468. void cmQtAutoMocUic::JobParseT::UicIncludes()
  469. {
  470. if (Content.find("ui_") == std::string::npos) {
  471. return;
  472. }
  473. std::set<std::string> includes;
  474. {
  475. const char* contentChars = Content.c_str();
  476. cmsys::RegularExpression const& regExp = UicConst().RegExpInclude;
  477. cmsys::RegularExpressionMatch match;
  478. while (regExp.find(contentChars, match)) {
  479. includes.emplace(match.match(2));
  480. // Forward content pointer
  481. contentChars += match.end();
  482. }
  483. }
  484. CreateKeys(FileHandle->ParseData->Uic.Include, includes, UiUnderscoreLength);
  485. }
  486. void cmQtAutoMocUic::JobParseHeaderT::Process()
  487. {
  488. if (!ReadFile()) {
  489. return;
  490. }
  491. // Moc parsing
  492. if (FileHandle->Moc) {
  493. MocMacro();
  494. MocDependecies();
  495. }
  496. // Uic parsing
  497. if (FileHandle->Uic) {
  498. UicIncludes();
  499. }
  500. }
  501. void cmQtAutoMocUic::JobParseSourceT::Process()
  502. {
  503. if (!ReadFile()) {
  504. return;
  505. }
  506. // Moc parsing
  507. if (FileHandle->Moc) {
  508. MocMacro();
  509. MocDependecies();
  510. MocIncludes();
  511. }
  512. // Uic parsing
  513. if (FileHandle->Uic) {
  514. UicIncludes();
  515. }
  516. }
  517. void cmQtAutoMocUic::JobEvaluateT::Process()
  518. {
  519. // Evaluate for moc
  520. if (MocConst().Enabled) {
  521. // Evaluate headers
  522. for (auto const& pair : BaseEval().Headers) {
  523. if (!MocEvalHeader(pair.second)) {
  524. return;
  525. }
  526. }
  527. // Evaluate sources
  528. for (auto const& pair : BaseEval().Sources) {
  529. if (!MocEvalSource(pair.second)) {
  530. return;
  531. }
  532. }
  533. }
  534. // Evaluate for uic
  535. if (UicConst().Enabled) {
  536. if (!UicEval(BaseEval().Headers) || !UicEval(BaseEval().Sources)) {
  537. return;
  538. }
  539. }
  540. // Add discovered header parse jobs
  541. Gen()->CreateParseJobs<JobParseHeaderT>(MocEval().HeadersDiscovered);
  542. // Add generate job after
  543. Gen()->WorkerPool().EmplaceJob<JobGenerateT>();
  544. }
  545. bool cmQtAutoMocUic::JobEvaluateT::MocEvalHeader(SourceFileHandleT source)
  546. {
  547. SourceFileT const& sourceFile = *source;
  548. auto const& parseData = sourceFile.ParseData->Moc;
  549. if (!source->Moc) {
  550. return true;
  551. }
  552. if (!parseData.Macro.empty()) {
  553. // Create a new mapping
  554. MappingHandleT handle = std::make_shared<MappingT>();
  555. handle->SourceFile = std::move(source);
  556. // Absolute build path
  557. if (BaseConst().MultiConfig) {
  558. handle->OutputFile = Gen()->AbsoluteIncludePath(sourceFile.BuildPath);
  559. } else {
  560. handle->OutputFile = Gen()->AbsoluteBuildPath(sourceFile.BuildPath);
  561. }
  562. // Register mapping in headers map
  563. MocRegisterMapping(handle, true);
  564. }
  565. return true;
  566. }
  567. bool cmQtAutoMocUic::JobEvaluateT::MocEvalSource(
  568. SourceFileHandleT const& source)
  569. {
  570. SourceFileT const& sourceFile = *source;
  571. auto const& parseData = sourceFile.ParseData->Moc;
  572. if (!sourceFile.Moc ||
  573. (parseData.Macro.empty() && parseData.Include.Underscore.empty() &&
  574. parseData.Include.Dot.empty())) {
  575. return true;
  576. }
  577. std::string const sourceDir = SubDirPrefix(sourceFile.FileName);
  578. std::string const sourceBase =
  579. cmSystemTools::GetFilenameWithoutLastExtension(sourceFile.FileName);
  580. // For relaxed mode check if the own "moc_" or ".moc" file is included
  581. bool const relaxedMode = MocConst().RelaxedMode;
  582. bool sourceIncludesMocUnderscore = false;
  583. bool sourceIncludesDotMoc = false;
  584. // Check if the sources own "moc_" or ".moc" file is included
  585. if (relaxedMode) {
  586. for (IncludeKeyT const& incKey : parseData.Include.Underscore) {
  587. if (incKey.Base == sourceBase) {
  588. sourceIncludesMocUnderscore = true;
  589. break;
  590. }
  591. }
  592. }
  593. for (IncludeKeyT const& incKey : parseData.Include.Dot) {
  594. if (incKey.Base == sourceBase) {
  595. sourceIncludesDotMoc = true;
  596. break;
  597. }
  598. }
  599. // Check if this source needs to be moc processed but doesn't.
  600. if (!sourceIncludesDotMoc && !parseData.Macro.empty() &&
  601. !(relaxedMode && sourceIncludesMocUnderscore)) {
  602. {
  603. std::string emsg =
  604. cmStrCat("The file contains a ", Quoted(parseData.Macro),
  605. " macro, but does not include ", Quoted(sourceBase + ".moc"),
  606. "!\nConsider to\n - add #include \"", sourceBase,
  607. ".moc\"\n - enable SKIP_AUTOMOC for this file");
  608. LogFileError(GenT::MOC, sourceFile.FileName, emsg);
  609. }
  610. return false;
  611. }
  612. // Evaluate "moc_" includes
  613. for (IncludeKeyT const& incKey : parseData.Include.Underscore) {
  614. std::string const headerBase = incKey.Dir + incKey.Base;
  615. SourceFileHandleT header = MocFindIncludedHeader(sourceDir, headerBase);
  616. if (!header) {
  617. {
  618. std::string msg = "The file includes the moc file ";
  619. msg += Quoted(incKey.Key);
  620. msg += ",\nbut the header could not be found "
  621. "in the following locations\n";
  622. msg += MocMessageTestHeaders(headerBase);
  623. LogFileError(GenT::MOC, sourceFile.FileName, msg);
  624. }
  625. return false;
  626. }
  627. // The include might be handled differently in relaxed mode
  628. if (relaxedMode && !sourceIncludesDotMoc && !parseData.Macro.empty() &&
  629. (incKey.Base == sourceBase)) {
  630. // The <BASE>.cpp file includes a Qt macro but does not include the
  631. // <BASE>.moc file. In this case, the moc_<BASE>.cpp should probably
  632. // be generated from <BASE>.cpp instead of <BASE>.h, because otherwise
  633. // it won't build. But warn, since this is not how it is supposed to be
  634. // used. This is for KDE4 compatibility.
  635. {
  636. // Issue a warning
  637. std::string msg = cmStrCat(
  638. "The file contains a ", Quoted(parseData.Macro),
  639. " macro, but does not include ", Quoted(sourceBase + ".moc"),
  640. ".\nInstead it includes ", Quoted(incKey.Key),
  641. ".\nRunning moc on the source\n ", Quoted(sourceFile.FileName),
  642. "!\nBetter include ", Quoted(sourceBase + ".moc"),
  643. " for compatibility with regular mode.\n",
  644. "This is a CMAKE_AUTOMOC_RELAXED_MODE warning.\n");
  645. Log().WarningFile(GenT::MOC, sourceFile.FileName, msg);
  646. }
  647. // Create mapping
  648. if (!MocRegisterIncluded(incKey.Key, source, source, false)) {
  649. return false;
  650. }
  651. continue;
  652. }
  653. // Check if header is skipped
  654. if (MocConst().skipped(header->FileName)) {
  655. continue;
  656. }
  657. // Create mapping
  658. if (!MocRegisterIncluded(incKey.Key, source, std::move(header), true)) {
  659. return false;
  660. }
  661. }
  662. // Evaluate ".moc" includes
  663. if (relaxedMode) {
  664. // Relaxed mode
  665. for (IncludeKeyT const& incKey : parseData.Include.Dot) {
  666. // Check if this is the sources own .moc file
  667. bool const ownMoc = (incKey.Base == sourceBase);
  668. if (ownMoc && !parseData.Macro.empty()) {
  669. // Create mapping for the regular use case
  670. if (!MocRegisterIncluded(incKey.Key, source, source, false)) {
  671. return false;
  672. }
  673. continue;
  674. }
  675. // Try to find a header instead but issue a warning.
  676. // This is for KDE4 compatibility.
  677. std::string const headerBase = incKey.Dir + incKey.Base;
  678. SourceFileHandleT header = MocFindIncludedHeader(sourceDir, headerBase);
  679. if (!header) {
  680. std::string msg = "The file includes the moc file ";
  681. msg += Quoted(incKey.Key);
  682. msg += ",\nwhich seems to be the moc file from a different source "
  683. "file.\nCMAKE_AUTOMOC_RELAXED_MODE: Also a matching header"
  684. "could not be found in the following locations\n";
  685. msg += MocMessageTestHeaders(headerBase);
  686. LogFileError(GenT::MOC, sourceFile.FileName, msg);
  687. return false;
  688. }
  689. // Check if header is skipped
  690. if (MocConst().skipped(header->FileName)) {
  691. continue;
  692. }
  693. // Issue a warning
  694. if (ownMoc && parseData.Macro.empty()) {
  695. std::string msg = cmStrCat(
  696. "The file includes the moc file ", Quoted(incKey.Key),
  697. ", but does not contain a\n", MocConst().MacrosString(),
  698. " macro.\nRunning moc on the header\n ", Quoted(header->FileName),
  699. "!\nBetter include ", Quoted("moc_" + incKey.Base + ".cpp"),
  700. " for a compatibility with regular mode.\n",
  701. "This is a CMAKE_AUTOMOC_RELAXED_MODE warning.\n");
  702. Log().WarningFile(GenT::MOC, sourceFile.FileName, msg);
  703. } else {
  704. std::string msg = cmStrCat(
  705. "The file includes the moc file ", Quoted(incKey.Key),
  706. " instead of ", Quoted("moc_" + incKey.Base + ".cpp"),
  707. ".\nRunning moc on the header\n ", Quoted(header->FileName),
  708. "!\nBetter include ", Quoted("moc_" + incKey.Base + ".cpp"),
  709. " for compatibility with regular mode.\n",
  710. "This is a CMAKE_AUTOMOC_RELAXED_MODE warning.\n");
  711. Log().WarningFile(GenT::MOC, sourceFile.FileName, msg);
  712. }
  713. // Create mapping
  714. if (!MocRegisterIncluded(incKey.Key, source, std::move(header), true)) {
  715. return false;
  716. }
  717. }
  718. } else {
  719. // Strict mode
  720. for (IncludeKeyT const& incKey : parseData.Include.Dot) {
  721. // Check if this is the sources own .moc file
  722. bool const ownMoc = (incKey.Base == sourceBase);
  723. if (!ownMoc) {
  724. // Don't allow <BASE>.moc include other than own in regular mode
  725. std::string msg = "The file includes the moc file ";
  726. msg += Quoted(incKey.Key);
  727. msg += ",\nwhich seems to be the moc file from a different "
  728. "source file.\nThis is not supported. Include ";
  729. msg += Quoted(sourceBase + ".moc");
  730. msg += " to run moc on this source file.";
  731. LogFileError(GenT::MOC, sourceFile.FileName, msg);
  732. return false;
  733. }
  734. // Accept but issue a warning if moc isn't required
  735. if (parseData.Macro.empty()) {
  736. std::string msg = cmStrCat(
  737. "The file includes the moc file ", Quoted(incKey.Key),
  738. ", but does not contain a ", MocConst().MacrosString(), " macro.");
  739. Log().WarningFile(GenT::MOC, sourceFile.FileName, msg);
  740. }
  741. // Create mapping
  742. if (!MocRegisterIncluded(incKey.Key, source, source, false)) {
  743. return false;
  744. }
  745. }
  746. }
  747. return true;
  748. }
  749. cmQtAutoMocUic::SourceFileHandleT
  750. cmQtAutoMocUic::JobEvaluateT::MocFindIncludedHeader(
  751. std::string const& includerDir, std::string const& includeBase) const
  752. {
  753. // Search in vicinity of the source
  754. {
  755. SourceFileHandleT res = MocFindHeader(includerDir + includeBase);
  756. if (res) {
  757. return res;
  758. }
  759. }
  760. // Search in include directories
  761. for (std::string const& path : MocConst().IncludePaths) {
  762. std::string testPath = cmStrCat(path, '/', includeBase);
  763. SourceFileHandleT res = MocFindHeader(testPath);
  764. if (res) {
  765. return res;
  766. }
  767. }
  768. // Return without success
  769. return SourceFileHandleT();
  770. }
  771. cmQtAutoMocUic::SourceFileHandleT cmQtAutoMocUic::JobEvaluateT::MocFindHeader(
  772. std::string const& basePath) const
  773. {
  774. std::string testPath;
  775. testPath.reserve(basePath.size() + 8);
  776. for (std::string const& ext : BaseConst().HeaderExtensions) {
  777. testPath.clear();
  778. testPath += basePath;
  779. testPath += '.';
  780. testPath += ext;
  781. cmFileTime fileTime;
  782. if (fileTime.Load(testPath)) {
  783. // Compute real path of the file
  784. testPath = cmSystemTools::GetRealPath(testPath);
  785. // Return a known file if it exists already
  786. {
  787. auto it = BaseEval().Headers.find(testPath);
  788. if (it != BaseEval().Headers.end()) {
  789. return it->second;
  790. }
  791. }
  792. // Created and return discovered file entry
  793. SourceFileHandleT& res = MocEval().HeadersDiscovered[testPath];
  794. if (!res) {
  795. res = std::make_shared<SourceFileT>(testPath);
  796. res->FileTime = fileTime;
  797. res->Moc = true;
  798. }
  799. return res;
  800. }
  801. }
  802. // Return without success
  803. return SourceFileHandleT();
  804. }
  805. std::string cmQtAutoMocUic::JobEvaluateT::MocMessageTestHeaders(
  806. std::string const& fileBase) const
  807. {
  808. std::ostringstream res;
  809. {
  810. std::string exts =
  811. cmStrCat(".{", cmJoin(BaseConst().HeaderExtensions, ","),
  812. '}'); // Compose result string
  813. res << " " << fileBase << exts << '\n';
  814. for (std::string const& path : MocConst().IncludePaths) {
  815. res << " " << path << '/' << fileBase << exts << '\n';
  816. }
  817. }
  818. return res.str();
  819. }
  820. bool cmQtAutoMocUic::JobEvaluateT::MocRegisterIncluded(
  821. std::string const& includeString, SourceFileHandleT includerFileHandle,
  822. SourceFileHandleT sourceFileHandle, bool sourceIsHeader) const
  823. {
  824. // Check if this file is already included
  825. MappingHandleT& handle = MocEval().Includes[includeString];
  826. if (handle) {
  827. // Check if the output file would be generated from different source files
  828. if (handle->SourceFile != sourceFileHandle) {
  829. std::string msg = cmStrCat("The source files\n ",
  830. Quoted(includerFileHandle->FileName), '\n');
  831. for (auto const& item : handle->IncluderFiles) {
  832. msg += " ";
  833. msg += Quoted(item->FileName);
  834. msg += '\n';
  835. }
  836. msg += "contain the same include string ";
  837. msg += Quoted(includeString);
  838. msg += ", but\nthe moc file would be generated from different "
  839. "source files\n ";
  840. msg += Quoted(sourceFileHandle->FileName);
  841. msg += " and\n ";
  842. msg += Quoted(handle->SourceFile->FileName);
  843. msg += ".\nConsider to\n"
  844. " - not include the \"moc_<NAME>.cpp\" file\n"
  845. " - add a directory prefix to a \"<NAME>.moc\" include "
  846. "(e.g \"sub/<NAME>.moc\")\n"
  847. " - rename the source file(s)\n";
  848. LogError(GenT::MOC, msg);
  849. return false;
  850. }
  851. // The same mapping already exists. Just add to the includers list.
  852. handle->IncluderFiles.emplace_back(std::move(includerFileHandle));
  853. return true;
  854. }
  855. // Create a new mapping
  856. handle = std::make_shared<MappingT>();
  857. handle->IncludeString = includeString;
  858. handle->IncluderFiles.emplace_back(std::move(includerFileHandle));
  859. handle->SourceFile = std::move(sourceFileHandle);
  860. handle->OutputFile += Gen()->AbsoluteIncludePath(includeString);
  861. // Register mapping in sources/headers map
  862. MocRegisterMapping(handle, sourceIsHeader);
  863. return true;
  864. }
  865. void cmQtAutoMocUic::JobEvaluateT::MocRegisterMapping(
  866. MappingHandleT mappingHandle, bool sourceIsHeader) const
  867. {
  868. auto& regMap =
  869. sourceIsHeader ? MocEval().HeaderMappings : MocEval().SourceMappings;
  870. // Check if source file already gets mapped
  871. auto& regHandle = regMap[mappingHandle->SourceFile->FileName];
  872. if (!regHandle) {
  873. // Yet unknown mapping
  874. regHandle = std::move(mappingHandle);
  875. } else {
  876. // Mappings with include string override those without
  877. if (!mappingHandle->IncludeString.empty()) {
  878. regHandle = std::move(mappingHandle);
  879. }
  880. }
  881. }
  882. bool cmQtAutoMocUic::JobEvaluateT::UicEval(SourceFileMapT const& fileMap)
  883. {
  884. for (auto const& pair : fileMap) {
  885. if (!UicEvalFile(pair.second)) {
  886. return false;
  887. }
  888. }
  889. return true;
  890. }
  891. bool cmQtAutoMocUic::JobEvaluateT::UicEvalFile(
  892. SourceFileHandleT sourceFileHandle)
  893. {
  894. SourceFileT const& sourceFile = *sourceFileHandle;
  895. auto const& Include = sourceFile.ParseData->Uic.Include;
  896. if (!sourceFile.Uic || Include.empty()) {
  897. return true;
  898. }
  899. std::string const sourceDir = SubDirPrefix(sourceFile.FileName);
  900. for (IncludeKeyT const& incKey : Include) {
  901. // Find .ui file name
  902. SourceFileHandleT uiFileHandle =
  903. UicFindIncludedUi(sourceFile.FileName, sourceDir, incKey);
  904. if (!uiFileHandle || UicConst().skipped(uiFileHandle->FileName)) {
  905. continue;
  906. }
  907. // Register mapping
  908. if (!UicRegisterMapping(incKey.Key, std::move(uiFileHandle),
  909. std::move(sourceFileHandle))) {
  910. return false;
  911. }
  912. }
  913. return true;
  914. }
  915. bool cmQtAutoMocUic::JobEvaluateT::UicRegisterMapping(
  916. std::string const& includeString, SourceFileHandleT uiFileHandle,
  917. SourceFileHandleT includerFileHandle)
  918. {
  919. auto& Includes = Gen()->UicEval().Includes;
  920. auto it = Includes.find(includeString);
  921. if (it != Includes.end()) {
  922. MappingHandleT const& handle = it->second;
  923. if (handle->SourceFile != uiFileHandle) {
  924. // The output file already gets generated - from a different .ui file!
  925. std::string msg = cmStrCat("The source files\n ",
  926. Quoted(includerFileHandle->FileName), '\n');
  927. for (auto const& item : handle->IncluderFiles) {
  928. msg += " ";
  929. msg += Quoted(item->FileName);
  930. msg += '\n';
  931. }
  932. msg += "contain the same include string ";
  933. msg += Quoted(includeString);
  934. msg += ", but\nthe uic file would be generated from different "
  935. "user interface files\n ";
  936. msg += Quoted(uiFileHandle->FileName);
  937. msg += " and\n ";
  938. msg += Quoted(handle->SourceFile->FileName);
  939. msg += ".\nConsider to\n"
  940. " - add a directory prefix to a \"ui_<NAME>.h\" include "
  941. "(e.g \"sub/ui_<NAME>.h\")\n"
  942. " - rename the <NAME>.ui file(s) and adjust the \"ui_<NAME>.h\" "
  943. "include(s)\n";
  944. LogError(GenT::UIC, msg);
  945. return false;
  946. }
  947. // Add includer file to existing mapping
  948. handle->IncluderFiles.emplace_back(std::move(includerFileHandle));
  949. } else {
  950. // New mapping handle
  951. MappingHandleT handle = std::make_shared<MappingT>();
  952. handle->IncludeString = includeString;
  953. handle->IncluderFiles.emplace_back(std::move(includerFileHandle));
  954. handle->SourceFile = std::move(uiFileHandle);
  955. handle->OutputFile += Gen()->AbsoluteIncludePath(includeString);
  956. // Register mapping
  957. Includes.emplace(includeString, std::move(handle));
  958. }
  959. return true;
  960. }
  961. cmQtAutoMocUic::SourceFileHandleT
  962. cmQtAutoMocUic::JobEvaluateT::UicFindIncludedUi(
  963. std::string const& sourceFile, std::string const& sourceDir,
  964. IncludeKeyT const& incKey) const
  965. {
  966. std::string searchFileName = cmStrCat(incKey.Base, ".ui");
  967. // Collect search paths list
  968. std::vector<std::string> testFiles;
  969. {
  970. auto& searchPaths = UicConst().SearchPaths;
  971. testFiles.reserve((searchPaths.size() + 1) * 2);
  972. // Vicinity of the source
  973. testFiles.emplace_back(sourceDir + searchFileName);
  974. if (!incKey.Dir.empty()) {
  975. testFiles.emplace_back(cmStrCat(sourceDir, incKey.Dir, searchFileName));
  976. }
  977. // AUTOUIC search paths
  978. if (!searchPaths.empty()) {
  979. for (std::string const& sPath : searchPaths) {
  980. testFiles.emplace_back(cmStrCat(sPath, '/', searchFileName));
  981. }
  982. if (!incKey.Dir.empty()) {
  983. for (std::string const& sPath : searchPaths) {
  984. testFiles.emplace_back(
  985. cmStrCat(sPath, '/', incKey.Dir, searchFileName));
  986. }
  987. }
  988. }
  989. }
  990. // Search for the .ui file!
  991. for (std::string const& testFile : testFiles) {
  992. cmFileTime fileTime;
  993. if (fileTime.Load(testFile)) {
  994. // .ui file found in files system!
  995. std::string realPath = cmSystemTools::GetRealPath(testFile);
  996. // Get or create .ui file handle
  997. SourceFileHandleT& handle = Gen()->UicEval().UiFiles[realPath];
  998. if (!handle) {
  999. // The file wasn't registered, yet
  1000. handle = std::make_shared<SourceFileT>(realPath);
  1001. handle->FileTime = fileTime;
  1002. }
  1003. return handle;
  1004. }
  1005. }
  1006. // Log error
  1007. {
  1008. std::string msg =
  1009. cmStrCat("The file includes the uic file ", Quoted(incKey.Key),
  1010. ",\nbut the user interface file ", Quoted(searchFileName),
  1011. "\ncould not be found in the following locations\n");
  1012. for (std::string const& testFile : testFiles) {
  1013. msg += " ";
  1014. msg += Quoted(testFile);
  1015. msg += '\n';
  1016. }
  1017. LogFileError(GenT::UIC, sourceFile, msg);
  1018. }
  1019. return SourceFileHandleT();
  1020. }
  1021. void cmQtAutoMocUic::JobGenerateT::Process()
  1022. {
  1023. // Add moc compile jobs
  1024. if (MocConst().Enabled) {
  1025. for (auto const& pair : MocEval().HeaderMappings) {
  1026. // Register if this mapping is a candidate for mocs_compilation.cpp
  1027. bool const compFile = pair.second->IncludeString.empty();
  1028. if (compFile) {
  1029. MocEval().CompFiles.emplace_back(pair.second->SourceFile->BuildPath);
  1030. }
  1031. if (!MocGenerate(pair.second, compFile)) {
  1032. return;
  1033. }
  1034. }
  1035. for (auto const& pair : MocEval().SourceMappings) {
  1036. if (!MocGenerate(pair.second, false)) {
  1037. return;
  1038. }
  1039. }
  1040. // Add mocs compilations job on demand
  1041. Gen()->WorkerPool().EmplaceJob<JobMocsCompilationT>();
  1042. }
  1043. // Add uic compile jobs
  1044. if (UicConst().Enabled) {
  1045. for (auto const& pair : Gen()->UicEval().Includes) {
  1046. if (!UicGenerate(pair.second)) {
  1047. return;
  1048. }
  1049. }
  1050. }
  1051. // Add finish job
  1052. Gen()->WorkerPool().EmplaceJob<JobFinishT>();
  1053. }
  1054. bool cmQtAutoMocUic::JobGenerateT::MocGenerate(MappingHandleT const& mapping,
  1055. bool compFile) const
  1056. {
  1057. std::unique_ptr<std::string> reason;
  1058. if (Log().Verbose()) {
  1059. reason = cm::make_unique<std::string>();
  1060. }
  1061. if (MocUpdate(*mapping, reason.get())) {
  1062. // Create the parent directory
  1063. if (!MakeParentDirectory(mapping->OutputFile)) {
  1064. LogFileError(GenT::MOC, mapping->OutputFile,
  1065. "Could not create parent directory.");
  1066. return false;
  1067. }
  1068. // Add moc job
  1069. Gen()->WorkerPool().EmplaceJob<JobMocT>(mapping, std::move(reason));
  1070. // Check if a moc job for a mocs_compilation.cpp entry was generated
  1071. if (compFile) {
  1072. MocEval().CompUpdated = true;
  1073. }
  1074. }
  1075. return true;
  1076. }
  1077. bool cmQtAutoMocUic::JobGenerateT::MocUpdate(MappingT const& mapping,
  1078. std::string* reason) const
  1079. {
  1080. std::string const& sourceFile = mapping.SourceFile->FileName;
  1081. std::string const& outputFile = mapping.OutputFile;
  1082. // Test if the output file exists
  1083. cmFileTime outputFileTime;
  1084. if (!outputFileTime.Load(outputFile)) {
  1085. if (reason != nullptr) {
  1086. *reason = "Generating ";
  1087. *reason += Quoted(outputFile);
  1088. *reason += ", because it doesn't exist, from ";
  1089. *reason += Quoted(sourceFile);
  1090. }
  1091. return true;
  1092. }
  1093. // Test if any setting changed
  1094. if (MocConst().SettingsChanged) {
  1095. if (reason != nullptr) {
  1096. *reason = "Generating ";
  1097. *reason += Quoted(outputFile);
  1098. *reason += ", because the uic settings changed, from ";
  1099. *reason += Quoted(sourceFile);
  1100. }
  1101. return true;
  1102. }
  1103. // Test if the source file is newer
  1104. if (outputFileTime.Older(mapping.SourceFile->FileTime)) {
  1105. if (reason != nullptr) {
  1106. *reason = "Generating ";
  1107. *reason += Quoted(outputFile);
  1108. *reason += ", because it's older than its source file, from ";
  1109. *reason += Quoted(sourceFile);
  1110. }
  1111. return true;
  1112. }
  1113. // Test if the moc_predefs file is newer
  1114. if (!MocConst().PredefsFileAbs.empty()) {
  1115. if (outputFileTime.Older(MocEval().PredefsTime)) {
  1116. if (reason != nullptr) {
  1117. *reason = "Generating ";
  1118. *reason += Quoted(outputFile);
  1119. *reason += ", because it's older than ";
  1120. *reason += Quoted(MocConst().PredefsFileAbs);
  1121. *reason += ", from ";
  1122. *reason += Quoted(sourceFile);
  1123. }
  1124. return true;
  1125. }
  1126. }
  1127. // Test if the moc executable is newer
  1128. if (outputFileTime.Older(MocConst().ExecutableTime)) {
  1129. if (reason != nullptr) {
  1130. *reason = "Generating ";
  1131. *reason += Quoted(outputFile);
  1132. *reason += ", because it's older than the moc executable, from ";
  1133. *reason += Quoted(sourceFile);
  1134. }
  1135. return true;
  1136. }
  1137. // Test if a dependency file is newer
  1138. {
  1139. // Check dependency timestamps
  1140. std::string const sourceDir = SubDirPrefix(sourceFile);
  1141. for (std::string const& dep : mapping.SourceFile->ParseData->Moc.Depends) {
  1142. // Find dependency file
  1143. auto const depMatch = MocFindDependency(sourceDir, dep);
  1144. if (depMatch.first.empty()) {
  1145. Log().WarningFile(GenT::MOC, sourceFile,
  1146. "Could not find dependency file " + Quoted(dep));
  1147. continue;
  1148. }
  1149. // Test if dependency file is older
  1150. if (outputFileTime.Older(depMatch.second)) {
  1151. if (reason != nullptr) {
  1152. *reason = "Generating ";
  1153. *reason += Quoted(outputFile);
  1154. *reason += ", because it's older than its dependency file ";
  1155. *reason += Quoted(depMatch.first);
  1156. *reason += ", from ";
  1157. *reason += Quoted(sourceFile);
  1158. }
  1159. return true;
  1160. }
  1161. }
  1162. }
  1163. return false;
  1164. }
  1165. std::pair<std::string, cmFileTime>
  1166. cmQtAutoMocUic::JobGenerateT::MocFindDependency(
  1167. std::string const& sourceDir, std::string const& includeString) const
  1168. {
  1169. typedef std::pair<std::string, cmFileTime> ResPair;
  1170. // Search in vicinity of the source
  1171. {
  1172. ResPair res{ sourceDir + includeString, {} };
  1173. if (res.second.Load(res.first)) {
  1174. return res;
  1175. }
  1176. }
  1177. // Search in include directories
  1178. for (std::string const& includePath : MocConst().IncludePaths) {
  1179. ResPair res{ includePath, {} };
  1180. res.first += '/';
  1181. res.first += includeString;
  1182. if (res.second.Load(res.first)) {
  1183. return res;
  1184. }
  1185. }
  1186. // Return empty
  1187. return ResPair();
  1188. }
  1189. bool cmQtAutoMocUic::JobGenerateT::UicGenerate(
  1190. MappingHandleT const& mapping) const
  1191. {
  1192. std::unique_ptr<std::string> reason;
  1193. if (Log().Verbose()) {
  1194. reason = cm::make_unique<std::string>();
  1195. }
  1196. if (UicUpdate(*mapping, reason.get())) {
  1197. // Create the parent directory
  1198. if (!MakeParentDirectory(mapping->OutputFile)) {
  1199. LogFileError(GenT::UIC, mapping->OutputFile,
  1200. "Could not create parent directory.");
  1201. return false;
  1202. }
  1203. // Add uic job
  1204. Gen()->WorkerPool().EmplaceJob<JobUicT>(mapping, std::move(reason));
  1205. }
  1206. return true;
  1207. }
  1208. bool cmQtAutoMocUic::JobGenerateT::UicUpdate(MappingT const& mapping,
  1209. std::string* reason) const
  1210. {
  1211. std::string const& sourceFile = mapping.SourceFile->FileName;
  1212. std::string const& outputFile = mapping.OutputFile;
  1213. // Test if the build file exists
  1214. cmFileTime outputFileTime;
  1215. if (!outputFileTime.Load(outputFile)) {
  1216. if (reason != nullptr) {
  1217. *reason = "Generating ";
  1218. *reason += Quoted(outputFile);
  1219. *reason += ", because it doesn't exist, from ";
  1220. *reason += Quoted(sourceFile);
  1221. }
  1222. return true;
  1223. }
  1224. // Test if the uic settings changed
  1225. if (UicConst().SettingsChanged) {
  1226. if (reason != nullptr) {
  1227. *reason = "Generating ";
  1228. *reason += Quoted(outputFile);
  1229. *reason += ", because the uic settings changed, from ";
  1230. *reason += Quoted(sourceFile);
  1231. }
  1232. return true;
  1233. }
  1234. // Test if the source file is newer
  1235. if (outputFileTime.Older(mapping.SourceFile->FileTime)) {
  1236. if (reason != nullptr) {
  1237. *reason = "Generating ";
  1238. *reason += Quoted(outputFile);
  1239. *reason += " because it's older than the source file ";
  1240. *reason += Quoted(sourceFile);
  1241. }
  1242. return true;
  1243. }
  1244. // Test if the uic executable is newer
  1245. if (outputFileTime.Older(UicConst().ExecutableTime)) {
  1246. if (reason != nullptr) {
  1247. *reason = "Generating ";
  1248. *reason += Quoted(outputFile);
  1249. *reason += ", because it's older than the uic executable, from ";
  1250. *reason += Quoted(sourceFile);
  1251. }
  1252. return true;
  1253. }
  1254. return false;
  1255. }
  1256. void cmQtAutoMocUic::JobMocT::Process()
  1257. {
  1258. std::string const& sourceFile = Mapping->SourceFile->FileName;
  1259. std::string const& outputFile = Mapping->OutputFile;
  1260. // Compose moc command
  1261. std::vector<std::string> cmd;
  1262. cmd.push_back(MocConst().Executable);
  1263. // Add options
  1264. cmAppend(cmd, MocConst().AllOptions);
  1265. // Add predefs include
  1266. if (!MocConst().PredefsFileAbs.empty()) {
  1267. cmd.emplace_back("--include");
  1268. cmd.push_back(MocConst().PredefsFileAbs);
  1269. }
  1270. cmd.emplace_back("-o");
  1271. cmd.push_back(outputFile);
  1272. cmd.push_back(sourceFile);
  1273. // Execute moc command
  1274. cmWorkerPool::ProcessResultT result;
  1275. if (RunProcess(GenT::MOC, result, cmd, Reason.get())) {
  1276. // Moc command success. Print moc output.
  1277. if (!result.StdOut.empty()) {
  1278. Log().Info(GenT::MOC, result.StdOut);
  1279. }
  1280. } else {
  1281. // Moc command failed
  1282. std::string msg =
  1283. cmStrCat("The moc process failed to compile\n ", Quoted(sourceFile),
  1284. "\ninto\n ", Quoted(outputFile));
  1285. if (Mapping->IncluderFiles.empty()) {
  1286. msg += ".\n";
  1287. } else {
  1288. msg += "\nincluded by\n";
  1289. for (auto const& item : Mapping->IncluderFiles) {
  1290. msg += " ";
  1291. msg += Quoted(item->FileName);
  1292. msg += '\n';
  1293. }
  1294. }
  1295. msg += result.ErrorMessage;
  1296. LogCommandError(GenT::MOC, msg, cmd, result.StdOut);
  1297. }
  1298. }
  1299. void cmQtAutoMocUic::JobUicT::Process()
  1300. {
  1301. std::string const& sourceFile = Mapping->SourceFile->FileName;
  1302. std::string const& outputFile = Mapping->OutputFile;
  1303. // Compose uic command
  1304. std::vector<std::string> cmd;
  1305. cmd.push_back(UicConst().Executable);
  1306. {
  1307. std::vector<std::string> allOpts = UicConst().TargetOptions;
  1308. auto optionIt = UicConst().Options.find(sourceFile);
  1309. if (optionIt != UicConst().Options.end()) {
  1310. UicMergeOptions(allOpts, optionIt->second,
  1311. (BaseConst().QtVersionMajor == 5));
  1312. }
  1313. cmAppend(cmd, allOpts);
  1314. }
  1315. cmd.emplace_back("-o");
  1316. cmd.emplace_back(outputFile);
  1317. cmd.emplace_back(sourceFile);
  1318. cmWorkerPool::ProcessResultT result;
  1319. if (RunProcess(GenT::UIC, result, cmd, Reason.get())) {
  1320. // Uic command success
  1321. // Print uic output
  1322. if (!result.StdOut.empty()) {
  1323. Log().Info(GenT::UIC, result.StdOut);
  1324. }
  1325. } else {
  1326. // Uic command failed
  1327. std::string msg =
  1328. cmStrCat("The uic process failed to compile\n ", Quoted(sourceFile),
  1329. "\ninto\n ", Quoted(outputFile), "\nincluded by\n");
  1330. for (auto const& item : Mapping->IncluderFiles) {
  1331. msg += " ";
  1332. msg += Quoted(item->FileName);
  1333. msg += '\n';
  1334. }
  1335. msg += result.ErrorMessage;
  1336. LogCommandError(GenT::UIC, msg, cmd, result.StdOut);
  1337. }
  1338. }
  1339. void cmQtAutoMocUic::JobMocsCompilationT::Process()
  1340. {
  1341. // Compose mocs compilation file content
  1342. std::string content =
  1343. "// This file is autogenerated. Changes will be overwritten.\n";
  1344. if (MocEval().CompFiles.empty()) {
  1345. // Placeholder content
  1346. content += "// No files found that require moc or the moc files are "
  1347. "included\n";
  1348. content += "enum some_compilers { need_more_than_nothing };\n";
  1349. } else {
  1350. // Valid content
  1351. char const clampB = BaseConst().MultiConfig ? '<' : '"';
  1352. char const clampE = BaseConst().MultiConfig ? '>' : '"';
  1353. for (std::string const& mocfile : MocEval().CompFiles) {
  1354. content += "#include ";
  1355. content += clampB;
  1356. content += mocfile;
  1357. content += clampE;
  1358. content += '\n';
  1359. }
  1360. }
  1361. std::string const& compAbs = MocConst().CompFileAbs;
  1362. if (cmQtAutoGenerator::FileDiffers(compAbs, content)) {
  1363. // Actually write mocs compilation file
  1364. if (Log().Verbose()) {
  1365. Log().Info(GenT::MOC, "Generating MOC compilation " + compAbs);
  1366. }
  1367. if (!FileWrite(compAbs, content)) {
  1368. LogFileError(GenT::MOC, compAbs,
  1369. "mocs compilation file writing failed.");
  1370. }
  1371. } else if (MocEval().CompUpdated) {
  1372. // Only touch mocs compilation file
  1373. if (Log().Verbose()) {
  1374. Log().Info(GenT::MOC, "Touching mocs compilation " + compAbs);
  1375. }
  1376. if (!cmSystemTools::Touch(compAbs, false)) {
  1377. LogFileError(GenT::MOC, compAbs,
  1378. "mocs compilation file touching failed.");
  1379. }
  1380. }
  1381. }
  1382. void cmQtAutoMocUic::JobFinishT::Process()
  1383. {
  1384. Gen()->AbortSuccess();
  1385. }
  1386. cmQtAutoMocUic::cmQtAutoMocUic() = default;
  1387. cmQtAutoMocUic::~cmQtAutoMocUic() = default;
  1388. bool cmQtAutoMocUic::Init(cmMakefile* makefile)
  1389. {
  1390. // Utility lambdas
  1391. auto InfoGet = [makefile](const char* key) {
  1392. return makefile->GetSafeDefinition(key);
  1393. };
  1394. auto InfoGetBool = [makefile](const char* key) {
  1395. return makefile->IsOn(key);
  1396. };
  1397. auto InfoGetList = [makefile](const char* key) -> std::vector<std::string> {
  1398. std::vector<std::string> list;
  1399. cmExpandList(makefile->GetSafeDefinition(key), list);
  1400. return list;
  1401. };
  1402. auto InfoGetLists =
  1403. [makefile](const char* key) -> std::vector<std::vector<std::string>> {
  1404. std::vector<std::vector<std::string>> lists;
  1405. {
  1406. std::string const value = makefile->GetSafeDefinition(key);
  1407. std::string::size_type pos = 0;
  1408. while (pos < value.size()) {
  1409. std::string::size_type next = value.find(ListSep, pos);
  1410. std::string::size_type length =
  1411. (next != std::string::npos) ? next - pos : value.size() - pos;
  1412. // Remove enclosing braces
  1413. if (length >= 2) {
  1414. std::string::const_iterator itBeg = value.begin() + (pos + 1);
  1415. std::string::const_iterator itEnd = itBeg + (length - 2);
  1416. lists.emplace_back(cmExpandedList(std::string(itBeg, itEnd)));
  1417. }
  1418. pos += length;
  1419. pos += ListSep.size();
  1420. }
  1421. }
  1422. return lists;
  1423. };
  1424. auto InfoGetConfig = [makefile, this](const char* key) -> std::string {
  1425. const char* valueConf = nullptr;
  1426. {
  1427. std::string keyConf = cmStrCat(key, '_', InfoConfig());
  1428. valueConf = makefile->GetDefinition(keyConf);
  1429. }
  1430. if (valueConf == nullptr) {
  1431. return makefile->GetSafeDefinition(key);
  1432. }
  1433. return std::string(valueConf);
  1434. };
  1435. auto InfoGetConfigList =
  1436. [&InfoGetConfig](const char* key) -> std::vector<std::string> {
  1437. std::vector<std::string> list;
  1438. cmExpandList(InfoGetConfig(key), list);
  1439. return list;
  1440. };
  1441. auto LogInfoError = [this](std::string const& msg) -> bool {
  1442. std::ostringstream err;
  1443. err << "In " << Quoted(this->InfoFile()) << ":\n" << msg;
  1444. this->Log().Error(GenT::GEN, err.str());
  1445. return false;
  1446. };
  1447. auto MatchSizes = [&LogInfoError](const char* keyA, const char* keyB,
  1448. std::size_t sizeA,
  1449. std::size_t sizeB) -> bool {
  1450. if (sizeA == sizeB) {
  1451. return true;
  1452. }
  1453. std::ostringstream err;
  1454. err << "Lists sizes mismatch " << keyA << '(' << sizeA << ") " << keyB
  1455. << '(' << sizeB << ')';
  1456. return LogInfoError(err.str());
  1457. };
  1458. // -- Read info file
  1459. if (!makefile->ReadListFile(InfoFile())) {
  1460. return LogInfoError("File processing failed");
  1461. }
  1462. // -- Meta
  1463. Logger_.RaiseVerbosity(InfoGet("AM_VERBOSITY"));
  1464. BaseConst_.MultiConfig = InfoGetBool("AM_MULTI_CONFIG");
  1465. {
  1466. unsigned long num = 1;
  1467. if (cmStrToULong(InfoGet("AM_PARALLEL"), &num)) {
  1468. num = std::max<unsigned long>(num, 1);
  1469. num = std::min<unsigned long>(num, ParallelMax);
  1470. }
  1471. WorkerPool_.SetThreadCount(static_cast<unsigned int>(num));
  1472. }
  1473. BaseConst_.HeaderExtensions =
  1474. makefile->GetCMakeInstance()->GetHeaderExtensions();
  1475. // - Files and directories
  1476. BaseConst_.IncludeProjectDirsBefore =
  1477. InfoGetBool("AM_CMAKE_INCLUDE_DIRECTORIES_PROJECT_BEFORE");
  1478. BaseConst_.ProjectSourceDir = InfoGet("AM_CMAKE_SOURCE_DIR");
  1479. BaseConst_.ProjectBinaryDir = InfoGet("AM_CMAKE_BINARY_DIR");
  1480. BaseConst_.CurrentSourceDir = InfoGet("AM_CMAKE_CURRENT_SOURCE_DIR");
  1481. BaseConst_.CurrentBinaryDir = InfoGet("AM_CMAKE_CURRENT_BINARY_DIR");
  1482. BaseConst_.AutogenBuildDir = InfoGet("AM_BUILD_DIR");
  1483. if (BaseConst_.AutogenBuildDir.empty()) {
  1484. return LogInfoError("Autogen build directory missing.");
  1485. }
  1486. BaseConst_.AutogenIncludeDir = InfoGetConfig("AM_INCLUDE_DIR");
  1487. if (BaseConst_.AutogenIncludeDir.empty()) {
  1488. return LogInfoError("Autogen include directory missing.");
  1489. }
  1490. BaseConst_.CMakeExecutable = InfoGetConfig("AM_CMAKE_EXECUTABLE");
  1491. if (BaseConst_.CMakeExecutable.empty()) {
  1492. return LogInfoError("CMake executable file name missing.");
  1493. }
  1494. if (!BaseConst_.CMakeExecutableTime.Load(BaseConst_.CMakeExecutable)) {
  1495. std::string error =
  1496. cmStrCat("The CMake executable ", Quoted(BaseConst_.CMakeExecutable),
  1497. " does not exist.");
  1498. return LogInfoError(error);
  1499. }
  1500. BaseConst_.ParseCacheFile = InfoGetConfig("AM_PARSE_CACHE_FILE");
  1501. if (BaseConst_.ParseCacheFile.empty()) {
  1502. return LogInfoError("Parse cache file name missing.");
  1503. }
  1504. // - Settings file
  1505. SettingsFile_ = InfoGetConfig("AM_SETTINGS_FILE");
  1506. if (SettingsFile_.empty()) {
  1507. return LogInfoError("Settings file name missing.");
  1508. }
  1509. // - Qt environment
  1510. {
  1511. unsigned long qtv = BaseConst_.QtVersionMajor;
  1512. if (cmStrToULong(InfoGet("AM_QT_VERSION_MAJOR"), &qtv)) {
  1513. BaseConst_.QtVersionMajor = static_cast<unsigned int>(qtv);
  1514. }
  1515. }
  1516. // - Moc
  1517. MocConst_.Executable = InfoGet("AM_QT_MOC_EXECUTABLE");
  1518. if (!MocConst().Executable.empty()) {
  1519. MocConst_.Enabled = true;
  1520. // Load the executable file time
  1521. if (!MocConst_.ExecutableTime.Load(MocConst_.Executable)) {
  1522. std::string error =
  1523. cmStrCat("The moc executable ", Quoted(MocConst_.Executable),
  1524. " does not exist.");
  1525. return LogInfoError(error);
  1526. }
  1527. for (std::string& sfl : InfoGetList("AM_MOC_SKIP")) {
  1528. MocConst_.SkipList.insert(std::move(sfl));
  1529. }
  1530. MocConst_.Definitions = InfoGetConfigList("AM_MOC_DEFINITIONS");
  1531. MocConst_.IncludePaths = InfoGetConfigList("AM_MOC_INCLUDES");
  1532. MocConst_.Options = InfoGetList("AM_MOC_OPTIONS");
  1533. MocConst_.RelaxedMode = InfoGetBool("AM_MOC_RELAXED_MODE");
  1534. for (std::string const& item : InfoGetList("AM_MOC_MACRO_NAMES")) {
  1535. MocConst_.MacroFilters.emplace_back(
  1536. item, ("[\n][ \t]*{?[ \t]*" + item).append("[^a-zA-Z0-9_]"));
  1537. }
  1538. {
  1539. auto addFilter = [this, &LogInfoError](std::string const& key,
  1540. std::string const& exp) -> bool {
  1541. auto filterErr = [&LogInfoError, &key, &exp](const char* err) -> bool {
  1542. std::ostringstream ferr;
  1543. ferr << "AUTOMOC_DEPEND_FILTERS: " << err << '\n';
  1544. ferr << " Key: " << Quoted(key) << '\n';
  1545. ferr << " Exp: " << Quoted(exp) << '\n';
  1546. return LogInfoError(ferr.str());
  1547. };
  1548. if (key.empty()) {
  1549. return filterErr("Key is empty");
  1550. }
  1551. if (exp.empty()) {
  1552. return filterErr("Regular expression is empty");
  1553. }
  1554. this->MocConst_.DependFilters.emplace_back(key, exp);
  1555. if (!this->MocConst_.DependFilters.back().Exp.is_valid()) {
  1556. return filterErr("Regular expression compiling failed");
  1557. }
  1558. return true;
  1559. };
  1560. // Insert default filter for Q_PLUGIN_METADATA
  1561. if (BaseConst().QtVersionMajor != 4) {
  1562. if (!addFilter("Q_PLUGIN_METADATA",
  1563. "[\n][ \t]*Q_PLUGIN_METADATA[ \t]*\\("
  1564. "[^\\)]*FILE[ \t]*\"([^\"]+)\"")) {
  1565. return false;
  1566. }
  1567. }
  1568. // Insert user defined dependency filters
  1569. std::vector<std::string> flts = InfoGetList("AM_MOC_DEPEND_FILTERS");
  1570. if ((flts.size() % 2) != 0) {
  1571. return LogInfoError(
  1572. "AUTOMOC_DEPEND_FILTERS list size is not a multiple of 2");
  1573. }
  1574. for (auto itC = flts.begin(), itE = flts.end(); itC != itE; itC += 2) {
  1575. if (!addFilter(*itC, *(itC + 1))) {
  1576. return false;
  1577. }
  1578. }
  1579. }
  1580. MocConst_.PredefsCmd = InfoGetList("AM_MOC_PREDEFS_CMD");
  1581. }
  1582. // - Uic
  1583. UicConst_.Executable = InfoGet("AM_QT_UIC_EXECUTABLE");
  1584. if (!UicConst().Executable.empty()) {
  1585. UicConst_.Enabled = true;
  1586. // Load the executable file time
  1587. if (!UicConst_.ExecutableTime.Load(UicConst_.Executable)) {
  1588. std::string error =
  1589. cmStrCat("The uic executable ", Quoted(UicConst_.Executable),
  1590. " does not exist.");
  1591. return LogInfoError(error);
  1592. }
  1593. for (std::string& sfl : InfoGetList("AM_UIC_SKIP")) {
  1594. UicConst_.SkipList.insert(std::move(sfl));
  1595. }
  1596. UicConst_.SearchPaths = InfoGetList("AM_UIC_SEARCH_PATHS");
  1597. UicConst_.TargetOptions = InfoGetConfigList("AM_UIC_TARGET_OPTIONS");
  1598. {
  1599. const char* keyFiles = "AM_UIC_OPTIONS_FILES";
  1600. const char* keyOpts = "AM_UIC_OPTIONS_OPTIONS";
  1601. auto sources = InfoGetList(keyFiles);
  1602. auto options = InfoGetLists(keyOpts);
  1603. if (!MatchSizes(keyFiles, keyOpts, sources.size(), options.size())) {
  1604. return false;
  1605. }
  1606. auto fitEnd = sources.cend();
  1607. auto fit = sources.begin();
  1608. auto oit = options.begin();
  1609. while (fit != fitEnd) {
  1610. UicConst_.Options[*fit] = std::move(*oit);
  1611. ++fit;
  1612. ++oit;
  1613. }
  1614. }
  1615. }
  1616. // - Headers and sources
  1617. {
  1618. auto makeSource =
  1619. [&LogInfoError](std::string const& fileName,
  1620. std::string const& fileFlags) -> SourceFileHandleT {
  1621. if (fileFlags.size() != 2) {
  1622. LogInfoError("Invalid file flags string size");
  1623. return SourceFileHandleT();
  1624. }
  1625. cmFileTime fileTime;
  1626. if (!fileTime.Load(fileName)) {
  1627. LogInfoError("The source file " + cmQtAutoGen::Quoted(fileName) +
  1628. " does not exist.");
  1629. return SourceFileHandleT();
  1630. }
  1631. SourceFileHandleT sfh = std::make_shared<SourceFileT>(fileName);
  1632. sfh->FileTime = fileTime;
  1633. sfh->Moc = (fileFlags[0] == 'M');
  1634. sfh->Uic = (fileFlags[1] == 'U');
  1635. return sfh;
  1636. };
  1637. // Headers
  1638. {
  1639. // Get file lists
  1640. const char *keyFiles = "AM_HEADERS", *keyFlags = "AM_HEADERS_FLAGS";
  1641. std::vector<std::string> files = InfoGetList(keyFiles);
  1642. std::vector<std::string> flags = InfoGetList(keyFlags);
  1643. std::vector<std::string> builds;
  1644. if (!MatchSizes(keyFiles, keyFlags, files.size(), flags.size())) {
  1645. return false;
  1646. }
  1647. if (MocConst().Enabled) {
  1648. const char* keyPaths = "AM_HEADERS_BUILD_PATHS";
  1649. builds = InfoGetList(keyPaths);
  1650. if (!MatchSizes(keyFiles, keyPaths, files.size(), builds.size())) {
  1651. return false;
  1652. }
  1653. }
  1654. // Process file lists
  1655. for (std::size_t ii = 0; ii != files.size(); ++ii) {
  1656. std::string& fileName(files[ii]);
  1657. SourceFileHandleT sfh = makeSource(fileName, flags[ii]);
  1658. if (!sfh) {
  1659. return false;
  1660. }
  1661. if (MocConst().Enabled) {
  1662. sfh->BuildPath = std::move(builds[ii]);
  1663. if (sfh->BuildPath.empty()) {
  1664. Log().ErrorFile(GenT::GEN, this->InfoFile(),
  1665. "Header file build path is empty");
  1666. return false;
  1667. }
  1668. }
  1669. BaseEval().Headers.emplace(std::move(fileName), std::move(sfh));
  1670. }
  1671. }
  1672. // Sources
  1673. {
  1674. const char *keyFiles = "AM_SOURCES", *keyFlags = "AM_SOURCES_FLAGS";
  1675. std::vector<std::string> files = InfoGetList(keyFiles);
  1676. std::vector<std::string> flags = InfoGetList(keyFlags);
  1677. if (!MatchSizes(keyFiles, keyFlags, files.size(), flags.size())) {
  1678. return false;
  1679. }
  1680. // Process file lists
  1681. for (std::size_t ii = 0; ii != files.size(); ++ii) {
  1682. std::string& fileName(files[ii]);
  1683. SourceFileHandleT sfh = makeSource(fileName, flags[ii]);
  1684. if (!sfh) {
  1685. return false;
  1686. }
  1687. BaseEval().Sources.emplace(std::move(fileName), std::move(sfh));
  1688. }
  1689. }
  1690. }
  1691. // Init derived information
  1692. // ------------------------
  1693. // Moc variables
  1694. if (MocConst().Enabled) {
  1695. // Mocs compilation file
  1696. MocConst_.CompFileAbs = AbsoluteBuildPath("mocs_compilation.cpp");
  1697. // Moc predefs file
  1698. if (!MocConst_.PredefsCmd.empty()) {
  1699. MocConst_.PredefsFileRel = "moc_predefs";
  1700. if (BaseConst_.MultiConfig) {
  1701. MocConst_.PredefsFileRel += '_';
  1702. MocConst_.PredefsFileRel += InfoConfig();
  1703. }
  1704. MocConst_.PredefsFileRel += ".h";
  1705. MocConst_.PredefsFileAbs = AbsoluteBuildPath(MocConst().PredefsFileRel);
  1706. }
  1707. // Sort include directories on demand
  1708. if (BaseConst().IncludeProjectDirsBefore) {
  1709. // Move strings to temporary list
  1710. std::list<std::string> includes(MocConst().IncludePaths.begin(),
  1711. MocConst().IncludePaths.end());
  1712. MocConst_.IncludePaths.clear();
  1713. MocConst_.IncludePaths.reserve(includes.size());
  1714. // Append project directories only
  1715. {
  1716. std::array<std::string const*, 2> const movePaths = {
  1717. { &BaseConst().ProjectBinaryDir, &BaseConst().ProjectSourceDir }
  1718. };
  1719. for (std::string const* ppath : movePaths) {
  1720. std::list<std::string>::iterator it = includes.begin();
  1721. while (it != includes.end()) {
  1722. std::string const& path = *it;
  1723. if (cmHasPrefix(path, *ppath)) {
  1724. MocConst_.IncludePaths.push_back(path);
  1725. it = includes.erase(it);
  1726. } else {
  1727. ++it;
  1728. }
  1729. }
  1730. }
  1731. }
  1732. // Append remaining directories
  1733. MocConst_.IncludePaths.insert(MocConst_.IncludePaths.end(),
  1734. includes.begin(), includes.end());
  1735. }
  1736. // Compose moc includes list
  1737. {
  1738. std::set<std::string> frameworkPaths;
  1739. for (std::string const& path : MocConst().IncludePaths) {
  1740. MocConst_.Includes.push_back("-I" + path);
  1741. // Extract framework path
  1742. if (cmHasLiteralSuffix(path, ".framework/Headers")) {
  1743. // Go up twice to get to the framework root
  1744. std::vector<std::string> pathComponents;
  1745. cmSystemTools::SplitPath(path, pathComponents);
  1746. frameworkPaths.emplace(cmSystemTools::JoinPath(
  1747. pathComponents.begin(), pathComponents.end() - 2));
  1748. }
  1749. }
  1750. // Append framework includes
  1751. for (std::string const& path : frameworkPaths) {
  1752. MocConst_.Includes.emplace_back("-F");
  1753. MocConst_.Includes.push_back(path);
  1754. }
  1755. }
  1756. // Setup single list with all options
  1757. {
  1758. // Add includes
  1759. MocConst_.AllOptions.insert(MocConst_.AllOptions.end(),
  1760. MocConst().Includes.begin(),
  1761. MocConst().Includes.end());
  1762. // Add definitions
  1763. for (std::string const& def : MocConst().Definitions) {
  1764. MocConst_.AllOptions.push_back("-D" + def);
  1765. }
  1766. // Add options
  1767. MocConst_.AllOptions.insert(MocConst_.AllOptions.end(),
  1768. MocConst().Options.begin(),
  1769. MocConst().Options.end());
  1770. }
  1771. }
  1772. return true;
  1773. }
  1774. template <class JOBTYPE>
  1775. void cmQtAutoMocUic::CreateParseJobs(SourceFileMapT const& sourceMap)
  1776. {
  1777. cmFileTime const parseCacheTime = BaseEval().ParseCacheTime;
  1778. ParseCacheT& parseCache = BaseEval().ParseCache;
  1779. for (auto& src : sourceMap) {
  1780. // Get or create the file parse data reference
  1781. ParseCacheT::GetOrInsertT cacheEntry = parseCache.GetOrInsert(src.first);
  1782. src.second->ParseData = std::move(cacheEntry.first);
  1783. // Create a parse job if the cache file was missing or is older
  1784. if (cacheEntry.second || src.second->FileTime.Newer(parseCacheTime)) {
  1785. BaseEval().ParseCacheChanged = true;
  1786. WorkerPool().EmplaceJob<JOBTYPE>(src.second);
  1787. }
  1788. }
  1789. }
  1790. void cmQtAutoMocUic::InitJobs()
  1791. {
  1792. // Add moc_predefs.h job
  1793. if (MocConst().Enabled && !MocConst().PredefsCmd.empty()) {
  1794. WorkerPool().EmplaceJob<JobMocPredefsT>();
  1795. }
  1796. // Add header parse jobs
  1797. CreateParseJobs<JobParseHeaderT>(BaseEval().Headers);
  1798. // Add source parse jobs
  1799. CreateParseJobs<JobParseSourceT>(BaseEval().Sources);
  1800. // Add evaluate job
  1801. WorkerPool().EmplaceJob<JobEvaluateT>();
  1802. }
  1803. bool cmQtAutoMocUic::Process()
  1804. {
  1805. SettingsFileRead();
  1806. ParseCacheRead();
  1807. if (!CreateDirectories()) {
  1808. return false;
  1809. }
  1810. InitJobs();
  1811. if (!WorkerPool_.Process(this)) {
  1812. return false;
  1813. }
  1814. if (JobError_) {
  1815. return false;
  1816. }
  1817. if (!ParseCacheWrite()) {
  1818. return false;
  1819. }
  1820. if (!SettingsFileWrite()) {
  1821. return false;
  1822. }
  1823. return true;
  1824. }
  1825. void cmQtAutoMocUic::SettingsFileRead()
  1826. {
  1827. // Compose current settings strings
  1828. {
  1829. cmCryptoHash cryptoHash(cmCryptoHash::AlgoSHA256);
  1830. std::string const sep(";");
  1831. auto cha = [&cryptoHash, &sep](std::string const& value) {
  1832. cryptoHash.Append(value);
  1833. cryptoHash.Append(sep);
  1834. };
  1835. if (MocConst_.Enabled) {
  1836. cryptoHash.Initialize();
  1837. cha(MocConst().Executable);
  1838. for (auto const& value : MocConst().AllOptions) {
  1839. cha(value);
  1840. }
  1841. cha(BaseConst().IncludeProjectDirsBefore ? "TRUE" : "FALSE");
  1842. for (auto const& value : MocConst().PredefsCmd) {
  1843. cha(value);
  1844. }
  1845. for (auto const& filter : MocConst().DependFilters) {
  1846. cha(filter.Key);
  1847. }
  1848. for (auto const& filter : MocConst().MacroFilters) {
  1849. cha(filter.Key);
  1850. }
  1851. SettingsStringMoc_ = cryptoHash.FinalizeHex();
  1852. }
  1853. if (UicConst().Enabled) {
  1854. cryptoHash.Initialize();
  1855. cha(UicConst().Executable);
  1856. for (auto const& value : UicConst().TargetOptions) {
  1857. cha(value);
  1858. }
  1859. for (const auto& item : UicConst().Options) {
  1860. cha(item.first);
  1861. for (auto const& svalue : item.second) {
  1862. cha(svalue);
  1863. }
  1864. }
  1865. SettingsStringUic_ = cryptoHash.FinalizeHex();
  1866. }
  1867. }
  1868. // Read old settings and compare
  1869. {
  1870. std::string content;
  1871. if (cmQtAutoGenerator::FileRead(content, SettingsFile_)) {
  1872. if (MocConst().Enabled) {
  1873. if (SettingsStringMoc_ != SettingsFind(content, "moc")) {
  1874. MocConst_.SettingsChanged = true;
  1875. }
  1876. }
  1877. if (UicConst().Enabled) {
  1878. if (SettingsStringUic_ != SettingsFind(content, "uic")) {
  1879. UicConst_.SettingsChanged = true;
  1880. }
  1881. }
  1882. // In case any setting changed remove the old settings file.
  1883. // This triggers a full rebuild on the next run if the current
  1884. // build is aborted before writing the current settings in the end.
  1885. if (MocConst().SettingsChanged || UicConst().SettingsChanged) {
  1886. cmSystemTools::RemoveFile(SettingsFile_);
  1887. }
  1888. } else {
  1889. // Settings file read failed
  1890. if (MocConst().Enabled) {
  1891. MocConst_.SettingsChanged = true;
  1892. }
  1893. if (UicConst().Enabled) {
  1894. UicConst_.SettingsChanged = true;
  1895. }
  1896. }
  1897. }
  1898. }
  1899. bool cmQtAutoMocUic::SettingsFileWrite()
  1900. {
  1901. // Only write if any setting changed
  1902. if (MocConst().SettingsChanged || UicConst().SettingsChanged) {
  1903. if (Log().Verbose()) {
  1904. Log().Info(GenT::GEN, "Writing settings file " + Quoted(SettingsFile_));
  1905. }
  1906. // Compose settings file content
  1907. std::string content;
  1908. {
  1909. auto SettingAppend = [&content](const char* key,
  1910. std::string const& value) {
  1911. if (!value.empty()) {
  1912. content += key;
  1913. content += ':';
  1914. content += value;
  1915. content += '\n';
  1916. }
  1917. };
  1918. SettingAppend("moc", SettingsStringMoc_);
  1919. SettingAppend("uic", SettingsStringUic_);
  1920. }
  1921. // Write settings file
  1922. std::string error;
  1923. if (!cmQtAutoGenerator::FileWrite(SettingsFile_, content, &error)) {
  1924. Log().ErrorFile(GenT::GEN, SettingsFile_,
  1925. "Settings file writing failed. " + error);
  1926. // Remove old settings file to trigger a full rebuild on the next run
  1927. cmSystemTools::RemoveFile(SettingsFile_);
  1928. return false;
  1929. }
  1930. }
  1931. return true;
  1932. }
  1933. void cmQtAutoMocUic::ParseCacheRead()
  1934. {
  1935. const char* reason = nullptr;
  1936. // Don't read the cache if it is invalid
  1937. if (!BaseEval().ParseCacheTime.Load(BaseConst().ParseCacheFile)) {
  1938. reason = "Refreshing parse cache because it doesn't exist.";
  1939. } else if (MocConst().SettingsChanged || UicConst().SettingsChanged) {
  1940. reason = "Refreshing parse cache because the settings changed.";
  1941. } else if (BaseEval().ParseCacheTime.Older(
  1942. BaseConst().CMakeExecutableTime)) {
  1943. reason =
  1944. "Refreshing parse cache because it is older than the CMake executable.";
  1945. }
  1946. if (reason != nullptr) {
  1947. // Don't read but refresh the complete parse cache
  1948. if (Log().Verbose()) {
  1949. Log().Info(GenT::GEN, reason);
  1950. }
  1951. BaseEval().ParseCacheChanged = true;
  1952. } else {
  1953. // Read parse cache
  1954. BaseEval().ParseCache.ReadFromFile(BaseConst().ParseCacheFile);
  1955. }
  1956. }
  1957. bool cmQtAutoMocUic::ParseCacheWrite()
  1958. {
  1959. if (BaseEval().ParseCacheChanged) {
  1960. if (Log().Verbose()) {
  1961. Log().Info(GenT::GEN,
  1962. "Writing parse cache file " +
  1963. Quoted(BaseConst().ParseCacheFile));
  1964. }
  1965. if (!BaseEval().ParseCache.WriteToFile(BaseConst().ParseCacheFile)) {
  1966. Log().ErrorFile(GenT::GEN, BaseConst().ParseCacheFile,
  1967. "Parse cache file writing failed.");
  1968. return false;
  1969. }
  1970. }
  1971. return true;
  1972. }
  1973. bool cmQtAutoMocUic::CreateDirectories()
  1974. {
  1975. // Create AUTOGEN include directory
  1976. if (!cmSystemTools::MakeDirectory(BaseConst().AutogenIncludeDir)) {
  1977. Log().ErrorFile(GenT::GEN, BaseConst().AutogenIncludeDir,
  1978. "Could not create directory.");
  1979. return false;
  1980. }
  1981. return true;
  1982. }
  1983. void cmQtAutoMocUic::Abort(bool error)
  1984. {
  1985. if (error) {
  1986. JobError_.store(true);
  1987. }
  1988. WorkerPool_.Abort();
  1989. }
  1990. std::string cmQtAutoMocUic::AbsoluteBuildPath(
  1991. std::string const& relativePath) const
  1992. {
  1993. std::string res(BaseConst().AutogenBuildDir);
  1994. res += '/';
  1995. res += relativePath;
  1996. return res;
  1997. }
  1998. std::string cmQtAutoMocUic::AbsoluteIncludePath(
  1999. std::string const& relativePath) const
  2000. {
  2001. std::string res(BaseConst().AutogenIncludeDir);
  2002. res += '/';
  2003. res += relativePath;
  2004. return res;
  2005. }