cmQtAutoGeneratorMocUic.cxx 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024
  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 "cmQtAutoGeneratorMocUic.h"
  4. #include <algorithm>
  5. #include <array>
  6. #include <cstddef>
  7. #include <list>
  8. #include <memory>
  9. #include <set>
  10. #include <sstream>
  11. #include <utility>
  12. #include "cmAlgorithms.h"
  13. #include "cmCryptoHash.h"
  14. #include "cmMakefile.h"
  15. #include "cmQtAutoGen.h"
  16. #include "cmSystemTools.h"
  17. #include "cmake.h"
  18. #if defined(__APPLE__)
  19. # include <unistd.h>
  20. #endif
  21. // -- Class methods
  22. std::string cmQtAutoGeneratorMocUic::BaseSettingsT::AbsoluteBuildPath(
  23. std::string const& relativePath) const
  24. {
  25. return FileSys->CollapseFullPath(relativePath, AutogenBuildDir);
  26. }
  27. /**
  28. * @brief Tries to find the header file to the given file base path by
  29. * appending different header extensions
  30. * @return True on success
  31. */
  32. bool cmQtAutoGeneratorMocUic::BaseSettingsT::FindHeader(
  33. std::string& header, std::string const& testBasePath) const
  34. {
  35. for (std::string const& ext : HeaderExtensions) {
  36. std::string testFilePath(testBasePath);
  37. testFilePath.push_back('.');
  38. testFilePath += ext;
  39. if (FileSys->FileExists(testFilePath)) {
  40. header = testFilePath;
  41. return true;
  42. }
  43. }
  44. return false;
  45. }
  46. bool cmQtAutoGeneratorMocUic::MocSettingsT::skipped(
  47. std::string const& fileName) const
  48. {
  49. return (!Enabled || (SkipList.find(fileName) != SkipList.end()));
  50. }
  51. /**
  52. * @brief Returns the first relevant Qt macro name found in the given C++ code
  53. * @return The name of the Qt macro or an empty string
  54. */
  55. std::string cmQtAutoGeneratorMocUic::MocSettingsT::FindMacro(
  56. std::string const& content) const
  57. {
  58. for (KeyExpT const& filter : MacroFilters) {
  59. // Run a simple find string operation before the expensive
  60. // regular expression check
  61. if (content.find(filter.Key) != std::string::npos) {
  62. cmsys::RegularExpressionMatch match;
  63. if (filter.Exp.find(content.c_str(), match)) {
  64. // Return macro name on demand
  65. return filter.Key;
  66. }
  67. }
  68. }
  69. return std::string();
  70. }
  71. std::string cmQtAutoGeneratorMocUic::MocSettingsT::MacrosString() const
  72. {
  73. std::string res;
  74. const auto itB = MacroFilters.cbegin();
  75. const auto itE = MacroFilters.cend();
  76. const auto itL = itE - 1;
  77. auto itC = itB;
  78. for (; itC != itE; ++itC) {
  79. // Separator
  80. if (itC != itB) {
  81. if (itC != itL) {
  82. res += ", ";
  83. } else {
  84. res += " or ";
  85. }
  86. }
  87. // Key
  88. res += itC->Key;
  89. }
  90. return res;
  91. }
  92. std::string cmQtAutoGeneratorMocUic::MocSettingsT::FindIncludedFile(
  93. std::string const& sourcePath, std::string const& includeString) const
  94. {
  95. // Search in vicinity of the source
  96. {
  97. std::string testPath = sourcePath;
  98. testPath += includeString;
  99. if (FileSys->FileExists(testPath)) {
  100. return FileSys->GetRealPath(testPath);
  101. }
  102. }
  103. // Search in include directories
  104. for (std::string const& path : IncludePaths) {
  105. std::string fullPath = path;
  106. fullPath.push_back('/');
  107. fullPath += includeString;
  108. if (FileSys->FileExists(fullPath)) {
  109. return FileSys->GetRealPath(fullPath);
  110. }
  111. }
  112. // Return empty string
  113. return std::string();
  114. }
  115. void cmQtAutoGeneratorMocUic::MocSettingsT::FindDependencies(
  116. std::string const& content, std::set<std::string>& depends) const
  117. {
  118. if (!DependFilters.empty() && !content.empty()) {
  119. for (KeyExpT const& filter : DependFilters) {
  120. // Run a simple find string check
  121. if (content.find(filter.Key) != std::string::npos) {
  122. // Run the expensive regular expression check loop
  123. const char* contentChars = content.c_str();
  124. cmsys::RegularExpressionMatch match;
  125. while (filter.Exp.find(contentChars, match)) {
  126. {
  127. std::string dep = match.match(1);
  128. if (!dep.empty()) {
  129. depends.emplace(std::move(dep));
  130. }
  131. }
  132. contentChars += match.end();
  133. }
  134. }
  135. }
  136. }
  137. }
  138. bool cmQtAutoGeneratorMocUic::UicSettingsT::skipped(
  139. std::string const& fileName) const
  140. {
  141. return (!Enabled || (SkipList.find(fileName) != SkipList.end()));
  142. }
  143. void cmQtAutoGeneratorMocUic::JobParseT::Process(WorkerT& wrk)
  144. {
  145. if (AutoMoc && Header) {
  146. // Don't parse header for moc if the file is included by a source already
  147. if (wrk.Gen().ParallelMocIncluded(FileName)) {
  148. AutoMoc = false;
  149. }
  150. }
  151. if (AutoMoc || AutoUic) {
  152. std::string error;
  153. MetaT meta;
  154. if (wrk.FileSys().FileRead(meta.Content, FileName, &error)) {
  155. if (!meta.Content.empty()) {
  156. meta.FileDir = wrk.FileSys().SubDirPrefix(FileName);
  157. meta.FileBase =
  158. wrk.FileSys().GetFilenameWithoutLastExtension(FileName);
  159. bool success = true;
  160. if (AutoMoc) {
  161. if (Header) {
  162. success = ParseMocHeader(wrk, meta);
  163. } else {
  164. success = ParseMocSource(wrk, meta);
  165. }
  166. }
  167. if (AutoUic && success) {
  168. ParseUic(wrk, meta);
  169. }
  170. } else {
  171. wrk.LogFileWarning(GenT::GEN, FileName, "The source file is empty");
  172. }
  173. } else {
  174. wrk.LogFileError(GenT::GEN, FileName,
  175. "Could not read the file: " + error);
  176. }
  177. }
  178. }
  179. bool cmQtAutoGeneratorMocUic::JobParseT::ParseMocSource(WorkerT& wrk,
  180. MetaT const& meta)
  181. {
  182. struct JobPre
  183. {
  184. bool self; // source file is self
  185. bool underscore; // "moc_" style include
  186. std::string SourceFile;
  187. std::string IncludeString;
  188. };
  189. struct MocInclude
  190. {
  191. std::string Inc; // full include string
  192. std::string Dir; // include string directory
  193. std::string Base; // include string file base
  194. };
  195. // Check if this source file contains a relevant macro
  196. std::string const ownMacro = wrk.Moc().FindMacro(meta.Content);
  197. // Extract moc includes from file
  198. std::deque<MocInclude> mocIncsUsc;
  199. std::deque<MocInclude> mocIncsDot;
  200. {
  201. if (meta.Content.find("moc") != std::string::npos) {
  202. const char* contentChars = meta.Content.c_str();
  203. cmsys::RegularExpressionMatch match;
  204. while (wrk.Moc().RegExpInclude.find(contentChars, match)) {
  205. std::string incString = match.match(2);
  206. std::string incDir(wrk.FileSys().SubDirPrefix(incString));
  207. std::string incBase =
  208. wrk.FileSys().GetFilenameWithoutLastExtension(incString);
  209. if (cmHasLiteralPrefix(incBase, "moc_")) {
  210. // moc_<BASE>.cxx
  211. // Remove the moc_ part from the base name
  212. mocIncsUsc.emplace_back(MocInclude{
  213. std::move(incString), std::move(incDir), incBase.substr(4) });
  214. } else {
  215. // <BASE>.moc
  216. mocIncsDot.emplace_back(MocInclude{
  217. std::move(incString), std::move(incDir), std::move(incBase) });
  218. }
  219. // Forward content pointer
  220. contentChars += match.end();
  221. }
  222. }
  223. }
  224. // Check if there is anything to do
  225. if (ownMacro.empty() && mocIncsUsc.empty() && mocIncsDot.empty()) {
  226. return true;
  227. }
  228. bool ownDotMocIncluded = false;
  229. bool ownMocUscIncluded = false;
  230. std::deque<JobPre> jobs;
  231. // Process moc_<BASE>.cxx includes
  232. for (const MocInclude& mocInc : mocIncsUsc) {
  233. std::string const header =
  234. MocFindIncludedHeader(wrk, meta.FileDir, mocInc.Dir + mocInc.Base);
  235. if (!header.empty()) {
  236. // Check if header is skipped
  237. if (wrk.Moc().skipped(header)) {
  238. continue;
  239. }
  240. // Register moc job
  241. const bool ownMoc = (mocInc.Base == meta.FileBase);
  242. jobs.emplace_back(JobPre{ ownMoc, true, header, mocInc.Inc });
  243. // Store meta information for relaxed mode
  244. if (ownMoc) {
  245. ownMocUscIncluded = true;
  246. }
  247. } else {
  248. {
  249. std::string emsg = "The file includes the moc file ";
  250. emsg += Quoted(mocInc.Inc);
  251. emsg += ", but the header ";
  252. emsg += Quoted(MocStringHeaders(wrk, mocInc.Base));
  253. emsg += " could not be found.";
  254. wrk.LogFileError(GenT::MOC, FileName, emsg);
  255. }
  256. return false;
  257. }
  258. }
  259. // Process <BASE>.moc includes
  260. for (const MocInclude& mocInc : mocIncsDot) {
  261. const bool ownMoc = (mocInc.Base == meta.FileBase);
  262. if (wrk.Moc().RelaxedMode) {
  263. // Relaxed mode
  264. if (!ownMacro.empty() && ownMoc) {
  265. // Add self
  266. jobs.emplace_back(JobPre{ ownMoc, false, FileName, mocInc.Inc });
  267. ownDotMocIncluded = true;
  268. } else {
  269. // In relaxed mode try to find a header instead but issue a warning.
  270. // This is for KDE4 compatibility
  271. std::string const header =
  272. MocFindIncludedHeader(wrk, meta.FileDir, mocInc.Dir + mocInc.Base);
  273. if (!header.empty()) {
  274. // Check if header is skipped
  275. if (wrk.Moc().skipped(header)) {
  276. continue;
  277. }
  278. // Register moc job
  279. jobs.emplace_back(JobPre{ ownMoc, false, header, mocInc.Inc });
  280. if (ownMacro.empty()) {
  281. if (ownMoc) {
  282. std::string emsg = "The file includes the moc file ";
  283. emsg += Quoted(mocInc.Inc);
  284. emsg += ", but does not contain a ";
  285. emsg += wrk.Moc().MacrosString();
  286. emsg += " macro.\nRunning moc on\n ";
  287. emsg += Quoted(header);
  288. emsg += "!\nBetter include ";
  289. emsg += Quoted("moc_" + mocInc.Base + ".cpp");
  290. emsg += " for a compatibility with strict mode.\n"
  291. "(CMAKE_AUTOMOC_RELAXED_MODE warning)\n";
  292. wrk.LogFileWarning(GenT::MOC, FileName, emsg);
  293. } else {
  294. std::string emsg = "The file includes the moc file ";
  295. emsg += Quoted(mocInc.Inc);
  296. emsg += " instead of ";
  297. emsg += Quoted("moc_" + mocInc.Base + ".cpp");
  298. emsg += ".\nRunning moc on\n ";
  299. emsg += Quoted(header);
  300. emsg += "!\nBetter include ";
  301. emsg += Quoted("moc_" + mocInc.Base + ".cpp");
  302. emsg += " for compatibility with strict mode.\n"
  303. "(CMAKE_AUTOMOC_RELAXED_MODE warning)\n";
  304. wrk.LogFileWarning(GenT::MOC, FileName, emsg);
  305. }
  306. }
  307. } else {
  308. {
  309. std::string emsg = "The file includes the moc file ";
  310. emsg += Quoted(mocInc.Inc);
  311. emsg += ", which seems to be the moc file from a different "
  312. "source file.\nCMAKE_AUTOMOC_RELAXED_MODE: Also a "
  313. "matching header ";
  314. emsg += Quoted(MocStringHeaders(wrk, mocInc.Base));
  315. emsg += " could not be found.";
  316. wrk.LogFileError(GenT::MOC, FileName, emsg);
  317. }
  318. return false;
  319. }
  320. }
  321. } else {
  322. // Strict mode
  323. if (ownMoc) {
  324. // Include self
  325. jobs.emplace_back(JobPre{ ownMoc, false, FileName, mocInc.Inc });
  326. ownDotMocIncluded = true;
  327. // Accept but issue a warning if moc isn't required
  328. if (ownMacro.empty()) {
  329. std::string emsg = "The file includes the moc file ";
  330. emsg += Quoted(mocInc.Inc);
  331. emsg += ", but does not contain a ";
  332. emsg += wrk.Moc().MacrosString();
  333. emsg += " macro.";
  334. wrk.LogFileWarning(GenT::MOC, FileName, emsg);
  335. }
  336. } else {
  337. // Don't allow <BASE>.moc include other than self in strict mode
  338. {
  339. std::string emsg = "The file includes the moc file ";
  340. emsg += Quoted(mocInc.Inc);
  341. emsg += ", which seems to be the moc file from a different "
  342. "source file.\nThis is not supported. Include ";
  343. emsg += Quoted(meta.FileBase + ".moc");
  344. emsg += " to run moc on this source file.";
  345. wrk.LogFileError(GenT::MOC, FileName, emsg);
  346. }
  347. return false;
  348. }
  349. }
  350. }
  351. if (!ownMacro.empty() && !ownDotMocIncluded) {
  352. // In this case, check whether the scanned file itself contains a
  353. // Q_OBJECT.
  354. // If this is the case, the moc_foo.cpp should probably be generated from
  355. // foo.cpp instead of foo.h, because otherwise it won't build.
  356. // But warn, since this is not how it is supposed to be used.
  357. // This is for KDE4 compatibility.
  358. if (wrk.Moc().RelaxedMode && ownMocUscIncluded) {
  359. JobPre uscJobPre;
  360. // Remove underscore job request
  361. {
  362. auto itC = jobs.begin();
  363. auto itE = jobs.end();
  364. for (; itC != itE; ++itC) {
  365. JobPre& job(*itC);
  366. if (job.self && job.underscore) {
  367. uscJobPre = std::move(job);
  368. jobs.erase(itC);
  369. break;
  370. }
  371. }
  372. }
  373. // Issue a warning
  374. {
  375. std::string emsg = "The file contains a ";
  376. emsg += ownMacro;
  377. emsg += " macro, but does not include ";
  378. emsg += Quoted(meta.FileBase + ".moc");
  379. emsg += ". Instead it includes ";
  380. emsg += Quoted(uscJobPre.IncludeString);
  381. emsg += ".\nRunning moc on\n ";
  382. emsg += Quoted(FileName);
  383. emsg += "!\nBetter include ";
  384. emsg += Quoted(meta.FileBase + ".moc");
  385. emsg += " for compatibility with strict mode.\n"
  386. "(CMAKE_AUTOMOC_RELAXED_MODE warning)";
  387. wrk.LogFileWarning(GenT::MOC, FileName, emsg);
  388. }
  389. // Add own source job
  390. jobs.emplace_back(
  391. JobPre{ true, false, FileName, uscJobPre.IncludeString });
  392. } else {
  393. // Otherwise always error out since it will not compile.
  394. {
  395. std::string emsg = "The file contains a ";
  396. emsg += ownMacro;
  397. emsg += " macro, but does not include ";
  398. emsg += Quoted(meta.FileBase + ".moc");
  399. emsg += "!\nConsider to\n - add #include \"";
  400. emsg += meta.FileBase;
  401. emsg += ".moc\"\n - enable SKIP_AUTOMOC for this file";
  402. wrk.LogFileError(GenT::MOC, FileName, emsg);
  403. }
  404. return false;
  405. }
  406. }
  407. // Convert pre jobs to actual jobs
  408. for (JobPre& jobPre : jobs) {
  409. JobHandleT jobHandle = cm::make_unique<JobMocT>(
  410. std::move(jobPre.SourceFile), FileName, std::move(jobPre.IncludeString));
  411. if (jobPre.self) {
  412. // Read dependencies from this source
  413. static_cast<JobMocT&>(*jobHandle).FindDependencies(wrk, meta.Content);
  414. }
  415. if (!wrk.Gen().ParallelJobPushMoc(jobHandle)) {
  416. return false;
  417. }
  418. }
  419. return true;
  420. }
  421. bool cmQtAutoGeneratorMocUic::JobParseT::ParseMocHeader(WorkerT& wrk,
  422. MetaT const& meta)
  423. {
  424. bool success = true;
  425. std::string const macroName = wrk.Moc().FindMacro(meta.Content);
  426. if (!macroName.empty()) {
  427. JobHandleT jobHandle = cm::make_unique<JobMocT>(
  428. std::string(FileName), std::string(), std::string());
  429. // Read dependencies from this source
  430. static_cast<JobMocT&>(*jobHandle).FindDependencies(wrk, meta.Content);
  431. success = wrk.Gen().ParallelJobPushMoc(jobHandle);
  432. }
  433. return success;
  434. }
  435. std::string cmQtAutoGeneratorMocUic::JobParseT::MocStringHeaders(
  436. WorkerT& wrk, std::string const& fileBase) const
  437. {
  438. std::string res = fileBase;
  439. res += ".{";
  440. res += cmJoin(wrk.Base().HeaderExtensions, ",");
  441. res += "}";
  442. return res;
  443. }
  444. std::string cmQtAutoGeneratorMocUic::JobParseT::MocFindIncludedHeader(
  445. WorkerT& wrk, std::string const& includerDir, std::string const& includeBase)
  446. {
  447. std::string header;
  448. // Search in vicinity of the source
  449. if (!wrk.Base().FindHeader(header, includerDir + includeBase)) {
  450. // Search in include directories
  451. for (std::string const& path : wrk.Moc().IncludePaths) {
  452. std::string fullPath = path;
  453. fullPath.push_back('/');
  454. fullPath += includeBase;
  455. if (wrk.Base().FindHeader(header, fullPath)) {
  456. break;
  457. }
  458. }
  459. }
  460. // Sanitize
  461. if (!header.empty()) {
  462. header = wrk.FileSys().GetRealPath(header);
  463. }
  464. return header;
  465. }
  466. bool cmQtAutoGeneratorMocUic::JobParseT::ParseUic(WorkerT& wrk,
  467. MetaT const& meta)
  468. {
  469. bool success = true;
  470. if (meta.Content.find("ui_") != std::string::npos) {
  471. const char* contentChars = meta.Content.c_str();
  472. cmsys::RegularExpressionMatch match;
  473. while (wrk.Uic().RegExpInclude.find(contentChars, match)) {
  474. if (!ParseUicInclude(wrk, meta, match.match(2))) {
  475. success = false;
  476. break;
  477. }
  478. contentChars += match.end();
  479. }
  480. }
  481. return success;
  482. }
  483. bool cmQtAutoGeneratorMocUic::JobParseT::ParseUicInclude(
  484. WorkerT& wrk, MetaT const& meta, std::string&& includeString)
  485. {
  486. bool success = false;
  487. std::string uiInputFile = UicFindIncludedFile(wrk, meta, includeString);
  488. if (!uiInputFile.empty()) {
  489. if (!wrk.Uic().skipped(uiInputFile)) {
  490. JobHandleT jobHandle = cm::make_unique<JobUicT>(
  491. std::move(uiInputFile), FileName, std::move(includeString));
  492. success = wrk.Gen().ParallelJobPushUic(jobHandle);
  493. } else {
  494. // A skipped file is successful
  495. success = true;
  496. }
  497. }
  498. return success;
  499. }
  500. std::string cmQtAutoGeneratorMocUic::JobParseT::UicFindIncludedFile(
  501. WorkerT& wrk, MetaT const& meta, std::string const& includeString)
  502. {
  503. std::string res;
  504. std::string searchFile =
  505. wrk.FileSys().GetFilenameWithoutLastExtension(includeString).substr(3);
  506. searchFile += ".ui";
  507. // Collect search paths list
  508. std::deque<std::string> testFiles;
  509. {
  510. std::string const searchPath = wrk.FileSys().SubDirPrefix(includeString);
  511. std::string searchFileFull;
  512. if (!searchPath.empty()) {
  513. searchFileFull = searchPath;
  514. searchFileFull += searchFile;
  515. }
  516. // Vicinity of the source
  517. {
  518. std::string const sourcePath = meta.FileDir;
  519. testFiles.push_back(sourcePath + searchFile);
  520. if (!searchPath.empty()) {
  521. testFiles.push_back(sourcePath + searchFileFull);
  522. }
  523. }
  524. // AUTOUIC search paths
  525. if (!wrk.Uic().SearchPaths.empty()) {
  526. for (std::string const& sPath : wrk.Uic().SearchPaths) {
  527. testFiles.push_back((sPath + "/").append(searchFile));
  528. }
  529. if (!searchPath.empty()) {
  530. for (std::string const& sPath : wrk.Uic().SearchPaths) {
  531. testFiles.push_back((sPath + "/").append(searchFileFull));
  532. }
  533. }
  534. }
  535. }
  536. // Search for the .ui file!
  537. for (std::string const& testFile : testFiles) {
  538. if (wrk.FileSys().FileExists(testFile)) {
  539. res = wrk.FileSys().GetRealPath(testFile);
  540. break;
  541. }
  542. }
  543. // Log error
  544. if (res.empty()) {
  545. std::string emsg = "Could not find ";
  546. emsg += Quoted(searchFile);
  547. emsg += " in\n";
  548. for (std::string const& testFile : testFiles) {
  549. emsg += " ";
  550. emsg += Quoted(testFile);
  551. emsg += "\n";
  552. }
  553. wrk.LogFileError(GenT::UIC, FileName, emsg);
  554. }
  555. return res;
  556. }
  557. void cmQtAutoGeneratorMocUic::JobMocPredefsT::Process(WorkerT& wrk)
  558. {
  559. // (Re)generate moc_predefs.h on demand
  560. bool generate(false);
  561. bool fileExists(wrk.FileSys().FileExists(wrk.Moc().PredefsFileAbs));
  562. if (!fileExists) {
  563. if (wrk.Log().Verbose()) {
  564. std::string reason = "Generating ";
  565. reason += Quoted(wrk.Moc().PredefsFileRel);
  566. reason += " because it doesn't exist";
  567. wrk.LogInfo(GenT::MOC, reason);
  568. }
  569. generate = true;
  570. } else if (wrk.Moc().SettingsChanged) {
  571. if (wrk.Log().Verbose()) {
  572. std::string reason = "Generating ";
  573. reason += Quoted(wrk.Moc().PredefsFileRel);
  574. reason += " because the settings changed.";
  575. wrk.LogInfo(GenT::MOC, reason);
  576. }
  577. generate = true;
  578. }
  579. if (generate) {
  580. ProcessResultT result;
  581. {
  582. // Compose command
  583. std::vector<std::string> cmd = wrk.Moc().PredefsCmd;
  584. // Add includes
  585. cmd.insert(cmd.end(), wrk.Moc().Includes.begin(),
  586. wrk.Moc().Includes.end());
  587. // Add definitions
  588. for (std::string const& def : wrk.Moc().Definitions) {
  589. cmd.push_back("-D" + def);
  590. }
  591. // Execute command
  592. if (!wrk.RunProcess(GenT::MOC, result, cmd)) {
  593. std::string emsg = "The content generation command for ";
  594. emsg += Quoted(wrk.Moc().PredefsFileRel);
  595. emsg += " failed.\n";
  596. emsg += result.ErrorMessage;
  597. wrk.LogCommandError(GenT::MOC, emsg, cmd, result.StdOut);
  598. }
  599. }
  600. // (Re)write predefs file only on demand
  601. if (!result.error()) {
  602. if (!fileExists ||
  603. wrk.FileSys().FileDiffers(wrk.Moc().PredefsFileAbs, result.StdOut)) {
  604. if (wrk.FileSys().FileWrite(GenT::MOC, wrk.Moc().PredefsFileAbs,
  605. result.StdOut)) {
  606. // Success
  607. } else {
  608. std::string emsg = "Writing ";
  609. emsg += Quoted(wrk.Moc().PredefsFileRel);
  610. emsg += " failed.";
  611. wrk.LogFileError(GenT::MOC, wrk.Moc().PredefsFileAbs, emsg);
  612. }
  613. } else {
  614. // Touch to update the time stamp
  615. if (wrk.Log().Verbose()) {
  616. std::string msg = "Touching ";
  617. msg += Quoted(wrk.Moc().PredefsFileRel);
  618. msg += ".";
  619. wrk.LogInfo(GenT::MOC, msg);
  620. }
  621. wrk.FileSys().Touch(wrk.Moc().PredefsFileAbs);
  622. }
  623. }
  624. }
  625. }
  626. void cmQtAutoGeneratorMocUic::JobMocT::FindDependencies(
  627. WorkerT& wrk, std::string const& content)
  628. {
  629. wrk.Moc().FindDependencies(content, Depends);
  630. DependsValid = true;
  631. }
  632. void cmQtAutoGeneratorMocUic::JobMocT::Process(WorkerT& wrk)
  633. {
  634. // Compute build file name
  635. if (!IncludeString.empty()) {
  636. BuildFile = wrk.Base().AutogenIncludeDir;
  637. BuildFile += '/';
  638. BuildFile += IncludeString;
  639. } else {
  640. // Relative build path
  641. std::string relPath = wrk.FileSys().GetFilePathChecksum(SourceFile);
  642. relPath += "/moc_";
  643. relPath += wrk.FileSys().GetFilenameWithoutLastExtension(SourceFile);
  644. // Register relative file path with duplication check
  645. relPath = wrk.Gen().ParallelMocAutoRegister(relPath);
  646. // Absolute build path
  647. if (wrk.Base().MultiConfig) {
  648. BuildFile = wrk.Base().AutogenIncludeDir;
  649. BuildFile += '/';
  650. BuildFile += relPath;
  651. } else {
  652. BuildFile = wrk.Base().AbsoluteBuildPath(relPath);
  653. }
  654. }
  655. if (UpdateRequired(wrk)) {
  656. GenerateMoc(wrk);
  657. }
  658. }
  659. bool cmQtAutoGeneratorMocUic::JobMocT::UpdateRequired(WorkerT& wrk)
  660. {
  661. bool const verbose = wrk.Gen().Log().Verbose();
  662. // Test if the build file exists
  663. if (!wrk.FileSys().FileExists(BuildFile)) {
  664. if (verbose) {
  665. std::string reason = "Generating ";
  666. reason += Quoted(BuildFile);
  667. reason += " from its source file ";
  668. reason += Quoted(SourceFile);
  669. reason += " because it doesn't exist";
  670. wrk.LogInfo(GenT::MOC, reason);
  671. }
  672. return true;
  673. }
  674. // Test if any setting changed
  675. if (wrk.Moc().SettingsChanged) {
  676. if (verbose) {
  677. std::string reason = "Generating ";
  678. reason += Quoted(BuildFile);
  679. reason += " from ";
  680. reason += Quoted(SourceFile);
  681. reason += " because the MOC settings changed";
  682. wrk.LogInfo(GenT::MOC, reason);
  683. }
  684. return true;
  685. }
  686. // Test if the moc_predefs file is newer
  687. if (!wrk.Moc().PredefsFileAbs.empty()) {
  688. bool isOlder = false;
  689. {
  690. std::string error;
  691. isOlder = wrk.FileSys().FileIsOlderThan(
  692. BuildFile, wrk.Moc().PredefsFileAbs, &error);
  693. if (!isOlder && !error.empty()) {
  694. wrk.LogError(GenT::MOC, error);
  695. return false;
  696. }
  697. }
  698. if (isOlder) {
  699. if (verbose) {
  700. std::string reason = "Generating ";
  701. reason += Quoted(BuildFile);
  702. reason += " because it's older than: ";
  703. reason += Quoted(wrk.Moc().PredefsFileAbs);
  704. wrk.LogInfo(GenT::MOC, reason);
  705. }
  706. return true;
  707. }
  708. }
  709. // Test if the source file is newer
  710. {
  711. bool isOlder = false;
  712. {
  713. std::string error;
  714. isOlder = wrk.FileSys().FileIsOlderThan(BuildFile, SourceFile, &error);
  715. if (!isOlder && !error.empty()) {
  716. wrk.LogError(GenT::MOC, error);
  717. return false;
  718. }
  719. }
  720. if (isOlder) {
  721. if (verbose) {
  722. std::string reason = "Generating ";
  723. reason += Quoted(BuildFile);
  724. reason += " because it's older than its source file ";
  725. reason += Quoted(SourceFile);
  726. wrk.LogInfo(GenT::MOC, reason);
  727. }
  728. return true;
  729. }
  730. }
  731. // Test if a dependency file is newer
  732. {
  733. // Read dependencies on demand
  734. if (!DependsValid) {
  735. std::string content;
  736. {
  737. std::string error;
  738. if (!wrk.FileSys().FileRead(content, SourceFile, &error)) {
  739. std::string emsg = "Could not read file\n ";
  740. emsg += Quoted(SourceFile);
  741. emsg += "\nrequired by moc include ";
  742. emsg += Quoted(IncludeString);
  743. emsg += " in\n ";
  744. emsg += Quoted(IncluderFile);
  745. emsg += ".\n";
  746. emsg += error;
  747. wrk.LogError(GenT::MOC, emsg);
  748. return false;
  749. }
  750. }
  751. FindDependencies(wrk, content);
  752. }
  753. // Check dependency timestamps
  754. std::string error;
  755. std::string sourceDir = wrk.FileSys().SubDirPrefix(SourceFile);
  756. for (std::string const& depFileRel : Depends) {
  757. std::string depFileAbs =
  758. wrk.Moc().FindIncludedFile(sourceDir, depFileRel);
  759. if (!depFileAbs.empty()) {
  760. if (wrk.FileSys().FileIsOlderThan(BuildFile, depFileAbs, &error)) {
  761. if (verbose) {
  762. std::string reason = "Generating ";
  763. reason += Quoted(BuildFile);
  764. reason += " from ";
  765. reason += Quoted(SourceFile);
  766. reason += " because it is older than it's dependency file ";
  767. reason += Quoted(depFileAbs);
  768. wrk.LogInfo(GenT::MOC, reason);
  769. }
  770. return true;
  771. }
  772. if (!error.empty()) {
  773. wrk.LogError(GenT::MOC, error);
  774. return false;
  775. }
  776. } else {
  777. std::string message = "Could not find dependency file ";
  778. message += Quoted(depFileRel);
  779. wrk.LogFileWarning(GenT::MOC, SourceFile, message);
  780. }
  781. }
  782. }
  783. return false;
  784. }
  785. void cmQtAutoGeneratorMocUic::JobMocT::GenerateMoc(WorkerT& wrk)
  786. {
  787. // Make sure the parent directory exists
  788. if (wrk.FileSys().MakeParentDirectory(GenT::MOC, BuildFile)) {
  789. // Compose moc command
  790. std::vector<std::string> cmd;
  791. cmd.push_back(wrk.Moc().Executable);
  792. // Add options
  793. cmd.insert(cmd.end(), wrk.Moc().AllOptions.begin(),
  794. wrk.Moc().AllOptions.end());
  795. // Add predefs include
  796. if (!wrk.Moc().PredefsFileAbs.empty()) {
  797. cmd.emplace_back("--include");
  798. cmd.push_back(wrk.Moc().PredefsFileAbs);
  799. }
  800. cmd.emplace_back("-o");
  801. cmd.push_back(BuildFile);
  802. cmd.push_back(SourceFile);
  803. // Execute moc command
  804. ProcessResultT result;
  805. if (wrk.RunProcess(GenT::MOC, result, cmd)) {
  806. // Moc command success
  807. // Print moc output
  808. if (!result.StdOut.empty()) {
  809. wrk.LogInfo(GenT::MOC, result.StdOut);
  810. }
  811. // Notify the generator that a not included file changed (on demand)
  812. if (IncludeString.empty()) {
  813. wrk.Gen().ParallelMocAutoUpdated();
  814. }
  815. } else {
  816. // Moc command failed
  817. {
  818. std::string emsg = "The moc process failed to compile\n ";
  819. emsg += Quoted(SourceFile);
  820. emsg += "\ninto\n ";
  821. emsg += Quoted(BuildFile);
  822. emsg += ".\n";
  823. emsg += result.ErrorMessage;
  824. wrk.LogCommandError(GenT::MOC, emsg, cmd, result.StdOut);
  825. }
  826. wrk.FileSys().FileRemove(BuildFile);
  827. }
  828. }
  829. }
  830. void cmQtAutoGeneratorMocUic::JobUicT::Process(WorkerT& wrk)
  831. {
  832. // Compute build file name
  833. BuildFile = wrk.Base().AutogenIncludeDir;
  834. BuildFile += '/';
  835. BuildFile += IncludeString;
  836. if (UpdateRequired(wrk)) {
  837. GenerateUic(wrk);
  838. }
  839. }
  840. bool cmQtAutoGeneratorMocUic::JobUicT::UpdateRequired(WorkerT& wrk)
  841. {
  842. bool const verbose = wrk.Gen().Log().Verbose();
  843. // Test if the build file exists
  844. if (!wrk.FileSys().FileExists(BuildFile)) {
  845. if (verbose) {
  846. std::string reason = "Generating ";
  847. reason += Quoted(BuildFile);
  848. reason += " from its source file ";
  849. reason += Quoted(SourceFile);
  850. reason += " because it doesn't exist";
  851. wrk.LogInfo(GenT::UIC, reason);
  852. }
  853. return true;
  854. }
  855. // Test if the uic settings changed
  856. if (wrk.Uic().SettingsChanged) {
  857. if (verbose) {
  858. std::string reason = "Generating ";
  859. reason += Quoted(BuildFile);
  860. reason += " from ";
  861. reason += Quoted(SourceFile);
  862. reason += " because the UIC settings changed";
  863. wrk.LogInfo(GenT::UIC, reason);
  864. }
  865. return true;
  866. }
  867. // Test if the source file is newer
  868. {
  869. bool isOlder = false;
  870. {
  871. std::string error;
  872. isOlder = wrk.FileSys().FileIsOlderThan(BuildFile, SourceFile, &error);
  873. if (!isOlder && !error.empty()) {
  874. wrk.LogError(GenT::UIC, error);
  875. return false;
  876. }
  877. }
  878. if (isOlder) {
  879. if (verbose) {
  880. std::string reason = "Generating ";
  881. reason += Quoted(BuildFile);
  882. reason += " because it's older than its source file ";
  883. reason += Quoted(SourceFile);
  884. wrk.LogInfo(GenT::UIC, reason);
  885. }
  886. return true;
  887. }
  888. }
  889. return false;
  890. }
  891. void cmQtAutoGeneratorMocUic::JobUicT::GenerateUic(WorkerT& wrk)
  892. {
  893. // Make sure the parent directory exists
  894. if (wrk.FileSys().MakeParentDirectory(GenT::UIC, BuildFile)) {
  895. // Compose uic command
  896. std::vector<std::string> cmd;
  897. cmd.push_back(wrk.Uic().Executable);
  898. {
  899. std::vector<std::string> allOpts = wrk.Uic().TargetOptions;
  900. auto optionIt = wrk.Uic().Options.find(SourceFile);
  901. if (optionIt != wrk.Uic().Options.end()) {
  902. UicMergeOptions(allOpts, optionIt->second,
  903. (wrk.Base().QtVersionMajor == 5));
  904. }
  905. cmd.insert(cmd.end(), allOpts.begin(), allOpts.end());
  906. }
  907. cmd.emplace_back("-o");
  908. cmd.push_back(BuildFile);
  909. cmd.push_back(SourceFile);
  910. ProcessResultT result;
  911. if (wrk.RunProcess(GenT::UIC, result, cmd)) {
  912. // Uic command success
  913. // Print uic output
  914. if (!result.StdOut.empty()) {
  915. wrk.LogInfo(GenT::UIC, result.StdOut);
  916. }
  917. } else {
  918. // Uic command failed
  919. {
  920. std::string emsg = "The uic process failed to compile\n ";
  921. emsg += Quoted(SourceFile);
  922. emsg += "\ninto\n ";
  923. emsg += Quoted(BuildFile);
  924. emsg += "\nincluded by\n ";
  925. emsg += Quoted(IncluderFile);
  926. emsg += ".\n";
  927. emsg += result.ErrorMessage;
  928. wrk.LogCommandError(GenT::UIC, emsg, cmd, result.StdOut);
  929. }
  930. wrk.FileSys().FileRemove(BuildFile);
  931. }
  932. }
  933. }
  934. cmQtAutoGeneratorMocUic::WorkerT::WorkerT(cmQtAutoGeneratorMocUic* gen,
  935. uv_loop_t* uvLoop)
  936. : Gen_(gen)
  937. {
  938. // Initialize uv asynchronous callback for process starting
  939. ProcessRequest_.init(*uvLoop, &WorkerT::UVProcessStart, this);
  940. // Start thread
  941. Thread_ = std::thread(&WorkerT::Loop, this);
  942. }
  943. cmQtAutoGeneratorMocUic::WorkerT::~WorkerT()
  944. {
  945. // Join thread
  946. if (Thread_.joinable()) {
  947. Thread_.join();
  948. }
  949. }
  950. void cmQtAutoGeneratorMocUic::WorkerT::LogInfo(
  951. GenT genType, std::string const& message) const
  952. {
  953. Log().Info(genType, message);
  954. }
  955. void cmQtAutoGeneratorMocUic::WorkerT::LogWarning(
  956. GenT genType, std::string const& message) const
  957. {
  958. Log().Warning(genType, message);
  959. }
  960. void cmQtAutoGeneratorMocUic::WorkerT::LogFileWarning(
  961. GenT genType, std::string const& filename, std::string const& message) const
  962. {
  963. Log().WarningFile(genType, filename, message);
  964. }
  965. void cmQtAutoGeneratorMocUic::WorkerT::LogError(
  966. GenT genType, std::string const& message) const
  967. {
  968. Gen().ParallelRegisterJobError();
  969. Log().Error(genType, message);
  970. }
  971. void cmQtAutoGeneratorMocUic::WorkerT::LogFileError(
  972. GenT genType, std::string const& filename, std::string const& message) const
  973. {
  974. Gen().ParallelRegisterJobError();
  975. Log().ErrorFile(genType, filename, message);
  976. }
  977. void cmQtAutoGeneratorMocUic::WorkerT::LogCommandError(
  978. GenT genType, std::string const& message,
  979. std::vector<std::string> const& command, std::string const& output) const
  980. {
  981. Gen().ParallelRegisterJobError();
  982. Log().ErrorCommand(genType, message, command, output);
  983. }
  984. bool cmQtAutoGeneratorMocUic::WorkerT::RunProcess(
  985. GenT genType, ProcessResultT& result,
  986. std::vector<std::string> const& command)
  987. {
  988. if (command.empty()) {
  989. return false;
  990. }
  991. // Create process instance
  992. {
  993. std::lock_guard<std::mutex> lock(ProcessMutex_);
  994. Process_ = cm::make_unique<ReadOnlyProcessT>();
  995. Process_->setup(&result, true, command, Gen().Base().AutogenBuildDir);
  996. }
  997. // Send asynchronous process start request to libuv loop
  998. ProcessRequest_.send();
  999. // Log command
  1000. if (this->Log().Verbose()) {
  1001. std::string msg = "Running command:\n";
  1002. msg += QuotedCommand(command);
  1003. msg += '\n';
  1004. this->LogInfo(genType, msg);
  1005. }
  1006. // Wait until the process has been finished and destroyed
  1007. {
  1008. std::unique_lock<std::mutex> ulock(ProcessMutex_);
  1009. while (Process_) {
  1010. ProcessCondition_.wait(ulock);
  1011. }
  1012. }
  1013. return !result.error();
  1014. }
  1015. void cmQtAutoGeneratorMocUic::WorkerT::Loop()
  1016. {
  1017. while (true) {
  1018. Gen().WorkerSwapJob(JobHandle_);
  1019. if (JobHandle_) {
  1020. JobHandle_->Process(*this);
  1021. } else {
  1022. break;
  1023. }
  1024. }
  1025. }
  1026. void cmQtAutoGeneratorMocUic::WorkerT::UVProcessStart(uv_async_t* handle)
  1027. {
  1028. auto& wrk = *reinterpret_cast<WorkerT*>(handle->data);
  1029. {
  1030. std::lock_guard<std::mutex> lock(wrk.ProcessMutex_);
  1031. if (wrk.Process_ && !wrk.Process_->IsStarted()) {
  1032. wrk.Process_->start(handle->loop, [&wrk] { wrk.UVProcessFinished(); });
  1033. }
  1034. }
  1035. if (!wrk.Process_->IsStarted()) {
  1036. wrk.UVProcessFinished();
  1037. }
  1038. }
  1039. void cmQtAutoGeneratorMocUic::WorkerT::UVProcessFinished()
  1040. {
  1041. {
  1042. std::lock_guard<std::mutex> lock(ProcessMutex_);
  1043. if (Process_ && (Process_->IsFinished() || !Process_->IsStarted())) {
  1044. Process_.reset();
  1045. }
  1046. }
  1047. // Notify idling thread
  1048. ProcessCondition_.notify_one();
  1049. }
  1050. cmQtAutoGeneratorMocUic::cmQtAutoGeneratorMocUic()
  1051. : Base_(&FileSys())
  1052. , Moc_(&FileSys())
  1053. {
  1054. // Precompile regular expressions
  1055. Moc_.RegExpInclude.compile(
  1056. "(^|\n)[ \t]*#[ \t]*include[ \t]+"
  1057. "[\"<](([^ \">]+/)?moc_[^ \">/]+\\.cpp|[^ \">]+\\.moc)[\">]");
  1058. Uic_.RegExpInclude.compile("(^|\n)[ \t]*#[ \t]*include[ \t]+"
  1059. "[\"<](([^ \">]+/)?ui_[^ \">/]+\\.h)[\">]");
  1060. // Initialize libuv asynchronous iteration request
  1061. UVRequest().init(*UVLoop(), &cmQtAutoGeneratorMocUic::UVPollStage, this);
  1062. }
  1063. cmQtAutoGeneratorMocUic::~cmQtAutoGeneratorMocUic() = default;
  1064. bool cmQtAutoGeneratorMocUic::Init(cmMakefile* makefile)
  1065. {
  1066. // -- Meta
  1067. Base_.HeaderExtensions = makefile->GetCMakeInstance()->GetHeaderExtensions();
  1068. // Utility lambdas
  1069. auto InfoGet = [makefile](const char* key) {
  1070. return makefile->GetSafeDefinition(key);
  1071. };
  1072. auto InfoGetBool = [makefile](const char* key) {
  1073. return makefile->IsOn(key);
  1074. };
  1075. auto InfoGetList = [makefile](const char* key) -> std::vector<std::string> {
  1076. std::vector<std::string> list;
  1077. cmSystemTools::ExpandListArgument(makefile->GetSafeDefinition(key), list);
  1078. return list;
  1079. };
  1080. auto InfoGetLists =
  1081. [makefile](const char* key) -> std::vector<std::vector<std::string>> {
  1082. std::vector<std::vector<std::string>> lists;
  1083. {
  1084. std::string const value = makefile->GetSafeDefinition(key);
  1085. std::string::size_type pos = 0;
  1086. while (pos < value.size()) {
  1087. std::string::size_type next = value.find(ListSep, pos);
  1088. std::string::size_type length =
  1089. (next != std::string::npos) ? next - pos : value.size() - pos;
  1090. // Remove enclosing braces
  1091. if (length >= 2) {
  1092. std::string::const_iterator itBeg = value.begin() + (pos + 1);
  1093. std::string::const_iterator itEnd = itBeg + (length - 2);
  1094. {
  1095. std::string subValue(itBeg, itEnd);
  1096. std::vector<std::string> list;
  1097. cmSystemTools::ExpandListArgument(subValue, list);
  1098. lists.push_back(std::move(list));
  1099. }
  1100. }
  1101. pos += length;
  1102. pos += ListSep.size();
  1103. }
  1104. }
  1105. return lists;
  1106. };
  1107. auto InfoGetConfig = [makefile, this](const char* key) -> std::string {
  1108. const char* valueConf = nullptr;
  1109. {
  1110. std::string keyConf = key;
  1111. keyConf += '_';
  1112. keyConf += InfoConfig();
  1113. valueConf = makefile->GetDefinition(keyConf);
  1114. }
  1115. if (valueConf == nullptr) {
  1116. return makefile->GetSafeDefinition(key);
  1117. }
  1118. return std::string(valueConf);
  1119. };
  1120. auto InfoGetConfigList =
  1121. [&InfoGetConfig](const char* key) -> std::vector<std::string> {
  1122. std::vector<std::string> list;
  1123. cmSystemTools::ExpandListArgument(InfoGetConfig(key), list);
  1124. return list;
  1125. };
  1126. // -- Read info file
  1127. if (!makefile->ReadListFile(InfoFile())) {
  1128. Log().ErrorFile(GenT::GEN, InfoFile(), "File processing failed");
  1129. return false;
  1130. }
  1131. // -- Meta
  1132. Log().RaiseVerbosity(InfoGet("AM_VERBOSITY"));
  1133. Base_.MultiConfig = InfoGetBool("AM_MULTI_CONFIG");
  1134. {
  1135. unsigned long num = Base_.NumThreads;
  1136. if (cmSystemTools::StringToULong(InfoGet("AM_PARALLEL").c_str(), &num)) {
  1137. num = std::max<unsigned long>(num, 1);
  1138. num = std::min<unsigned long>(num, ParallelMax);
  1139. Base_.NumThreads = static_cast<unsigned int>(num);
  1140. }
  1141. }
  1142. // - Files and directories
  1143. Base_.ProjectSourceDir = InfoGet("AM_CMAKE_SOURCE_DIR");
  1144. Base_.ProjectBinaryDir = InfoGet("AM_CMAKE_BINARY_DIR");
  1145. Base_.CurrentSourceDir = InfoGet("AM_CMAKE_CURRENT_SOURCE_DIR");
  1146. Base_.CurrentBinaryDir = InfoGet("AM_CMAKE_CURRENT_BINARY_DIR");
  1147. Base_.IncludeProjectDirsBefore =
  1148. InfoGetBool("AM_CMAKE_INCLUDE_DIRECTORIES_PROJECT_BEFORE");
  1149. Base_.AutogenBuildDir = InfoGet("AM_BUILD_DIR");
  1150. if (Base_.AutogenBuildDir.empty()) {
  1151. Log().ErrorFile(GenT::GEN, InfoFile(), "Autogen build directory missing");
  1152. return false;
  1153. }
  1154. // include directory
  1155. Base_.AutogenIncludeDir = InfoGetConfig("AM_INCLUDE_DIR");
  1156. if (Base_.AutogenIncludeDir.empty()) {
  1157. Log().ErrorFile(GenT::GEN, InfoFile(),
  1158. "Autogen include directory missing");
  1159. return false;
  1160. }
  1161. // - Files
  1162. SettingsFile_ = InfoGetConfig("AM_SETTINGS_FILE");
  1163. if (SettingsFile_.empty()) {
  1164. Log().ErrorFile(GenT::GEN, InfoFile(), "Settings file name missing");
  1165. return false;
  1166. }
  1167. // - Qt environment
  1168. {
  1169. unsigned long qtv = Base_.QtVersionMajor;
  1170. if (cmSystemTools::StringToULong(InfoGet("AM_QT_VERSION_MAJOR").c_str(),
  1171. &qtv)) {
  1172. Base_.QtVersionMajor = static_cast<unsigned int>(qtv);
  1173. }
  1174. }
  1175. // - Moc
  1176. Moc_.Executable = InfoGet("AM_QT_MOC_EXECUTABLE");
  1177. Moc_.Enabled = !Moc().Executable.empty();
  1178. if (Moc().Enabled) {
  1179. for (std::string& sfl : InfoGetList("AM_MOC_SKIP")) {
  1180. Moc_.SkipList.insert(std::move(sfl));
  1181. }
  1182. Moc_.Definitions = InfoGetConfigList("AM_MOC_DEFINITIONS");
  1183. Moc_.IncludePaths = InfoGetConfigList("AM_MOC_INCLUDES");
  1184. Moc_.Options = InfoGetList("AM_MOC_OPTIONS");
  1185. Moc_.RelaxedMode = InfoGetBool("AM_MOC_RELAXED_MODE");
  1186. for (std::string const& item : InfoGetList("AM_MOC_MACRO_NAMES")) {
  1187. Moc_.MacroFilters.emplace_back(
  1188. item, ("[\n][ \t]*{?[ \t]*" + item).append("[^a-zA-Z0-9_]"));
  1189. }
  1190. {
  1191. auto pushFilter = [this](std::string const& key, std::string const& exp,
  1192. std::string& error) {
  1193. if (!key.empty()) {
  1194. if (!exp.empty()) {
  1195. Moc_.DependFilters.emplace_back();
  1196. KeyExpT& filter(Moc_.DependFilters.back());
  1197. if (filter.Exp.compile(exp)) {
  1198. filter.Key = key;
  1199. } else {
  1200. error = "Regular expression compiling failed";
  1201. }
  1202. } else {
  1203. error = "Regular expression is empty";
  1204. }
  1205. } else {
  1206. error = "Key is empty";
  1207. }
  1208. if (!error.empty()) {
  1209. error = ("AUTOMOC_DEPEND_FILTERS: " + error);
  1210. error += "\n";
  1211. error += " Key: ";
  1212. error += Quoted(key);
  1213. error += "\n";
  1214. error += " Exp: ";
  1215. error += Quoted(exp);
  1216. error += "\n";
  1217. }
  1218. };
  1219. std::string error;
  1220. // Insert default filter for Q_PLUGIN_METADATA
  1221. if (Base().QtVersionMajor != 4) {
  1222. pushFilter("Q_PLUGIN_METADATA",
  1223. "[\n][ \t]*Q_PLUGIN_METADATA[ \t]*\\("
  1224. "[^\\)]*FILE[ \t]*\"([^\"]+)\"",
  1225. error);
  1226. }
  1227. // Insert user defined dependency filters
  1228. {
  1229. std::vector<std::string> flts = InfoGetList("AM_MOC_DEPEND_FILTERS");
  1230. if ((flts.size() % 2) == 0) {
  1231. for (std::vector<std::string>::iterator itC = flts.begin(),
  1232. itE = flts.end();
  1233. itC != itE; itC += 2) {
  1234. pushFilter(*itC, *(itC + 1), error);
  1235. if (!error.empty()) {
  1236. break;
  1237. }
  1238. }
  1239. } else {
  1240. Log().ErrorFile(
  1241. GenT::MOC, InfoFile(),
  1242. "AUTOMOC_DEPEND_FILTERS list size is not a multiple of 2");
  1243. return false;
  1244. }
  1245. }
  1246. if (!error.empty()) {
  1247. Log().ErrorFile(GenT::MOC, InfoFile(), error);
  1248. return false;
  1249. }
  1250. }
  1251. Moc_.PredefsCmd = InfoGetList("AM_MOC_PREDEFS_CMD");
  1252. // Install moc predefs job
  1253. if (!Moc().PredefsCmd.empty()) {
  1254. JobQueues_.MocPredefs.emplace_back(cm::make_unique<JobMocPredefsT>());
  1255. }
  1256. }
  1257. // - Uic
  1258. Uic_.Executable = InfoGet("AM_QT_UIC_EXECUTABLE");
  1259. Uic_.Enabled = !Uic().Executable.empty();
  1260. if (Uic().Enabled) {
  1261. for (std::string& sfl : InfoGetList("AM_UIC_SKIP")) {
  1262. Uic_.SkipList.insert(std::move(sfl));
  1263. }
  1264. Uic_.SearchPaths = InfoGetList("AM_UIC_SEARCH_PATHS");
  1265. Uic_.TargetOptions = InfoGetConfigList("AM_UIC_TARGET_OPTIONS");
  1266. {
  1267. auto sources = InfoGetList("AM_UIC_OPTIONS_FILES");
  1268. auto options = InfoGetLists("AM_UIC_OPTIONS_OPTIONS");
  1269. // Compare list sizes
  1270. if (sources.size() != options.size()) {
  1271. std::ostringstream ost;
  1272. ost << "files/options lists sizes mismatch (" << sources.size() << "/"
  1273. << options.size() << ")";
  1274. Log().ErrorFile(GenT::UIC, InfoFile(), ost.str());
  1275. return false;
  1276. }
  1277. auto fitEnd = sources.cend();
  1278. auto fit = sources.begin();
  1279. auto oit = options.begin();
  1280. while (fit != fitEnd) {
  1281. Uic_.Options[*fit] = std::move(*oit);
  1282. ++fit;
  1283. ++oit;
  1284. }
  1285. }
  1286. }
  1287. // - Headers and sources
  1288. {
  1289. auto addHeader = [this](std::string&& hdr, bool moc, bool uic) {
  1290. this->JobQueues_.Headers.emplace_back(
  1291. cm::make_unique<JobParseT>(std::move(hdr), moc, uic, true));
  1292. };
  1293. auto addSource = [this](std::string&& src, bool moc, bool uic) {
  1294. this->JobQueues_.Sources.emplace_back(
  1295. cm::make_unique<JobParseT>(std::move(src), moc, uic, false));
  1296. };
  1297. // Add headers
  1298. for (std::string& hdr : InfoGetList("AM_HEADERS")) {
  1299. addHeader(std::move(hdr), true, true);
  1300. }
  1301. if (Moc().Enabled) {
  1302. for (std::string& hdr : InfoGetList("AM_MOC_HEADERS")) {
  1303. addHeader(std::move(hdr), true, false);
  1304. }
  1305. }
  1306. if (Uic().Enabled) {
  1307. for (std::string& hdr : InfoGetList("AM_UIC_HEADERS")) {
  1308. addHeader(std::move(hdr), false, true);
  1309. }
  1310. }
  1311. // Add sources
  1312. for (std::string& src : InfoGetList("AM_SOURCES")) {
  1313. addSource(std::move(src), true, true);
  1314. }
  1315. if (Moc().Enabled) {
  1316. for (std::string& src : InfoGetList("AM_MOC_SOURCES")) {
  1317. addSource(std::move(src), true, false);
  1318. }
  1319. }
  1320. if (Uic().Enabled) {
  1321. for (std::string& src : InfoGetList("AM_UIC_SOURCES")) {
  1322. addSource(std::move(src), false, true);
  1323. }
  1324. }
  1325. }
  1326. // Init derived information
  1327. // ------------------------
  1328. // Init file path checksum generator
  1329. FileSys().setupFilePathChecksum(
  1330. Base().CurrentSourceDir, Base().CurrentBinaryDir, Base().ProjectSourceDir,
  1331. Base().ProjectBinaryDir);
  1332. // Moc variables
  1333. if (Moc().Enabled) {
  1334. // Mocs compilation file
  1335. Moc_.CompFileAbs = Base().AbsoluteBuildPath("mocs_compilation.cpp");
  1336. // Moc predefs file
  1337. if (!Moc_.PredefsCmd.empty()) {
  1338. Moc_.PredefsFileRel = "moc_predefs";
  1339. if (Base_.MultiConfig) {
  1340. Moc_.PredefsFileRel += '_';
  1341. Moc_.PredefsFileRel += InfoConfig();
  1342. }
  1343. Moc_.PredefsFileRel += ".h";
  1344. Moc_.PredefsFileAbs = Base_.AbsoluteBuildPath(Moc().PredefsFileRel);
  1345. }
  1346. // Sort include directories on demand
  1347. if (Base().IncludeProjectDirsBefore) {
  1348. // Move strings to temporary list
  1349. std::list<std::string> includes;
  1350. includes.insert(includes.end(), Moc().IncludePaths.begin(),
  1351. Moc().IncludePaths.end());
  1352. Moc_.IncludePaths.clear();
  1353. Moc_.IncludePaths.reserve(includes.size());
  1354. // Append project directories only
  1355. {
  1356. std::array<std::string const*, 2> const movePaths = {
  1357. { &Base().ProjectBinaryDir, &Base().ProjectSourceDir }
  1358. };
  1359. for (std::string const* ppath : movePaths) {
  1360. std::list<std::string>::iterator it = includes.begin();
  1361. while (it != includes.end()) {
  1362. std::string const& path = *it;
  1363. if (cmSystemTools::StringStartsWith(path, ppath->c_str())) {
  1364. Moc_.IncludePaths.push_back(path);
  1365. it = includes.erase(it);
  1366. } else {
  1367. ++it;
  1368. }
  1369. }
  1370. }
  1371. }
  1372. // Append remaining directories
  1373. Moc_.IncludePaths.insert(Moc_.IncludePaths.end(), includes.begin(),
  1374. includes.end());
  1375. }
  1376. // Compose moc includes list
  1377. {
  1378. std::set<std::string> frameworkPaths;
  1379. for (std::string const& path : Moc().IncludePaths) {
  1380. Moc_.Includes.push_back("-I" + path);
  1381. // Extract framework path
  1382. if (cmHasLiteralSuffix(path, ".framework/Headers")) {
  1383. // Go up twice to get to the framework root
  1384. std::vector<std::string> pathComponents;
  1385. FileSys().SplitPath(path, pathComponents);
  1386. std::string frameworkPath = FileSys().JoinPath(
  1387. pathComponents.begin(), pathComponents.end() - 2);
  1388. frameworkPaths.insert(frameworkPath);
  1389. }
  1390. }
  1391. // Append framework includes
  1392. for (std::string const& path : frameworkPaths) {
  1393. Moc_.Includes.emplace_back("-F");
  1394. Moc_.Includes.push_back(path);
  1395. }
  1396. }
  1397. // Setup single list with all options
  1398. {
  1399. // Add includes
  1400. Moc_.AllOptions.insert(Moc_.AllOptions.end(), Moc().Includes.begin(),
  1401. Moc().Includes.end());
  1402. // Add definitions
  1403. for (std::string const& def : Moc().Definitions) {
  1404. Moc_.AllOptions.push_back("-D" + def);
  1405. }
  1406. // Add options
  1407. Moc_.AllOptions.insert(Moc_.AllOptions.end(), Moc().Options.begin(),
  1408. Moc().Options.end());
  1409. }
  1410. }
  1411. return true;
  1412. }
  1413. bool cmQtAutoGeneratorMocUic::Process()
  1414. {
  1415. // Run libuv event loop
  1416. UVRequest().send();
  1417. if (uv_run(UVLoop(), UV_RUN_DEFAULT) == 0) {
  1418. if (JobError_) {
  1419. return false;
  1420. }
  1421. } else {
  1422. return false;
  1423. }
  1424. return true;
  1425. }
  1426. void cmQtAutoGeneratorMocUic::UVPollStage(uv_async_t* handle)
  1427. {
  1428. reinterpret_cast<cmQtAutoGeneratorMocUic*>(handle->data)->PollStage();
  1429. }
  1430. void cmQtAutoGeneratorMocUic::PollStage()
  1431. {
  1432. switch (Stage_) {
  1433. case StageT::SETTINGS_READ:
  1434. SettingsFileRead();
  1435. SetStage(StageT::CREATE_DIRECTORIES);
  1436. break;
  1437. case StageT::CREATE_DIRECTORIES:
  1438. CreateDirectories();
  1439. SetStage(StageT::PARSE_SOURCES);
  1440. break;
  1441. case StageT::PARSE_SOURCES:
  1442. if (ThreadsStartJobs(JobQueues_.Sources)) {
  1443. SetStage(StageT::PARSE_HEADERS);
  1444. }
  1445. break;
  1446. case StageT::PARSE_HEADERS:
  1447. if (ThreadsStartJobs(JobQueues_.Headers)) {
  1448. SetStage(StageT::MOC_PREDEFS);
  1449. }
  1450. break;
  1451. case StageT::MOC_PREDEFS:
  1452. if (ThreadsStartJobs(JobQueues_.MocPredefs)) {
  1453. SetStage(StageT::MOC_PROCESS);
  1454. }
  1455. break;
  1456. case StageT::MOC_PROCESS:
  1457. if (ThreadsStartJobs(JobQueues_.Moc)) {
  1458. SetStage(StageT::MOCS_COMPILATION);
  1459. }
  1460. break;
  1461. case StageT::MOCS_COMPILATION:
  1462. if (ThreadsJobsDone()) {
  1463. MocGenerateCompilation();
  1464. SetStage(StageT::UIC_PROCESS);
  1465. }
  1466. break;
  1467. case StageT::UIC_PROCESS:
  1468. if (ThreadsStartJobs(JobQueues_.Uic)) {
  1469. SetStage(StageT::SETTINGS_WRITE);
  1470. }
  1471. break;
  1472. case StageT::SETTINGS_WRITE:
  1473. SettingsFileWrite();
  1474. SetStage(StageT::FINISH);
  1475. break;
  1476. case StageT::FINISH:
  1477. if (ThreadsJobsDone()) {
  1478. // Clear all libuv handles
  1479. ThreadsStop();
  1480. UVRequest().reset();
  1481. // Set highest END stage manually
  1482. Stage_ = StageT::END;
  1483. }
  1484. break;
  1485. case StageT::END:
  1486. break;
  1487. }
  1488. }
  1489. void cmQtAutoGeneratorMocUic::SetStage(StageT stage)
  1490. {
  1491. if (JobError_) {
  1492. stage = StageT::FINISH;
  1493. }
  1494. // Only allow to increase the stage
  1495. if (Stage_ < stage) {
  1496. Stage_ = stage;
  1497. UVRequest().send();
  1498. }
  1499. }
  1500. void cmQtAutoGeneratorMocUic::SettingsFileRead()
  1501. {
  1502. // Compose current settings strings
  1503. {
  1504. cmCryptoHash crypt(cmCryptoHash::AlgoSHA256);
  1505. std::string const sep(" ~~~ ");
  1506. if (Moc_.Enabled) {
  1507. std::string str;
  1508. str += Moc().Executable;
  1509. str += sep;
  1510. str += cmJoin(Moc().AllOptions, ";");
  1511. str += sep;
  1512. str += Base().IncludeProjectDirsBefore ? "TRUE" : "FALSE";
  1513. str += sep;
  1514. str += cmJoin(Moc().PredefsCmd, ";");
  1515. str += sep;
  1516. SettingsStringMoc_ = crypt.HashString(str);
  1517. }
  1518. if (Uic().Enabled) {
  1519. std::string str;
  1520. str += Uic().Executable;
  1521. str += sep;
  1522. str += cmJoin(Uic().TargetOptions, ";");
  1523. for (const auto& item : Uic().Options) {
  1524. str += sep;
  1525. str += item.first;
  1526. str += sep;
  1527. str += cmJoin(item.second, ";");
  1528. }
  1529. str += sep;
  1530. SettingsStringUic_ = crypt.HashString(str);
  1531. }
  1532. }
  1533. // Read old settings and compare
  1534. {
  1535. std::string content;
  1536. if (FileSys().FileRead(content, SettingsFile_)) {
  1537. if (Moc().Enabled) {
  1538. if (SettingsStringMoc_ != SettingsFind(content, "moc")) {
  1539. Moc_.SettingsChanged = true;
  1540. }
  1541. }
  1542. if (Uic().Enabled) {
  1543. if (SettingsStringUic_ != SettingsFind(content, "uic")) {
  1544. Uic_.SettingsChanged = true;
  1545. }
  1546. }
  1547. // In case any setting changed remove the old settings file.
  1548. // This triggers a full rebuild on the next run if the current
  1549. // build is aborted before writing the current settings in the end.
  1550. if (Moc().SettingsChanged || Uic().SettingsChanged) {
  1551. FileSys().FileRemove(SettingsFile_);
  1552. }
  1553. } else {
  1554. // Settings file read failed
  1555. if (Moc().Enabled) {
  1556. Moc_.SettingsChanged = true;
  1557. }
  1558. if (Uic().Enabled) {
  1559. Uic_.SettingsChanged = true;
  1560. }
  1561. }
  1562. }
  1563. }
  1564. void cmQtAutoGeneratorMocUic::SettingsFileWrite()
  1565. {
  1566. std::lock_guard<std::mutex> jobsLock(JobsMutex_);
  1567. // Only write if any setting changed
  1568. if (!JobError_ && (Moc().SettingsChanged || Uic().SettingsChanged)) {
  1569. if (Log().Verbose()) {
  1570. Log().Info(GenT::GEN, "Writing settings file " + Quoted(SettingsFile_));
  1571. }
  1572. // Compose settings file content
  1573. std::string content;
  1574. {
  1575. auto SettingAppend = [&content](const char* key,
  1576. std::string const& value) {
  1577. if (!value.empty()) {
  1578. content += key;
  1579. content += ':';
  1580. content += value;
  1581. content += '\n';
  1582. }
  1583. };
  1584. SettingAppend("moc", SettingsStringMoc_);
  1585. SettingAppend("uic", SettingsStringUic_);
  1586. }
  1587. // Write settings file
  1588. if (!FileSys().FileWrite(GenT::GEN, SettingsFile_, content)) {
  1589. Log().ErrorFile(GenT::GEN, SettingsFile_,
  1590. "Settings file writing failed");
  1591. // Remove old settings file to trigger a full rebuild on the next run
  1592. FileSys().FileRemove(SettingsFile_);
  1593. RegisterJobError();
  1594. }
  1595. }
  1596. }
  1597. void cmQtAutoGeneratorMocUic::CreateDirectories()
  1598. {
  1599. // Create AUTOGEN include directory
  1600. if (!FileSys().MakeDirectory(GenT::GEN, Base().AutogenIncludeDir)) {
  1601. RegisterJobError();
  1602. }
  1603. }
  1604. bool cmQtAutoGeneratorMocUic::ThreadsStartJobs(JobQueueT& queue)
  1605. {
  1606. bool done = false;
  1607. std::size_t queueSize = queue.size();
  1608. // Change the active queue
  1609. {
  1610. std::lock_guard<std::mutex> jobsLock(JobsMutex_);
  1611. // Check if there are still unfinished jobs from the previous queue
  1612. if (JobsRemain_ == 0) {
  1613. if (!JobThreadsAbort_) {
  1614. JobQueue_.swap(queue);
  1615. JobsRemain_ = queueSize;
  1616. } else {
  1617. // Abort requested
  1618. queue.clear();
  1619. queueSize = 0;
  1620. }
  1621. done = true;
  1622. }
  1623. }
  1624. if (done && (queueSize != 0)) {
  1625. // Start new threads on demand
  1626. if (Workers_.empty()) {
  1627. Workers_.resize(Base().NumThreads);
  1628. for (auto& item : Workers_) {
  1629. item = cm::make_unique<WorkerT>(this, UVLoop());
  1630. }
  1631. } else {
  1632. // Notify threads
  1633. if (queueSize == 1) {
  1634. JobsConditionRead_.notify_one();
  1635. } else {
  1636. JobsConditionRead_.notify_all();
  1637. }
  1638. }
  1639. }
  1640. return done;
  1641. }
  1642. void cmQtAutoGeneratorMocUic::ThreadsStop()
  1643. {
  1644. if (!Workers_.empty()) {
  1645. // Clear all jobs
  1646. {
  1647. std::lock_guard<std::mutex> jobsLock(JobsMutex_);
  1648. JobThreadsAbort_ = true;
  1649. JobsRemain_ -= JobQueue_.size();
  1650. JobQueue_.clear();
  1651. JobQueues_.Sources.clear();
  1652. JobQueues_.Headers.clear();
  1653. JobQueues_.MocPredefs.clear();
  1654. JobQueues_.Moc.clear();
  1655. JobQueues_.Uic.clear();
  1656. }
  1657. // Wake threads
  1658. JobsConditionRead_.notify_all();
  1659. // Join and clear threads
  1660. Workers_.clear();
  1661. }
  1662. }
  1663. bool cmQtAutoGeneratorMocUic::ThreadsJobsDone()
  1664. {
  1665. std::lock_guard<std::mutex> jobsLock(JobsMutex_);
  1666. return (JobsRemain_ == 0);
  1667. }
  1668. void cmQtAutoGeneratorMocUic::WorkerSwapJob(JobHandleT& jobHandle)
  1669. {
  1670. bool const jobProcessed(jobHandle);
  1671. if (jobProcessed) {
  1672. jobHandle.reset();
  1673. }
  1674. {
  1675. std::unique_lock<std::mutex> jobsLock(JobsMutex_);
  1676. // Reduce the remaining job count and notify the libuv loop
  1677. // when all jobs are done
  1678. if (jobProcessed) {
  1679. --JobsRemain_;
  1680. if (JobsRemain_ == 0) {
  1681. UVRequest().send();
  1682. }
  1683. }
  1684. // Wait for new jobs
  1685. while (!JobThreadsAbort_ && JobQueue_.empty()) {
  1686. JobsConditionRead_.wait(jobsLock);
  1687. }
  1688. // Try to pick up a new job handle
  1689. if (!JobThreadsAbort_ && !JobQueue_.empty()) {
  1690. jobHandle = std::move(JobQueue_.front());
  1691. JobQueue_.pop_front();
  1692. }
  1693. }
  1694. }
  1695. void cmQtAutoGeneratorMocUic::ParallelRegisterJobError()
  1696. {
  1697. std::lock_guard<std::mutex> jobsLock(JobsMutex_);
  1698. RegisterJobError();
  1699. }
  1700. // Private method that requires cmQtAutoGeneratorMocUic::JobsMutex_ to be
  1701. // locked
  1702. void cmQtAutoGeneratorMocUic::RegisterJobError()
  1703. {
  1704. JobError_ = true;
  1705. if (!JobThreadsAbort_) {
  1706. JobThreadsAbort_ = true;
  1707. // Clear remaining jobs
  1708. if (JobsRemain_ != 0) {
  1709. JobsRemain_ -= JobQueue_.size();
  1710. JobQueue_.clear();
  1711. }
  1712. }
  1713. }
  1714. bool cmQtAutoGeneratorMocUic::ParallelJobPushMoc(JobHandleT& jobHandle)
  1715. {
  1716. std::lock_guard<std::mutex> jobsLock(JobsMutex_);
  1717. if (!JobThreadsAbort_) {
  1718. bool pushJobHandle = true;
  1719. // Do additional tests if this is an included moc job
  1720. const JobMocT& mocJob(static_cast<JobMocT&>(*jobHandle));
  1721. if (!mocJob.IncludeString.empty()) {
  1722. // Register included moc file and look for collisions
  1723. MocIncludedFiles_.emplace(mocJob.SourceFile);
  1724. if (!MocIncludedStrings_.emplace(mocJob.IncludeString).second) {
  1725. // Another source file includes the same moc file!
  1726. for (const JobHandleT& otherHandle : JobQueues_.Moc) {
  1727. const JobMocT& otherJob(static_cast<JobMocT&>(*otherHandle));
  1728. if (otherJob.IncludeString == mocJob.IncludeString) {
  1729. // Check if the same moc file would be generated from different
  1730. // source files which is an error.
  1731. if (otherJob.SourceFile != mocJob.SourceFile) {
  1732. // Include string collision
  1733. std::string error = "The two source files\n ";
  1734. error += Quoted(mocJob.IncluderFile);
  1735. error += " and\n ";
  1736. error += Quoted(otherJob.IncluderFile);
  1737. error += "\ncontain the same moc include string ";
  1738. error += Quoted(mocJob.IncludeString);
  1739. error += "\nbut the moc file would be generated from different "
  1740. "source files\n ";
  1741. error += Quoted(mocJob.SourceFile);
  1742. error += " and\n ";
  1743. error += Quoted(otherJob.SourceFile);
  1744. error += ".\nConsider to\n"
  1745. "- not include the \"moc_<NAME>.cpp\" file\n"
  1746. "- add a directory prefix to a \"<NAME>.moc\" include "
  1747. "(e.g \"sub/<NAME>.moc\")\n"
  1748. "- rename the source file(s)\n";
  1749. Log().Error(GenT::MOC, error);
  1750. RegisterJobError();
  1751. }
  1752. // Do not push this job in since the included moc file already
  1753. // gets generated by an other job.
  1754. pushJobHandle = false;
  1755. break;
  1756. }
  1757. }
  1758. }
  1759. }
  1760. // Push job on demand
  1761. if (pushJobHandle) {
  1762. JobQueues_.Moc.emplace_back(std::move(jobHandle));
  1763. }
  1764. }
  1765. return !JobError_;
  1766. }
  1767. bool cmQtAutoGeneratorMocUic::ParallelJobPushUic(JobHandleT& jobHandle)
  1768. {
  1769. std::lock_guard<std::mutex> jobsLock(JobsMutex_);
  1770. if (!JobThreadsAbort_) {
  1771. bool pushJobHandle = true;
  1772. // Look for include collisions.
  1773. const JobUicT& uicJob(static_cast<JobUicT&>(*jobHandle));
  1774. for (const JobHandleT& otherHandle : JobQueues_.Uic) {
  1775. const JobUicT& otherJob(static_cast<JobUicT&>(*otherHandle));
  1776. if (otherJob.IncludeString == uicJob.IncludeString) {
  1777. // Check if the same uic file would be generated from different
  1778. // source files which would be an error.
  1779. if (otherJob.SourceFile != uicJob.SourceFile) {
  1780. // Include string collision
  1781. std::string error = "The two source files\n ";
  1782. error += Quoted(uicJob.IncluderFile);
  1783. error += " and\n ";
  1784. error += Quoted(otherJob.IncluderFile);
  1785. error += "\ncontain the same uic include string ";
  1786. error += Quoted(uicJob.IncludeString);
  1787. error += "\nbut the uic file would be generated from different "
  1788. "source files\n ";
  1789. error += Quoted(uicJob.SourceFile);
  1790. error += " and\n ";
  1791. error += Quoted(otherJob.SourceFile);
  1792. error +=
  1793. ".\nConsider to\n"
  1794. "- add a directory prefix to a \"ui_<NAME>.h\" include "
  1795. "(e.g \"sub/ui_<NAME>.h\")\n"
  1796. "- rename the <NAME>.ui file(s) and adjust the \"ui_<NAME>.h\" "
  1797. "include(s)\n";
  1798. Log().Error(GenT::UIC, error);
  1799. RegisterJobError();
  1800. }
  1801. // Do not push this job in since the uic file already
  1802. // gets generated by an other job.
  1803. pushJobHandle = false;
  1804. break;
  1805. }
  1806. }
  1807. if (pushJobHandle) {
  1808. JobQueues_.Uic.emplace_back(std::move(jobHandle));
  1809. }
  1810. }
  1811. return !JobError_;
  1812. }
  1813. bool cmQtAutoGeneratorMocUic::ParallelMocIncluded(
  1814. std::string const& sourceFile)
  1815. {
  1816. std::lock_guard<std::mutex> mocLock(JobsMutex_);
  1817. return (MocIncludedFiles_.find(sourceFile) != MocIncludedFiles_.end());
  1818. }
  1819. std::string cmQtAutoGeneratorMocUic::ParallelMocAutoRegister(
  1820. std::string const& baseName)
  1821. {
  1822. std::string res;
  1823. {
  1824. std::lock_guard<std::mutex> mocLock(JobsMutex_);
  1825. res = baseName;
  1826. res += ".cpp";
  1827. if (MocAutoFiles_.find(res) == MocAutoFiles_.end()) {
  1828. MocAutoFiles_.emplace(res);
  1829. } else {
  1830. // Append number suffix to the file name
  1831. for (unsigned int ii = 2; ii != 1024; ++ii) {
  1832. res = baseName;
  1833. res += '_';
  1834. res += std::to_string(ii);
  1835. res += ".cpp";
  1836. if (MocAutoFiles_.find(res) == MocAutoFiles_.end()) {
  1837. MocAutoFiles_.emplace(res);
  1838. break;
  1839. }
  1840. }
  1841. }
  1842. }
  1843. return res;
  1844. }
  1845. void cmQtAutoGeneratorMocUic::ParallelMocAutoUpdated()
  1846. {
  1847. std::lock_guard<std::mutex> mocLock(JobsMutex_);
  1848. MocAutoFileUpdated_ = true;
  1849. }
  1850. void cmQtAutoGeneratorMocUic::MocGenerateCompilation()
  1851. {
  1852. std::lock_guard<std::mutex> mocLock(JobsMutex_);
  1853. if (!JobError_ && Moc().Enabled) {
  1854. // Write mocs compilation build file
  1855. {
  1856. // Compose mocs compilation file content
  1857. std::string content =
  1858. "// This file is autogenerated. Changes will be overwritten.\n";
  1859. if (MocAutoFiles_.empty()) {
  1860. // Placeholder content
  1861. content += "// No files found that require moc or the moc files are "
  1862. "included\n";
  1863. content += "enum some_compilers { need_more_than_nothing };\n";
  1864. } else {
  1865. // Valid content
  1866. char const sbeg = Base().MultiConfig ? '<' : '"';
  1867. char const send = Base().MultiConfig ? '>' : '"';
  1868. for (std::string const& mocfile : MocAutoFiles_) {
  1869. content += "#include ";
  1870. content += sbeg;
  1871. content += mocfile;
  1872. content += send;
  1873. content += '\n';
  1874. }
  1875. }
  1876. std::string const& compAbs = Moc().CompFileAbs;
  1877. if (FileSys().FileDiffers(compAbs, content)) {
  1878. // Actually write mocs compilation file
  1879. if (Log().Verbose()) {
  1880. Log().Info(GenT::MOC, "Generating MOC compilation " + compAbs);
  1881. }
  1882. if (!FileSys().FileWrite(GenT::MOC, compAbs, content)) {
  1883. Log().ErrorFile(GenT::MOC, compAbs,
  1884. "mocs compilation file writing failed");
  1885. RegisterJobError();
  1886. return;
  1887. }
  1888. } else if (MocAutoFileUpdated_) {
  1889. // Only touch mocs compilation file
  1890. if (Log().Verbose()) {
  1891. Log().Info(GenT::MOC, "Touching mocs compilation " + compAbs);
  1892. }
  1893. FileSys().Touch(compAbs);
  1894. }
  1895. }
  1896. // Write mocs compilation wrapper file
  1897. if (Base().MultiConfig) {
  1898. }
  1899. }
  1900. }