cmQtAutoMocUic.cxx 66 KB

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