cmQtAutoGeneratorMocUic.cxx 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020
  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. }
  1036. void cmQtAutoGeneratorMocUic::WorkerT::UVProcessFinished()
  1037. {
  1038. {
  1039. std::lock_guard<std::mutex> lock(ProcessMutex_);
  1040. if (Process_ && Process_->IsFinished()) {
  1041. Process_.reset();
  1042. }
  1043. }
  1044. // Notify idling thread
  1045. ProcessCondition_.notify_one();
  1046. }
  1047. cmQtAutoGeneratorMocUic::cmQtAutoGeneratorMocUic()
  1048. : Base_(&FileSys())
  1049. , Moc_(&FileSys())
  1050. {
  1051. // Precompile regular expressions
  1052. Moc_.RegExpInclude.compile(
  1053. "(^|\n)[ \t]*#[ \t]*include[ \t]+"
  1054. "[\"<](([^ \">]+/)?moc_[^ \">/]+\\.cpp|[^ \">]+\\.moc)[\">]");
  1055. Uic_.RegExpInclude.compile("(^|\n)[ \t]*#[ \t]*include[ \t]+"
  1056. "[\"<](([^ \">]+/)?ui_[^ \">/]+\\.h)[\">]");
  1057. // Initialize libuv asynchronous iteration request
  1058. UVRequest().init(*UVLoop(), &cmQtAutoGeneratorMocUic::UVPollStage, this);
  1059. }
  1060. cmQtAutoGeneratorMocUic::~cmQtAutoGeneratorMocUic() = default;
  1061. bool cmQtAutoGeneratorMocUic::Init(cmMakefile* makefile)
  1062. {
  1063. // -- Meta
  1064. Base_.HeaderExtensions = makefile->GetCMakeInstance()->GetHeaderExtensions();
  1065. // Utility lambdas
  1066. auto InfoGet = [makefile](const char* key) {
  1067. return makefile->GetSafeDefinition(key);
  1068. };
  1069. auto InfoGetBool = [makefile](const char* key) {
  1070. return makefile->IsOn(key);
  1071. };
  1072. auto InfoGetList = [makefile](const char* key) -> std::vector<std::string> {
  1073. std::vector<std::string> list;
  1074. cmSystemTools::ExpandListArgument(makefile->GetSafeDefinition(key), list);
  1075. return list;
  1076. };
  1077. auto InfoGetLists =
  1078. [makefile](const char* key) -> std::vector<std::vector<std::string>> {
  1079. std::vector<std::vector<std::string>> lists;
  1080. {
  1081. std::string const value = makefile->GetSafeDefinition(key);
  1082. std::string::size_type pos = 0;
  1083. while (pos < value.size()) {
  1084. std::string::size_type next = value.find(ListSep, pos);
  1085. std::string::size_type length =
  1086. (next != std::string::npos) ? next - pos : value.size() - pos;
  1087. // Remove enclosing braces
  1088. if (length >= 2) {
  1089. std::string::const_iterator itBeg = value.begin() + (pos + 1);
  1090. std::string::const_iterator itEnd = itBeg + (length - 2);
  1091. {
  1092. std::string subValue(itBeg, itEnd);
  1093. std::vector<std::string> list;
  1094. cmSystemTools::ExpandListArgument(subValue, list);
  1095. lists.push_back(std::move(list));
  1096. }
  1097. }
  1098. pos += length;
  1099. pos += ListSep.size();
  1100. }
  1101. }
  1102. return lists;
  1103. };
  1104. auto InfoGetConfig = [makefile, this](const char* key) -> std::string {
  1105. const char* valueConf = nullptr;
  1106. {
  1107. std::string keyConf = key;
  1108. keyConf += '_';
  1109. keyConf += InfoConfig();
  1110. valueConf = makefile->GetDefinition(keyConf);
  1111. }
  1112. if (valueConf == nullptr) {
  1113. return makefile->GetSafeDefinition(key);
  1114. }
  1115. return std::string(valueConf);
  1116. };
  1117. auto InfoGetConfigList =
  1118. [&InfoGetConfig](const char* key) -> std::vector<std::string> {
  1119. std::vector<std::string> list;
  1120. cmSystemTools::ExpandListArgument(InfoGetConfig(key), list);
  1121. return list;
  1122. };
  1123. // -- Read info file
  1124. if (!makefile->ReadListFile(InfoFile())) {
  1125. Log().ErrorFile(GenT::GEN, InfoFile(), "File processing failed");
  1126. return false;
  1127. }
  1128. // -- Meta
  1129. Log().RaiseVerbosity(InfoGet("AM_VERBOSITY"));
  1130. Base_.MultiConfig = InfoGetBool("AM_MULTI_CONFIG");
  1131. {
  1132. unsigned long num = Base_.NumThreads;
  1133. if (cmSystemTools::StringToULong(InfoGet("AM_PARALLEL").c_str(), &num)) {
  1134. num = std::max<unsigned long>(num, 1);
  1135. num = std::min<unsigned long>(num, ParallelMax);
  1136. Base_.NumThreads = static_cast<unsigned int>(num);
  1137. }
  1138. }
  1139. // - Files and directories
  1140. Base_.ProjectSourceDir = InfoGet("AM_CMAKE_SOURCE_DIR");
  1141. Base_.ProjectBinaryDir = InfoGet("AM_CMAKE_BINARY_DIR");
  1142. Base_.CurrentSourceDir = InfoGet("AM_CMAKE_CURRENT_SOURCE_DIR");
  1143. Base_.CurrentBinaryDir = InfoGet("AM_CMAKE_CURRENT_BINARY_DIR");
  1144. Base_.IncludeProjectDirsBefore =
  1145. InfoGetBool("AM_CMAKE_INCLUDE_DIRECTORIES_PROJECT_BEFORE");
  1146. Base_.AutogenBuildDir = InfoGet("AM_BUILD_DIR");
  1147. if (Base_.AutogenBuildDir.empty()) {
  1148. Log().ErrorFile(GenT::GEN, InfoFile(), "Autogen build directory missing");
  1149. return false;
  1150. }
  1151. // include directory
  1152. Base_.AutogenIncludeDir = InfoGetConfig("AM_INCLUDE_DIR");
  1153. if (Base_.AutogenIncludeDir.empty()) {
  1154. Log().ErrorFile(GenT::GEN, InfoFile(),
  1155. "Autogen include directory missing");
  1156. return false;
  1157. }
  1158. // - Files
  1159. SettingsFile_ = InfoGetConfig("AM_SETTINGS_FILE");
  1160. if (SettingsFile_.empty()) {
  1161. Log().ErrorFile(GenT::GEN, InfoFile(), "Settings file name missing");
  1162. return false;
  1163. }
  1164. // - Qt environment
  1165. {
  1166. unsigned long qtv = Base_.QtVersionMajor;
  1167. if (cmSystemTools::StringToULong(InfoGet("AM_QT_VERSION_MAJOR").c_str(),
  1168. &qtv)) {
  1169. Base_.QtVersionMajor = static_cast<unsigned int>(qtv);
  1170. }
  1171. }
  1172. // - Moc
  1173. Moc_.Executable = InfoGet("AM_QT_MOC_EXECUTABLE");
  1174. Moc_.Enabled = !Moc().Executable.empty();
  1175. if (Moc().Enabled) {
  1176. for (std::string& sfl : InfoGetList("AM_MOC_SKIP")) {
  1177. Moc_.SkipList.insert(std::move(sfl));
  1178. }
  1179. Moc_.Definitions = InfoGetConfigList("AM_MOC_DEFINITIONS");
  1180. Moc_.IncludePaths = InfoGetConfigList("AM_MOC_INCLUDES");
  1181. Moc_.Options = InfoGetList("AM_MOC_OPTIONS");
  1182. Moc_.RelaxedMode = InfoGetBool("AM_MOC_RELAXED_MODE");
  1183. for (std::string const& item : InfoGetList("AM_MOC_MACRO_NAMES")) {
  1184. Moc_.MacroFilters.emplace_back(
  1185. item, ("[\n][ \t]*{?[ \t]*" + item).append("[^a-zA-Z0-9_]"));
  1186. }
  1187. {
  1188. auto pushFilter = [this](std::string const& key, std::string const& exp,
  1189. std::string& error) {
  1190. if (!key.empty()) {
  1191. if (!exp.empty()) {
  1192. Moc_.DependFilters.emplace_back();
  1193. KeyExpT& filter(Moc_.DependFilters.back());
  1194. if (filter.Exp.compile(exp)) {
  1195. filter.Key = key;
  1196. } else {
  1197. error = "Regular expression compiling failed";
  1198. }
  1199. } else {
  1200. error = "Regular expression is empty";
  1201. }
  1202. } else {
  1203. error = "Key is empty";
  1204. }
  1205. if (!error.empty()) {
  1206. error = ("AUTOMOC_DEPEND_FILTERS: " + error);
  1207. error += "\n";
  1208. error += " Key: ";
  1209. error += Quoted(key);
  1210. error += "\n";
  1211. error += " Exp: ";
  1212. error += Quoted(exp);
  1213. error += "\n";
  1214. }
  1215. };
  1216. std::string error;
  1217. // Insert default filter for Q_PLUGIN_METADATA
  1218. if (Base().QtVersionMajor != 4) {
  1219. pushFilter("Q_PLUGIN_METADATA",
  1220. "[\n][ \t]*Q_PLUGIN_METADATA[ \t]*\\("
  1221. "[^\\)]*FILE[ \t]*\"([^\"]+)\"",
  1222. error);
  1223. }
  1224. // Insert user defined dependency filters
  1225. {
  1226. std::vector<std::string> flts = InfoGetList("AM_MOC_DEPEND_FILTERS");
  1227. if ((flts.size() % 2) == 0) {
  1228. for (std::vector<std::string>::iterator itC = flts.begin(),
  1229. itE = flts.end();
  1230. itC != itE; itC += 2) {
  1231. pushFilter(*itC, *(itC + 1), error);
  1232. if (!error.empty()) {
  1233. break;
  1234. }
  1235. }
  1236. } else {
  1237. Log().ErrorFile(
  1238. GenT::MOC, InfoFile(),
  1239. "AUTOMOC_DEPEND_FILTERS list size is not a multiple of 2");
  1240. return false;
  1241. }
  1242. }
  1243. if (!error.empty()) {
  1244. Log().ErrorFile(GenT::MOC, InfoFile(), error);
  1245. return false;
  1246. }
  1247. }
  1248. Moc_.PredefsCmd = InfoGetList("AM_MOC_PREDEFS_CMD");
  1249. // Install moc predefs job
  1250. if (!Moc().PredefsCmd.empty()) {
  1251. JobQueues_.MocPredefs.emplace_back(cm::make_unique<JobMocPredefsT>());
  1252. }
  1253. }
  1254. // - Uic
  1255. Uic_.Executable = InfoGet("AM_QT_UIC_EXECUTABLE");
  1256. Uic_.Enabled = !Uic().Executable.empty();
  1257. if (Uic().Enabled) {
  1258. for (std::string& sfl : InfoGetList("AM_UIC_SKIP")) {
  1259. Uic_.SkipList.insert(std::move(sfl));
  1260. }
  1261. Uic_.SearchPaths = InfoGetList("AM_UIC_SEARCH_PATHS");
  1262. Uic_.TargetOptions = InfoGetConfigList("AM_UIC_TARGET_OPTIONS");
  1263. {
  1264. auto sources = InfoGetList("AM_UIC_OPTIONS_FILES");
  1265. auto options = InfoGetLists("AM_UIC_OPTIONS_OPTIONS");
  1266. // Compare list sizes
  1267. if (sources.size() != options.size()) {
  1268. std::ostringstream ost;
  1269. ost << "files/options lists sizes mismatch (" << sources.size() << "/"
  1270. << options.size() << ")";
  1271. Log().ErrorFile(GenT::UIC, InfoFile(), ost.str());
  1272. return false;
  1273. }
  1274. auto fitEnd = sources.cend();
  1275. auto fit = sources.begin();
  1276. auto oit = options.begin();
  1277. while (fit != fitEnd) {
  1278. Uic_.Options[*fit] = std::move(*oit);
  1279. ++fit;
  1280. ++oit;
  1281. }
  1282. }
  1283. }
  1284. // - Headers and sources
  1285. {
  1286. auto addHeader = [this](std::string&& hdr, bool moc, bool uic) {
  1287. this->JobQueues_.Headers.emplace_back(
  1288. cm::make_unique<JobParseT>(std::move(hdr), moc, uic, true));
  1289. };
  1290. auto addSource = [this](std::string&& src, bool moc, bool uic) {
  1291. this->JobQueues_.Sources.emplace_back(
  1292. cm::make_unique<JobParseT>(std::move(src), moc, uic, false));
  1293. };
  1294. // Add headers
  1295. for (std::string& hdr : InfoGetList("AM_HEADERS")) {
  1296. addHeader(std::move(hdr), true, true);
  1297. }
  1298. if (Moc().Enabled) {
  1299. for (std::string& hdr : InfoGetList("AM_MOC_HEADERS")) {
  1300. addHeader(std::move(hdr), true, false);
  1301. }
  1302. }
  1303. if (Uic().Enabled) {
  1304. for (std::string& hdr : InfoGetList("AM_UIC_HEADERS")) {
  1305. addHeader(std::move(hdr), false, true);
  1306. }
  1307. }
  1308. // Add sources
  1309. for (std::string& src : InfoGetList("AM_SOURCES")) {
  1310. addSource(std::move(src), true, true);
  1311. }
  1312. if (Moc().Enabled) {
  1313. for (std::string& src : InfoGetList("AM_MOC_SOURCES")) {
  1314. addSource(std::move(src), true, false);
  1315. }
  1316. }
  1317. if (Uic().Enabled) {
  1318. for (std::string& src : InfoGetList("AM_UIC_SOURCES")) {
  1319. addSource(std::move(src), false, true);
  1320. }
  1321. }
  1322. }
  1323. // Init derived information
  1324. // ------------------------
  1325. // Init file path checksum generator
  1326. FileSys().setupFilePathChecksum(
  1327. Base().CurrentSourceDir, Base().CurrentBinaryDir, Base().ProjectSourceDir,
  1328. Base().ProjectBinaryDir);
  1329. // Moc variables
  1330. if (Moc().Enabled) {
  1331. // Mocs compilation file
  1332. Moc_.CompFileAbs = Base().AbsoluteBuildPath("mocs_compilation.cpp");
  1333. // Moc predefs file
  1334. if (!Moc_.PredefsCmd.empty()) {
  1335. Moc_.PredefsFileRel = "moc_predefs";
  1336. if (Base_.MultiConfig) {
  1337. Moc_.PredefsFileRel += '_';
  1338. Moc_.PredefsFileRel += InfoConfig();
  1339. }
  1340. Moc_.PredefsFileRel += ".h";
  1341. Moc_.PredefsFileAbs = Base_.AbsoluteBuildPath(Moc().PredefsFileRel);
  1342. }
  1343. // Sort include directories on demand
  1344. if (Base().IncludeProjectDirsBefore) {
  1345. // Move strings to temporary list
  1346. std::list<std::string> includes;
  1347. includes.insert(includes.end(), Moc().IncludePaths.begin(),
  1348. Moc().IncludePaths.end());
  1349. Moc_.IncludePaths.clear();
  1350. Moc_.IncludePaths.reserve(includes.size());
  1351. // Append project directories only
  1352. {
  1353. std::array<std::string const*, 2> const movePaths = {
  1354. { &Base().ProjectBinaryDir, &Base().ProjectSourceDir }
  1355. };
  1356. for (std::string const* ppath : movePaths) {
  1357. std::list<std::string>::iterator it = includes.begin();
  1358. while (it != includes.end()) {
  1359. std::string const& path = *it;
  1360. if (cmSystemTools::StringStartsWith(path, ppath->c_str())) {
  1361. Moc_.IncludePaths.push_back(path);
  1362. it = includes.erase(it);
  1363. } else {
  1364. ++it;
  1365. }
  1366. }
  1367. }
  1368. }
  1369. // Append remaining directories
  1370. Moc_.IncludePaths.insert(Moc_.IncludePaths.end(), includes.begin(),
  1371. includes.end());
  1372. }
  1373. // Compose moc includes list
  1374. {
  1375. std::set<std::string> frameworkPaths;
  1376. for (std::string const& path : Moc().IncludePaths) {
  1377. Moc_.Includes.push_back("-I" + path);
  1378. // Extract framework path
  1379. if (cmHasLiteralSuffix(path, ".framework/Headers")) {
  1380. // Go up twice to get to the framework root
  1381. std::vector<std::string> pathComponents;
  1382. FileSys().SplitPath(path, pathComponents);
  1383. std::string frameworkPath = FileSys().JoinPath(
  1384. pathComponents.begin(), pathComponents.end() - 2);
  1385. frameworkPaths.insert(frameworkPath);
  1386. }
  1387. }
  1388. // Append framework includes
  1389. for (std::string const& path : frameworkPaths) {
  1390. Moc_.Includes.emplace_back("-F");
  1391. Moc_.Includes.push_back(path);
  1392. }
  1393. }
  1394. // Setup single list with all options
  1395. {
  1396. // Add includes
  1397. Moc_.AllOptions.insert(Moc_.AllOptions.end(), Moc().Includes.begin(),
  1398. Moc().Includes.end());
  1399. // Add definitions
  1400. for (std::string const& def : Moc().Definitions) {
  1401. Moc_.AllOptions.push_back("-D" + def);
  1402. }
  1403. // Add options
  1404. Moc_.AllOptions.insert(Moc_.AllOptions.end(), Moc().Options.begin(),
  1405. Moc().Options.end());
  1406. }
  1407. }
  1408. return true;
  1409. }
  1410. bool cmQtAutoGeneratorMocUic::Process()
  1411. {
  1412. // Run libuv event loop
  1413. UVRequest().send();
  1414. if (uv_run(UVLoop(), UV_RUN_DEFAULT) == 0) {
  1415. if (JobError_) {
  1416. return false;
  1417. }
  1418. } else {
  1419. return false;
  1420. }
  1421. return true;
  1422. }
  1423. void cmQtAutoGeneratorMocUic::UVPollStage(uv_async_t* handle)
  1424. {
  1425. reinterpret_cast<cmQtAutoGeneratorMocUic*>(handle->data)->PollStage();
  1426. }
  1427. void cmQtAutoGeneratorMocUic::PollStage()
  1428. {
  1429. switch (Stage_) {
  1430. case StageT::SETTINGS_READ:
  1431. SettingsFileRead();
  1432. SetStage(StageT::CREATE_DIRECTORIES);
  1433. break;
  1434. case StageT::CREATE_DIRECTORIES:
  1435. CreateDirectories();
  1436. SetStage(StageT::PARSE_SOURCES);
  1437. break;
  1438. case StageT::PARSE_SOURCES:
  1439. if (ThreadsStartJobs(JobQueues_.Sources)) {
  1440. SetStage(StageT::PARSE_HEADERS);
  1441. }
  1442. break;
  1443. case StageT::PARSE_HEADERS:
  1444. if (ThreadsStartJobs(JobQueues_.Headers)) {
  1445. SetStage(StageT::MOC_PREDEFS);
  1446. }
  1447. break;
  1448. case StageT::MOC_PREDEFS:
  1449. if (ThreadsStartJobs(JobQueues_.MocPredefs)) {
  1450. SetStage(StageT::MOC_PROCESS);
  1451. }
  1452. break;
  1453. case StageT::MOC_PROCESS:
  1454. if (ThreadsStartJobs(JobQueues_.Moc)) {
  1455. SetStage(StageT::MOCS_COMPILATION);
  1456. }
  1457. break;
  1458. case StageT::MOCS_COMPILATION:
  1459. if (ThreadsJobsDone()) {
  1460. MocGenerateCompilation();
  1461. SetStage(StageT::UIC_PROCESS);
  1462. }
  1463. break;
  1464. case StageT::UIC_PROCESS:
  1465. if (ThreadsStartJobs(JobQueues_.Uic)) {
  1466. SetStage(StageT::SETTINGS_WRITE);
  1467. }
  1468. break;
  1469. case StageT::SETTINGS_WRITE:
  1470. SettingsFileWrite();
  1471. SetStage(StageT::FINISH);
  1472. break;
  1473. case StageT::FINISH:
  1474. if (ThreadsJobsDone()) {
  1475. // Clear all libuv handles
  1476. ThreadsStop();
  1477. UVRequest().reset();
  1478. // Set highest END stage manually
  1479. Stage_ = StageT::END;
  1480. }
  1481. break;
  1482. case StageT::END:
  1483. break;
  1484. }
  1485. }
  1486. void cmQtAutoGeneratorMocUic::SetStage(StageT stage)
  1487. {
  1488. if (JobError_) {
  1489. stage = StageT::FINISH;
  1490. }
  1491. // Only allow to increase the stage
  1492. if (Stage_ < stage) {
  1493. Stage_ = stage;
  1494. UVRequest().send();
  1495. }
  1496. }
  1497. void cmQtAutoGeneratorMocUic::SettingsFileRead()
  1498. {
  1499. // Compose current settings strings
  1500. {
  1501. cmCryptoHash crypt(cmCryptoHash::AlgoSHA256);
  1502. std::string const sep(" ~~~ ");
  1503. if (Moc_.Enabled) {
  1504. std::string str;
  1505. str += Moc().Executable;
  1506. str += sep;
  1507. str += cmJoin(Moc().AllOptions, ";");
  1508. str += sep;
  1509. str += Base().IncludeProjectDirsBefore ? "TRUE" : "FALSE";
  1510. str += sep;
  1511. str += cmJoin(Moc().PredefsCmd, ";");
  1512. str += sep;
  1513. SettingsStringMoc_ = crypt.HashString(str);
  1514. }
  1515. if (Uic().Enabled) {
  1516. std::string str;
  1517. str += Uic().Executable;
  1518. str += sep;
  1519. str += cmJoin(Uic().TargetOptions, ";");
  1520. for (const auto& item : Uic().Options) {
  1521. str += sep;
  1522. str += item.first;
  1523. str += sep;
  1524. str += cmJoin(item.second, ";");
  1525. }
  1526. str += sep;
  1527. SettingsStringUic_ = crypt.HashString(str);
  1528. }
  1529. }
  1530. // Read old settings and compare
  1531. {
  1532. std::string content;
  1533. if (FileSys().FileRead(content, SettingsFile_)) {
  1534. if (Moc().Enabled) {
  1535. if (SettingsStringMoc_ != SettingsFind(content, "moc")) {
  1536. Moc_.SettingsChanged = true;
  1537. }
  1538. }
  1539. if (Uic().Enabled) {
  1540. if (SettingsStringUic_ != SettingsFind(content, "uic")) {
  1541. Uic_.SettingsChanged = true;
  1542. }
  1543. }
  1544. // In case any setting changed remove the old settings file.
  1545. // This triggers a full rebuild on the next run if the current
  1546. // build is aborted before writing the current settings in the end.
  1547. if (Moc().SettingsChanged || Uic().SettingsChanged) {
  1548. FileSys().FileRemove(SettingsFile_);
  1549. }
  1550. } else {
  1551. // Settings file read failed
  1552. if (Moc().Enabled) {
  1553. Moc_.SettingsChanged = true;
  1554. }
  1555. if (Uic().Enabled) {
  1556. Uic_.SettingsChanged = true;
  1557. }
  1558. }
  1559. }
  1560. }
  1561. void cmQtAutoGeneratorMocUic::SettingsFileWrite()
  1562. {
  1563. std::lock_guard<std::mutex> jobsLock(JobsMutex_);
  1564. // Only write if any setting changed
  1565. if (!JobError_ && (Moc().SettingsChanged || Uic().SettingsChanged)) {
  1566. if (Log().Verbose()) {
  1567. Log().Info(GenT::GEN, "Writing settings file " + Quoted(SettingsFile_));
  1568. }
  1569. // Compose settings file content
  1570. std::string content;
  1571. {
  1572. auto SettingAppend = [&content](const char* key,
  1573. std::string const& value) {
  1574. if (!value.empty()) {
  1575. content += key;
  1576. content += ':';
  1577. content += value;
  1578. content += '\n';
  1579. }
  1580. };
  1581. SettingAppend("moc", SettingsStringMoc_);
  1582. SettingAppend("uic", SettingsStringUic_);
  1583. }
  1584. // Write settings file
  1585. if (!FileSys().FileWrite(GenT::GEN, SettingsFile_, content)) {
  1586. Log().ErrorFile(GenT::GEN, SettingsFile_,
  1587. "Settings file writing failed");
  1588. // Remove old settings file to trigger a full rebuild on the next run
  1589. FileSys().FileRemove(SettingsFile_);
  1590. RegisterJobError();
  1591. }
  1592. }
  1593. }
  1594. void cmQtAutoGeneratorMocUic::CreateDirectories()
  1595. {
  1596. // Create AUTOGEN include directory
  1597. if (!FileSys().MakeDirectory(GenT::GEN, Base().AutogenIncludeDir)) {
  1598. RegisterJobError();
  1599. }
  1600. }
  1601. bool cmQtAutoGeneratorMocUic::ThreadsStartJobs(JobQueueT& queue)
  1602. {
  1603. bool done = false;
  1604. std::size_t queueSize = queue.size();
  1605. // Change the active queue
  1606. {
  1607. std::lock_guard<std::mutex> jobsLock(JobsMutex_);
  1608. // Check if there are still unfinished jobs from the previous queue
  1609. if (JobsRemain_ == 0) {
  1610. if (!JobThreadsAbort_) {
  1611. JobQueue_.swap(queue);
  1612. JobsRemain_ = queueSize;
  1613. } else {
  1614. // Abort requested
  1615. queue.clear();
  1616. queueSize = 0;
  1617. }
  1618. done = true;
  1619. }
  1620. }
  1621. if (done && (queueSize != 0)) {
  1622. // Start new threads on demand
  1623. if (Workers_.empty()) {
  1624. Workers_.resize(Base().NumThreads);
  1625. for (auto& item : Workers_) {
  1626. item = cm::make_unique<WorkerT>(this, UVLoop());
  1627. }
  1628. } else {
  1629. // Notify threads
  1630. if (queueSize == 1) {
  1631. JobsConditionRead_.notify_one();
  1632. } else {
  1633. JobsConditionRead_.notify_all();
  1634. }
  1635. }
  1636. }
  1637. return done;
  1638. }
  1639. void cmQtAutoGeneratorMocUic::ThreadsStop()
  1640. {
  1641. if (!Workers_.empty()) {
  1642. // Clear all jobs
  1643. {
  1644. std::lock_guard<std::mutex> jobsLock(JobsMutex_);
  1645. JobThreadsAbort_ = true;
  1646. JobsRemain_ -= JobQueue_.size();
  1647. JobQueue_.clear();
  1648. JobQueues_.Sources.clear();
  1649. JobQueues_.Headers.clear();
  1650. JobQueues_.MocPredefs.clear();
  1651. JobQueues_.Moc.clear();
  1652. JobQueues_.Uic.clear();
  1653. }
  1654. // Wake threads
  1655. JobsConditionRead_.notify_all();
  1656. // Join and clear threads
  1657. Workers_.clear();
  1658. }
  1659. }
  1660. bool cmQtAutoGeneratorMocUic::ThreadsJobsDone()
  1661. {
  1662. std::lock_guard<std::mutex> jobsLock(JobsMutex_);
  1663. return (JobsRemain_ == 0);
  1664. }
  1665. void cmQtAutoGeneratorMocUic::WorkerSwapJob(JobHandleT& jobHandle)
  1666. {
  1667. bool const jobProcessed(jobHandle);
  1668. if (jobProcessed) {
  1669. jobHandle.reset();
  1670. }
  1671. {
  1672. std::unique_lock<std::mutex> jobsLock(JobsMutex_);
  1673. // Reduce the remaining job count and notify the libuv loop
  1674. // when all jobs are done
  1675. if (jobProcessed) {
  1676. --JobsRemain_;
  1677. if (JobsRemain_ == 0) {
  1678. UVRequest().send();
  1679. }
  1680. }
  1681. // Wait for new jobs
  1682. while (!JobThreadsAbort_ && JobQueue_.empty()) {
  1683. JobsConditionRead_.wait(jobsLock);
  1684. }
  1685. // Try to pick up a new job handle
  1686. if (!JobThreadsAbort_ && !JobQueue_.empty()) {
  1687. jobHandle = std::move(JobQueue_.front());
  1688. JobQueue_.pop_front();
  1689. }
  1690. }
  1691. }
  1692. void cmQtAutoGeneratorMocUic::ParallelRegisterJobError()
  1693. {
  1694. std::lock_guard<std::mutex> jobsLock(JobsMutex_);
  1695. RegisterJobError();
  1696. }
  1697. // Private method that requires cmQtAutoGeneratorMocUic::JobsMutex_ to be
  1698. // locked
  1699. void cmQtAutoGeneratorMocUic::RegisterJobError()
  1700. {
  1701. JobError_ = true;
  1702. if (!JobThreadsAbort_) {
  1703. JobThreadsAbort_ = true;
  1704. // Clear remaining jobs
  1705. if (JobsRemain_ != 0) {
  1706. JobsRemain_ -= JobQueue_.size();
  1707. JobQueue_.clear();
  1708. }
  1709. }
  1710. }
  1711. bool cmQtAutoGeneratorMocUic::ParallelJobPushMoc(JobHandleT& jobHandle)
  1712. {
  1713. std::lock_guard<std::mutex> jobsLock(JobsMutex_);
  1714. if (!JobThreadsAbort_) {
  1715. bool pushJobHandle = true;
  1716. // Do additional tests if this is an included moc job
  1717. const JobMocT& mocJob(static_cast<JobMocT&>(*jobHandle));
  1718. if (!mocJob.IncludeString.empty()) {
  1719. // Register included moc file and look for collisions
  1720. MocIncludedFiles_.emplace(mocJob.SourceFile);
  1721. if (!MocIncludedStrings_.emplace(mocJob.IncludeString).second) {
  1722. // Another source file includes the same moc file!
  1723. for (const JobHandleT& otherHandle : JobQueues_.Moc) {
  1724. const JobMocT& otherJob(static_cast<JobMocT&>(*otherHandle));
  1725. if (otherJob.IncludeString == mocJob.IncludeString) {
  1726. // Check if the same moc file would be generated from different
  1727. // source files which is an error.
  1728. if (otherJob.SourceFile != mocJob.SourceFile) {
  1729. // Include string collision
  1730. std::string error = "The two source files\n ";
  1731. error += Quoted(mocJob.IncluderFile);
  1732. error += " and\n ";
  1733. error += Quoted(otherJob.IncluderFile);
  1734. error += "\ncontain the same moc include string ";
  1735. error += Quoted(mocJob.IncludeString);
  1736. error += "\nbut the moc file would be generated from different "
  1737. "source files\n ";
  1738. error += Quoted(mocJob.SourceFile);
  1739. error += " and\n ";
  1740. error += Quoted(otherJob.SourceFile);
  1741. error += ".\nConsider to\n"
  1742. "- not include the \"moc_<NAME>.cpp\" file\n"
  1743. "- add a directory prefix to a \"<NAME>.moc\" include "
  1744. "(e.g \"sub/<NAME>.moc\")\n"
  1745. "- rename the source file(s)\n";
  1746. Log().Error(GenT::MOC, error);
  1747. RegisterJobError();
  1748. }
  1749. // Do not push this job in since the included moc file already
  1750. // gets generated by an other job.
  1751. pushJobHandle = false;
  1752. break;
  1753. }
  1754. }
  1755. }
  1756. }
  1757. // Push job on demand
  1758. if (pushJobHandle) {
  1759. JobQueues_.Moc.emplace_back(std::move(jobHandle));
  1760. }
  1761. }
  1762. return !JobError_;
  1763. }
  1764. bool cmQtAutoGeneratorMocUic::ParallelJobPushUic(JobHandleT& jobHandle)
  1765. {
  1766. std::lock_guard<std::mutex> jobsLock(JobsMutex_);
  1767. if (!JobThreadsAbort_) {
  1768. bool pushJobHandle = true;
  1769. // Look for include collisions.
  1770. const JobUicT& uicJob(static_cast<JobUicT&>(*jobHandle));
  1771. for (const JobHandleT& otherHandle : JobQueues_.Uic) {
  1772. const JobUicT& otherJob(static_cast<JobUicT&>(*otherHandle));
  1773. if (otherJob.IncludeString == uicJob.IncludeString) {
  1774. // Check if the same uic file would be generated from different
  1775. // source files which would be an error.
  1776. if (otherJob.SourceFile != uicJob.SourceFile) {
  1777. // Include string collision
  1778. std::string error = "The two source files\n ";
  1779. error += Quoted(uicJob.IncluderFile);
  1780. error += " and\n ";
  1781. error += Quoted(otherJob.IncluderFile);
  1782. error += "\ncontain the same uic include string ";
  1783. error += Quoted(uicJob.IncludeString);
  1784. error += "\nbut the uic file would be generated from different "
  1785. "source files\n ";
  1786. error += Quoted(uicJob.SourceFile);
  1787. error += " and\n ";
  1788. error += Quoted(otherJob.SourceFile);
  1789. error +=
  1790. ".\nConsider to\n"
  1791. "- add a directory prefix to a \"ui_<NAME>.h\" include "
  1792. "(e.g \"sub/ui_<NAME>.h\")\n"
  1793. "- rename the <NAME>.ui file(s) and adjust the \"ui_<NAME>.h\" "
  1794. "include(s)\n";
  1795. Log().Error(GenT::UIC, error);
  1796. RegisterJobError();
  1797. }
  1798. // Do not push this job in since the uic file already
  1799. // gets generated by an other job.
  1800. pushJobHandle = false;
  1801. break;
  1802. }
  1803. }
  1804. if (pushJobHandle) {
  1805. JobQueues_.Uic.emplace_back(std::move(jobHandle));
  1806. }
  1807. }
  1808. return !JobError_;
  1809. }
  1810. bool cmQtAutoGeneratorMocUic::ParallelMocIncluded(
  1811. std::string const& sourceFile)
  1812. {
  1813. std::lock_guard<std::mutex> mocLock(JobsMutex_);
  1814. return (MocIncludedFiles_.find(sourceFile) != MocIncludedFiles_.end());
  1815. }
  1816. std::string cmQtAutoGeneratorMocUic::ParallelMocAutoRegister(
  1817. std::string const& baseName)
  1818. {
  1819. std::string res;
  1820. {
  1821. std::lock_guard<std::mutex> mocLock(JobsMutex_);
  1822. res = baseName;
  1823. res += ".cpp";
  1824. if (MocAutoFiles_.find(res) == MocAutoFiles_.end()) {
  1825. MocAutoFiles_.emplace(res);
  1826. } else {
  1827. // Append number suffix to the file name
  1828. for (unsigned int ii = 2; ii != 1024; ++ii) {
  1829. res = baseName;
  1830. res += '_';
  1831. res += std::to_string(ii);
  1832. res += ".cpp";
  1833. if (MocAutoFiles_.find(res) == MocAutoFiles_.end()) {
  1834. MocAutoFiles_.emplace(res);
  1835. break;
  1836. }
  1837. }
  1838. }
  1839. }
  1840. return res;
  1841. }
  1842. void cmQtAutoGeneratorMocUic::ParallelMocAutoUpdated()
  1843. {
  1844. std::lock_guard<std::mutex> mocLock(JobsMutex_);
  1845. MocAutoFileUpdated_ = true;
  1846. }
  1847. void cmQtAutoGeneratorMocUic::MocGenerateCompilation()
  1848. {
  1849. std::lock_guard<std::mutex> mocLock(JobsMutex_);
  1850. if (!JobError_ && Moc().Enabled) {
  1851. // Write mocs compilation build file
  1852. {
  1853. // Compose mocs compilation file content
  1854. std::string content =
  1855. "// This file is autogenerated. Changes will be overwritten.\n";
  1856. if (MocAutoFiles_.empty()) {
  1857. // Placeholder content
  1858. content += "// No files found that require moc or the moc files are "
  1859. "included\n";
  1860. content += "enum some_compilers { need_more_than_nothing };\n";
  1861. } else {
  1862. // Valid content
  1863. char const sbeg = Base().MultiConfig ? '<' : '"';
  1864. char const send = Base().MultiConfig ? '>' : '"';
  1865. for (std::string const& mocfile : MocAutoFiles_) {
  1866. content += "#include ";
  1867. content += sbeg;
  1868. content += mocfile;
  1869. content += send;
  1870. content += '\n';
  1871. }
  1872. }
  1873. std::string const& compAbs = Moc().CompFileAbs;
  1874. if (FileSys().FileDiffers(compAbs, content)) {
  1875. // Actually write mocs compilation file
  1876. if (Log().Verbose()) {
  1877. Log().Info(GenT::MOC, "Generating MOC compilation " + compAbs);
  1878. }
  1879. if (!FileSys().FileWrite(GenT::MOC, compAbs, content)) {
  1880. Log().ErrorFile(GenT::MOC, compAbs,
  1881. "mocs compilation file writing failed");
  1882. RegisterJobError();
  1883. return;
  1884. }
  1885. } else if (MocAutoFileUpdated_) {
  1886. // Only touch mocs compilation file
  1887. if (Log().Verbose()) {
  1888. Log().Info(GenT::MOC, "Touching mocs compilation " + compAbs);
  1889. }
  1890. FileSys().Touch(compAbs);
  1891. }
  1892. }
  1893. // Write mocs compilation wrapper file
  1894. if (Base().MultiConfig) {
  1895. }
  1896. }
  1897. }