cmQtAutoMocUic.cxx 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153
  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. cmSystemTools::ExpandListArgument(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(
  1417. cmSystemTools::ExpandedListArgument(std::string(itBeg, itEnd)));
  1418. }
  1419. pos += length;
  1420. pos += ListSep.size();
  1421. }
  1422. }
  1423. return lists;
  1424. };
  1425. auto InfoGetConfig = [makefile, this](const char* key) -> std::string {
  1426. const char* valueConf = nullptr;
  1427. {
  1428. std::string keyConf = cmStrCat(key, '_', InfoConfig());
  1429. valueConf = makefile->GetDefinition(keyConf);
  1430. }
  1431. if (valueConf == nullptr) {
  1432. return makefile->GetSafeDefinition(key);
  1433. }
  1434. return std::string(valueConf);
  1435. };
  1436. auto InfoGetConfigList =
  1437. [&InfoGetConfig](const char* key) -> std::vector<std::string> {
  1438. std::vector<std::string> list;
  1439. cmSystemTools::ExpandListArgument(InfoGetConfig(key), list);
  1440. return list;
  1441. };
  1442. auto LogInfoError = [this](std::string const& msg) -> bool {
  1443. std::ostringstream err;
  1444. err << "In " << Quoted(this->InfoFile()) << ":\n" << msg;
  1445. this->Log().Error(GenT::GEN, err.str());
  1446. return false;
  1447. };
  1448. auto MatchSizes = [&LogInfoError](const char* keyA, const char* keyB,
  1449. std::size_t sizeA,
  1450. std::size_t sizeB) -> bool {
  1451. if (sizeA == sizeB) {
  1452. return true;
  1453. }
  1454. std::ostringstream err;
  1455. err << "Lists sizes mismatch " << keyA << '(' << sizeA << ") " << keyB
  1456. << '(' << sizeB << ')';
  1457. return LogInfoError(err.str());
  1458. };
  1459. // -- Read info file
  1460. if (!makefile->ReadListFile(InfoFile())) {
  1461. return LogInfoError("File processing failed");
  1462. }
  1463. // -- Meta
  1464. Logger_.RaiseVerbosity(InfoGet("AM_VERBOSITY"));
  1465. BaseConst_.MultiConfig = InfoGetBool("AM_MULTI_CONFIG");
  1466. {
  1467. unsigned long num = 1;
  1468. if (cmSystemTools::StringToULong(InfoGet("AM_PARALLEL").c_str(), &num)) {
  1469. num = std::max<unsigned long>(num, 1);
  1470. num = std::min<unsigned long>(num, ParallelMax);
  1471. }
  1472. WorkerPool_.SetThreadCount(static_cast<unsigned int>(num));
  1473. }
  1474. BaseConst_.HeaderExtensions =
  1475. makefile->GetCMakeInstance()->GetHeaderExtensions();
  1476. // - Files and directories
  1477. BaseConst_.IncludeProjectDirsBefore =
  1478. InfoGetBool("AM_CMAKE_INCLUDE_DIRECTORIES_PROJECT_BEFORE");
  1479. BaseConst_.ProjectSourceDir = InfoGet("AM_CMAKE_SOURCE_DIR");
  1480. BaseConst_.ProjectBinaryDir = InfoGet("AM_CMAKE_BINARY_DIR");
  1481. BaseConst_.CurrentSourceDir = InfoGet("AM_CMAKE_CURRENT_SOURCE_DIR");
  1482. BaseConst_.CurrentBinaryDir = InfoGet("AM_CMAKE_CURRENT_BINARY_DIR");
  1483. BaseConst_.AutogenBuildDir = InfoGet("AM_BUILD_DIR");
  1484. if (BaseConst_.AutogenBuildDir.empty()) {
  1485. return LogInfoError("Autogen build directory missing.");
  1486. }
  1487. BaseConst_.AutogenIncludeDir = InfoGetConfig("AM_INCLUDE_DIR");
  1488. if (BaseConst_.AutogenIncludeDir.empty()) {
  1489. return LogInfoError("Autogen include directory missing.");
  1490. }
  1491. BaseConst_.CMakeExecutable = InfoGetConfig("AM_CMAKE_EXECUTABLE");
  1492. if (BaseConst_.CMakeExecutable.empty()) {
  1493. return LogInfoError("CMake executable file name missing.");
  1494. }
  1495. if (!BaseConst_.CMakeExecutableTime.Load(BaseConst_.CMakeExecutable)) {
  1496. std::string error =
  1497. cmStrCat("The CMake executable ", Quoted(BaseConst_.CMakeExecutable),
  1498. " does not exist.");
  1499. return LogInfoError(error);
  1500. }
  1501. BaseConst_.ParseCacheFile = InfoGetConfig("AM_PARSE_CACHE_FILE");
  1502. if (BaseConst_.ParseCacheFile.empty()) {
  1503. return LogInfoError("Parse cache file name missing.");
  1504. }
  1505. // - Settings file
  1506. SettingsFile_ = InfoGetConfig("AM_SETTINGS_FILE");
  1507. if (SettingsFile_.empty()) {
  1508. return LogInfoError("Settings file name missing.");
  1509. }
  1510. // - Qt environment
  1511. {
  1512. unsigned long qtv = BaseConst_.QtVersionMajor;
  1513. if (cmSystemTools::StringToULong(InfoGet("AM_QT_VERSION_MAJOR").c_str(),
  1514. &qtv)) {
  1515. BaseConst_.QtVersionMajor = static_cast<unsigned int>(qtv);
  1516. }
  1517. }
  1518. // - Moc
  1519. MocConst_.Executable = InfoGet("AM_QT_MOC_EXECUTABLE");
  1520. if (!MocConst().Executable.empty()) {
  1521. MocConst_.Enabled = true;
  1522. // Load the executable file time
  1523. if (!MocConst_.ExecutableTime.Load(MocConst_.Executable)) {
  1524. std::string error =
  1525. cmStrCat("The moc executable ", Quoted(MocConst_.Executable),
  1526. " does not exist.");
  1527. return LogInfoError(error);
  1528. }
  1529. for (std::string& sfl : InfoGetList("AM_MOC_SKIP")) {
  1530. MocConst_.SkipList.insert(std::move(sfl));
  1531. }
  1532. MocConst_.Definitions = InfoGetConfigList("AM_MOC_DEFINITIONS");
  1533. MocConst_.IncludePaths = InfoGetConfigList("AM_MOC_INCLUDES");
  1534. MocConst_.Options = InfoGetList("AM_MOC_OPTIONS");
  1535. MocConst_.RelaxedMode = InfoGetBool("AM_MOC_RELAXED_MODE");
  1536. for (std::string const& item : InfoGetList("AM_MOC_MACRO_NAMES")) {
  1537. MocConst_.MacroFilters.emplace_back(
  1538. item, ("[\n][ \t]*{?[ \t]*" + item).append("[^a-zA-Z0-9_]"));
  1539. }
  1540. {
  1541. auto addFilter = [this, &LogInfoError](std::string const& key,
  1542. std::string const& exp) -> bool {
  1543. auto filterErr = [&LogInfoError, &key, &exp](const char* err) -> bool {
  1544. std::ostringstream ferr;
  1545. ferr << "AUTOMOC_DEPEND_FILTERS: " << err << '\n';
  1546. ferr << " Key: " << Quoted(key) << '\n';
  1547. ferr << " Exp: " << Quoted(exp) << '\n';
  1548. return LogInfoError(ferr.str());
  1549. };
  1550. if (key.empty()) {
  1551. return filterErr("Key is empty");
  1552. }
  1553. if (exp.empty()) {
  1554. return filterErr("Regular expression is empty");
  1555. }
  1556. this->MocConst_.DependFilters.emplace_back(key, exp);
  1557. if (!this->MocConst_.DependFilters.back().Exp.is_valid()) {
  1558. return filterErr("Regular expression compiling failed");
  1559. }
  1560. return true;
  1561. };
  1562. // Insert default filter for Q_PLUGIN_METADATA
  1563. if (BaseConst().QtVersionMajor != 4) {
  1564. if (!addFilter("Q_PLUGIN_METADATA",
  1565. "[\n][ \t]*Q_PLUGIN_METADATA[ \t]*\\("
  1566. "[^\\)]*FILE[ \t]*\"([^\"]+)\"")) {
  1567. return false;
  1568. }
  1569. }
  1570. // Insert user defined dependency filters
  1571. std::vector<std::string> flts = InfoGetList("AM_MOC_DEPEND_FILTERS");
  1572. if ((flts.size() % 2) != 0) {
  1573. return LogInfoError(
  1574. "AUTOMOC_DEPEND_FILTERS list size is not a multiple of 2");
  1575. }
  1576. for (auto itC = flts.begin(), itE = flts.end(); itC != itE; itC += 2) {
  1577. if (!addFilter(*itC, *(itC + 1))) {
  1578. return false;
  1579. }
  1580. }
  1581. }
  1582. MocConst_.PredefsCmd = InfoGetList("AM_MOC_PREDEFS_CMD");
  1583. }
  1584. // - Uic
  1585. UicConst_.Executable = InfoGet("AM_QT_UIC_EXECUTABLE");
  1586. if (!UicConst().Executable.empty()) {
  1587. UicConst_.Enabled = true;
  1588. // Load the executable file time
  1589. if (!UicConst_.ExecutableTime.Load(UicConst_.Executable)) {
  1590. std::string error =
  1591. cmStrCat("The uic executable ", Quoted(UicConst_.Executable),
  1592. " does not exist.");
  1593. return LogInfoError(error);
  1594. }
  1595. for (std::string& sfl : InfoGetList("AM_UIC_SKIP")) {
  1596. UicConst_.SkipList.insert(std::move(sfl));
  1597. }
  1598. UicConst_.SearchPaths = InfoGetList("AM_UIC_SEARCH_PATHS");
  1599. UicConst_.TargetOptions = InfoGetConfigList("AM_UIC_TARGET_OPTIONS");
  1600. {
  1601. const char* keyFiles = "AM_UIC_OPTIONS_FILES";
  1602. const char* keyOpts = "AM_UIC_OPTIONS_OPTIONS";
  1603. auto sources = InfoGetList(keyFiles);
  1604. auto options = InfoGetLists(keyOpts);
  1605. if (!MatchSizes(keyFiles, keyOpts, sources.size(), options.size())) {
  1606. return false;
  1607. }
  1608. auto fitEnd = sources.cend();
  1609. auto fit = sources.begin();
  1610. auto oit = options.begin();
  1611. while (fit != fitEnd) {
  1612. UicConst_.Options[*fit] = std::move(*oit);
  1613. ++fit;
  1614. ++oit;
  1615. }
  1616. }
  1617. }
  1618. // - Headers and sources
  1619. {
  1620. auto makeSource =
  1621. [&LogInfoError](std::string const& fileName,
  1622. std::string const& fileFlags) -> SourceFileHandleT {
  1623. if (fileFlags.size() != 2) {
  1624. LogInfoError("Invalid file flags string size");
  1625. return SourceFileHandleT();
  1626. }
  1627. cmFileTime fileTime;
  1628. if (!fileTime.Load(fileName)) {
  1629. LogInfoError("The source file " + cmQtAutoGen::Quoted(fileName) +
  1630. " does not exist.");
  1631. return SourceFileHandleT();
  1632. }
  1633. SourceFileHandleT sfh = std::make_shared<SourceFileT>(fileName);
  1634. sfh->FileTime = fileTime;
  1635. sfh->Moc = (fileFlags[0] == 'M');
  1636. sfh->Uic = (fileFlags[1] == 'U');
  1637. return sfh;
  1638. };
  1639. // Headers
  1640. {
  1641. // Get file lists
  1642. const char *keyFiles = "AM_HEADERS", *keyFlags = "AM_HEADERS_FLAGS";
  1643. std::vector<std::string> files = InfoGetList(keyFiles);
  1644. std::vector<std::string> flags = InfoGetList(keyFlags);
  1645. std::vector<std::string> builds;
  1646. if (!MatchSizes(keyFiles, keyFlags, files.size(), flags.size())) {
  1647. return false;
  1648. }
  1649. if (MocConst().Enabled) {
  1650. const char* keyPaths = "AM_HEADERS_BUILD_PATHS";
  1651. builds = InfoGetList(keyPaths);
  1652. if (!MatchSizes(keyFiles, keyPaths, files.size(), builds.size())) {
  1653. return false;
  1654. }
  1655. }
  1656. // Process file lists
  1657. for (std::size_t ii = 0; ii != files.size(); ++ii) {
  1658. std::string& fileName(files[ii]);
  1659. SourceFileHandleT sfh = makeSource(fileName, flags[ii]);
  1660. if (!sfh) {
  1661. return false;
  1662. }
  1663. if (MocConst().Enabled) {
  1664. sfh->BuildPath = std::move(builds[ii]);
  1665. if (sfh->BuildPath.empty()) {
  1666. Log().ErrorFile(GenT::GEN, this->InfoFile(),
  1667. "Header file build path is empty");
  1668. return false;
  1669. }
  1670. }
  1671. BaseEval().Headers.emplace(std::move(fileName), std::move(sfh));
  1672. }
  1673. }
  1674. // Sources
  1675. {
  1676. const char *keyFiles = "AM_SOURCES", *keyFlags = "AM_SOURCES_FLAGS";
  1677. std::vector<std::string> files = InfoGetList(keyFiles);
  1678. std::vector<std::string> flags = InfoGetList(keyFlags);
  1679. if (!MatchSizes(keyFiles, keyFlags, files.size(), flags.size())) {
  1680. return false;
  1681. }
  1682. // Process file lists
  1683. for (std::size_t ii = 0; ii != files.size(); ++ii) {
  1684. std::string& fileName(files[ii]);
  1685. SourceFileHandleT sfh = makeSource(fileName, flags[ii]);
  1686. if (!sfh) {
  1687. return false;
  1688. }
  1689. BaseEval().Sources.emplace(std::move(fileName), std::move(sfh));
  1690. }
  1691. }
  1692. }
  1693. // Init derived information
  1694. // ------------------------
  1695. // Moc variables
  1696. if (MocConst().Enabled) {
  1697. // Mocs compilation file
  1698. MocConst_.CompFileAbs = AbsoluteBuildPath("mocs_compilation.cpp");
  1699. // Moc predefs file
  1700. if (!MocConst_.PredefsCmd.empty()) {
  1701. MocConst_.PredefsFileRel = "moc_predefs";
  1702. if (BaseConst_.MultiConfig) {
  1703. MocConst_.PredefsFileRel += '_';
  1704. MocConst_.PredefsFileRel += InfoConfig();
  1705. }
  1706. MocConst_.PredefsFileRel += ".h";
  1707. MocConst_.PredefsFileAbs = AbsoluteBuildPath(MocConst().PredefsFileRel);
  1708. }
  1709. // Sort include directories on demand
  1710. if (BaseConst().IncludeProjectDirsBefore) {
  1711. // Move strings to temporary list
  1712. std::list<std::string> includes(MocConst().IncludePaths.begin(),
  1713. MocConst().IncludePaths.end());
  1714. MocConst_.IncludePaths.clear();
  1715. MocConst_.IncludePaths.reserve(includes.size());
  1716. // Append project directories only
  1717. {
  1718. std::array<std::string const*, 2> const movePaths = {
  1719. { &BaseConst().ProjectBinaryDir, &BaseConst().ProjectSourceDir }
  1720. };
  1721. for (std::string const* ppath : movePaths) {
  1722. std::list<std::string>::iterator it = includes.begin();
  1723. while (it != includes.end()) {
  1724. std::string const& path = *it;
  1725. if (cmHasPrefix(path, *ppath)) {
  1726. MocConst_.IncludePaths.push_back(path);
  1727. it = includes.erase(it);
  1728. } else {
  1729. ++it;
  1730. }
  1731. }
  1732. }
  1733. }
  1734. // Append remaining directories
  1735. MocConst_.IncludePaths.insert(MocConst_.IncludePaths.end(),
  1736. includes.begin(), includes.end());
  1737. }
  1738. // Compose moc includes list
  1739. {
  1740. std::set<std::string> frameworkPaths;
  1741. for (std::string const& path : MocConst().IncludePaths) {
  1742. MocConst_.Includes.push_back("-I" + path);
  1743. // Extract framework path
  1744. if (cmHasLiteralSuffix(path, ".framework/Headers")) {
  1745. // Go up twice to get to the framework root
  1746. std::vector<std::string> pathComponents;
  1747. cmSystemTools::SplitPath(path, pathComponents);
  1748. frameworkPaths.emplace(cmSystemTools::JoinPath(
  1749. pathComponents.begin(), pathComponents.end() - 2));
  1750. }
  1751. }
  1752. // Append framework includes
  1753. for (std::string const& path : frameworkPaths) {
  1754. MocConst_.Includes.emplace_back("-F");
  1755. MocConst_.Includes.push_back(path);
  1756. }
  1757. }
  1758. // Setup single list with all options
  1759. {
  1760. // Add includes
  1761. MocConst_.AllOptions.insert(MocConst_.AllOptions.end(),
  1762. MocConst().Includes.begin(),
  1763. MocConst().Includes.end());
  1764. // Add definitions
  1765. for (std::string const& def : MocConst().Definitions) {
  1766. MocConst_.AllOptions.push_back("-D" + def);
  1767. }
  1768. // Add options
  1769. MocConst_.AllOptions.insert(MocConst_.AllOptions.end(),
  1770. MocConst().Options.begin(),
  1771. MocConst().Options.end());
  1772. }
  1773. }
  1774. return true;
  1775. }
  1776. template <class JOBTYPE>
  1777. void cmQtAutoMocUic::CreateParseJobs(SourceFileMapT const& sourceMap)
  1778. {
  1779. cmFileTime const parseCacheTime = BaseEval().ParseCacheTime;
  1780. ParseCacheT& parseCache = BaseEval().ParseCache;
  1781. for (auto& src : sourceMap) {
  1782. // Get or create the file parse data reference
  1783. ParseCacheT::GetOrInsertT cacheEntry = parseCache.GetOrInsert(src.first);
  1784. src.second->ParseData = std::move(cacheEntry.first);
  1785. // Create a parse job if the cache file was missing or is older
  1786. if (cacheEntry.second || src.second->FileTime.Newer(parseCacheTime)) {
  1787. BaseEval().ParseCacheChanged = true;
  1788. WorkerPool().EmplaceJob<JOBTYPE>(src.second);
  1789. }
  1790. }
  1791. }
  1792. void cmQtAutoMocUic::InitJobs()
  1793. {
  1794. // Add moc_predefs.h job
  1795. if (MocConst().Enabled && !MocConst().PredefsCmd.empty()) {
  1796. WorkerPool().EmplaceJob<JobMocPredefsT>();
  1797. }
  1798. // Add header parse jobs
  1799. CreateParseJobs<JobParseHeaderT>(BaseEval().Headers);
  1800. // Add source parse jobs
  1801. CreateParseJobs<JobParseSourceT>(BaseEval().Sources);
  1802. // Add evaluate job
  1803. WorkerPool().EmplaceJob<JobEvaluateT>();
  1804. }
  1805. bool cmQtAutoMocUic::Process()
  1806. {
  1807. SettingsFileRead();
  1808. ParseCacheRead();
  1809. if (!CreateDirectories()) {
  1810. return false;
  1811. }
  1812. InitJobs();
  1813. if (!WorkerPool_.Process(this)) {
  1814. return false;
  1815. }
  1816. if (JobError_) {
  1817. return false;
  1818. }
  1819. if (!ParseCacheWrite()) {
  1820. return false;
  1821. }
  1822. if (!SettingsFileWrite()) {
  1823. return false;
  1824. }
  1825. return true;
  1826. }
  1827. void cmQtAutoMocUic::SettingsFileRead()
  1828. {
  1829. // Compose current settings strings
  1830. {
  1831. cmCryptoHash cryptoHash(cmCryptoHash::AlgoSHA256);
  1832. std::string const sep(";");
  1833. auto cha = [&cryptoHash, &sep](std::string const& value) {
  1834. cryptoHash.Append(value);
  1835. cryptoHash.Append(sep);
  1836. };
  1837. if (MocConst_.Enabled) {
  1838. cryptoHash.Initialize();
  1839. cha(MocConst().Executable);
  1840. for (auto const& value : MocConst().AllOptions) {
  1841. cha(value);
  1842. }
  1843. cha(BaseConst().IncludeProjectDirsBefore ? "TRUE" : "FALSE");
  1844. for (auto const& value : MocConst().PredefsCmd) {
  1845. cha(value);
  1846. }
  1847. for (auto const& filter : MocConst().DependFilters) {
  1848. cha(filter.Key);
  1849. }
  1850. for (auto const& filter : MocConst().MacroFilters) {
  1851. cha(filter.Key);
  1852. }
  1853. SettingsStringMoc_ = cryptoHash.FinalizeHex();
  1854. }
  1855. if (UicConst().Enabled) {
  1856. cryptoHash.Initialize();
  1857. cha(UicConst().Executable);
  1858. for (auto const& value : UicConst().TargetOptions) {
  1859. cha(value);
  1860. }
  1861. for (const auto& item : UicConst().Options) {
  1862. cha(item.first);
  1863. for (auto const& svalue : item.second) {
  1864. cha(svalue);
  1865. }
  1866. }
  1867. SettingsStringUic_ = cryptoHash.FinalizeHex();
  1868. }
  1869. }
  1870. // Read old settings and compare
  1871. {
  1872. std::string content;
  1873. if (cmQtAutoGenerator::FileRead(content, SettingsFile_)) {
  1874. if (MocConst().Enabled) {
  1875. if (SettingsStringMoc_ != SettingsFind(content, "moc")) {
  1876. MocConst_.SettingsChanged = true;
  1877. }
  1878. }
  1879. if (UicConst().Enabled) {
  1880. if (SettingsStringUic_ != SettingsFind(content, "uic")) {
  1881. UicConst_.SettingsChanged = true;
  1882. }
  1883. }
  1884. // In case any setting changed remove the old settings file.
  1885. // This triggers a full rebuild on the next run if the current
  1886. // build is aborted before writing the current settings in the end.
  1887. if (MocConst().SettingsChanged || UicConst().SettingsChanged) {
  1888. cmSystemTools::RemoveFile(SettingsFile_);
  1889. }
  1890. } else {
  1891. // Settings file read failed
  1892. if (MocConst().Enabled) {
  1893. MocConst_.SettingsChanged = true;
  1894. }
  1895. if (UicConst().Enabled) {
  1896. UicConst_.SettingsChanged = true;
  1897. }
  1898. }
  1899. }
  1900. }
  1901. bool cmQtAutoMocUic::SettingsFileWrite()
  1902. {
  1903. // Only write if any setting changed
  1904. if (MocConst().SettingsChanged || UicConst().SettingsChanged) {
  1905. if (Log().Verbose()) {
  1906. Log().Info(GenT::GEN, "Writing settings file " + Quoted(SettingsFile_));
  1907. }
  1908. // Compose settings file content
  1909. std::string content;
  1910. {
  1911. auto SettingAppend = [&content](const char* key,
  1912. std::string const& value) {
  1913. if (!value.empty()) {
  1914. content += key;
  1915. content += ':';
  1916. content += value;
  1917. content += '\n';
  1918. }
  1919. };
  1920. SettingAppend("moc", SettingsStringMoc_);
  1921. SettingAppend("uic", SettingsStringUic_);
  1922. }
  1923. // Write settings file
  1924. std::string error;
  1925. if (!cmQtAutoGenerator::FileWrite(SettingsFile_, content, &error)) {
  1926. Log().ErrorFile(GenT::GEN, SettingsFile_,
  1927. "Settings file writing failed. " + error);
  1928. // Remove old settings file to trigger a full rebuild on the next run
  1929. cmSystemTools::RemoveFile(SettingsFile_);
  1930. return false;
  1931. }
  1932. }
  1933. return true;
  1934. }
  1935. void cmQtAutoMocUic::ParseCacheRead()
  1936. {
  1937. const char* reason = nullptr;
  1938. // Don't read the cache if it is invalid
  1939. if (!BaseEval().ParseCacheTime.Load(BaseConst().ParseCacheFile)) {
  1940. reason = "Refreshing parse cache because it doesn't exist.";
  1941. } else if (MocConst().SettingsChanged || UicConst().SettingsChanged) {
  1942. reason = "Refreshing parse cache because the settings changed.";
  1943. } else if (BaseEval().ParseCacheTime.Older(
  1944. BaseConst().CMakeExecutableTime)) {
  1945. reason =
  1946. "Refreshing parse cache because it is older than the CMake executable.";
  1947. }
  1948. if (reason != nullptr) {
  1949. // Don't read but refresh the complete parse cache
  1950. if (Log().Verbose()) {
  1951. Log().Info(GenT::GEN, reason);
  1952. }
  1953. BaseEval().ParseCacheChanged = true;
  1954. } else {
  1955. // Read parse cache
  1956. BaseEval().ParseCache.ReadFromFile(BaseConst().ParseCacheFile);
  1957. }
  1958. }
  1959. bool cmQtAutoMocUic::ParseCacheWrite()
  1960. {
  1961. if (BaseEval().ParseCacheChanged) {
  1962. if (Log().Verbose()) {
  1963. Log().Info(GenT::GEN,
  1964. "Writing parse cache file " +
  1965. Quoted(BaseConst().ParseCacheFile));
  1966. }
  1967. if (!BaseEval().ParseCache.WriteToFile(BaseConst().ParseCacheFile)) {
  1968. Log().ErrorFile(GenT::GEN, BaseConst().ParseCacheFile,
  1969. "Parse cache file writing failed.");
  1970. return false;
  1971. }
  1972. }
  1973. return true;
  1974. }
  1975. bool cmQtAutoMocUic::CreateDirectories()
  1976. {
  1977. // Create AUTOGEN include directory
  1978. if (!cmSystemTools::MakeDirectory(BaseConst().AutogenIncludeDir)) {
  1979. Log().ErrorFile(GenT::GEN, BaseConst().AutogenIncludeDir,
  1980. "Could not create directory.");
  1981. return false;
  1982. }
  1983. return true;
  1984. }
  1985. void cmQtAutoMocUic::Abort(bool error)
  1986. {
  1987. if (error) {
  1988. JobError_.store(true);
  1989. }
  1990. WorkerPool_.Abort();
  1991. }
  1992. std::string cmQtAutoMocUic::AbsoluteBuildPath(
  1993. std::string const& relativePath) const
  1994. {
  1995. std::string res(BaseConst().AutogenBuildDir);
  1996. res += '/';
  1997. res += relativePath;
  1998. return res;
  1999. }
  2000. std::string cmQtAutoMocUic::AbsoluteIncludePath(
  2001. std::string const& relativePath) const
  2002. {
  2003. std::string res(BaseConst().AutogenIncludeDir);
  2004. res += '/';
  2005. res += relativePath;
  2006. return res;
  2007. }