cmQtAutoGeneratorMocUic.cxx 64 KB

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