qt.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. # Copyright 2015 The Meson development team
  2. # Licensed under the Apache License, Version 2.0 (the "License");
  3. # you may not use this file except in compliance with the License.
  4. # You may obtain a copy of the License at
  5. # http://www.apache.org/licenses/LICENSE-2.0
  6. # Unless required by applicable law or agreed to in writing, software
  7. # distributed under the License is distributed on an "AS IS" BASIS,
  8. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. # See the License for the specific language governing permissions and
  10. # limitations under the License.
  11. import os
  12. from .. import mlog
  13. from .. import build
  14. from ..mesonlib import MesonException, Popen_safe, extract_as_list, File
  15. from ..dependencies import Qt4Dependency, Qt5Dependency
  16. import xml.etree.ElementTree as ET
  17. from . import ModuleReturnValue, get_include_args
  18. from ..interpreterbase import permittedKwargs, FeatureNewKwargs
  19. _QT_DEPS_LUT = {
  20. 4: Qt4Dependency,
  21. 5: Qt5Dependency
  22. }
  23. class QtBaseModule:
  24. tools_detected = False
  25. def __init__(self, qt_version=5):
  26. self.qt_version = qt_version
  27. def _detect_tools(self, env, method):
  28. if self.tools_detected:
  29. return
  30. mlog.log('Detecting Qt{version} tools'.format(version=self.qt_version))
  31. # FIXME: We currently require QtX to exist while importing the module.
  32. # We should make it gracefully degrade and not create any targets if
  33. # the import is marked as 'optional' (not implemented yet)
  34. kwargs = {'required': 'true', 'modules': 'Core', 'silent': 'true', 'method': method}
  35. qt = _QT_DEPS_LUT[self.qt_version](env, kwargs)
  36. # Get all tools and then make sure that they are the right version
  37. self.moc, self.uic, self.rcc, self.lrelease = qt.compilers_detect()
  38. # Moc, uic and rcc write their version strings to stderr.
  39. # Moc and rcc return a non-zero result when doing so.
  40. # What kind of an idiot thought that was a good idea?
  41. for compiler, compiler_name in ((self.moc, "Moc"), (self.uic, "Uic"), (self.rcc, "Rcc"), (self.lrelease, "lrelease")):
  42. if compiler.found():
  43. # Workaround since there is no easy way to know which tool/version support which flag
  44. for flag in ['-v', '-version']:
  45. p, stdout, stderr = Popen_safe(compiler.get_command() + [flag])[0:3]
  46. if p.returncode == 0:
  47. break
  48. stdout = stdout.strip()
  49. stderr = stderr.strip()
  50. if 'Qt {}'.format(self.qt_version) in stderr:
  51. compiler_ver = stderr
  52. elif 'version {}.'.format(self.qt_version) in stderr:
  53. compiler_ver = stderr
  54. elif ' {}.'.format(self.qt_version) in stdout:
  55. compiler_ver = stdout
  56. else:
  57. raise MesonException('{name} preprocessor is not for Qt {version}. Output:\n{stdo}\n{stderr}'.format(
  58. name=compiler_name, version=self.qt_version, stdo=stdout, stderr=stderr))
  59. mlog.log(' {}:'.format(compiler_name.lower()), mlog.green('YES'), '({path}, {version})'.format(
  60. path=compiler.get_path(), version=compiler_ver.split()[-1]))
  61. else:
  62. mlog.log(' {}:'.format(compiler_name.lower()), mlog.red('NO'))
  63. self.tools_detected = True
  64. def parse_qrc(self, state, rcc_file):
  65. if type(rcc_file) is str:
  66. abspath = os.path.join(state.environment.source_dir, state.subdir, rcc_file)
  67. rcc_dirname = os.path.dirname(abspath)
  68. elif type(rcc_file) is File:
  69. abspath = rcc_file.absolute_path(state.environment.source_dir, state.environment.build_dir)
  70. rcc_dirname = os.path.dirname(abspath)
  71. try:
  72. tree = ET.parse(abspath)
  73. root = tree.getroot()
  74. result = []
  75. for child in root[0]:
  76. if child.tag != 'file':
  77. mlog.warning("malformed rcc file: ", os.path.join(state.subdir, rcc_file))
  78. break
  79. else:
  80. resource_path = child.text
  81. # We need to guess if the pointed resource is:
  82. # a) in build directory -> implies a generated file
  83. # b) in source directory
  84. # c) somewhere else external dependency file to bundle
  85. #
  86. # Also from qrc documentation: relative path are always from qrc file
  87. # So relative path must always be computed from qrc file !
  88. if os.path.isabs(resource_path):
  89. # a)
  90. if resource_path.startswith(os.path.abspath(state.environment.build_dir)):
  91. resource_relpath = os.path.relpath(resource_path, state.environment.build_dir)
  92. result.append(File(is_built=True, subdir='', fname=resource_relpath))
  93. # either b) or c)
  94. else:
  95. result.append(File(is_built=False, subdir=state.subdir, fname=resource_path))
  96. else:
  97. path_from_rcc = os.path.normpath(os.path.join(rcc_dirname, resource_path))
  98. # a)
  99. if path_from_rcc.startswith(state.environment.build_dir):
  100. result.append(File(is_built=True, subdir=state.subdir, fname=resource_path))
  101. # b)
  102. else:
  103. result.append(File(is_built=False, subdir=state.subdir, fname=path_from_rcc))
  104. return result
  105. except Exception:
  106. return []
  107. @FeatureNewKwargs('qt.preprocess', '0.44.0', ['moc_extra_arguments'])
  108. @permittedKwargs({'moc_headers', 'moc_sources', 'moc_extra_arguments', 'include_directories', 'ui_files', 'qresources', 'method'})
  109. def preprocess(self, state, args, kwargs):
  110. rcc_files, ui_files, moc_headers, moc_sources, moc_extra_arguments, sources, include_directories \
  111. = extract_as_list(kwargs, 'qresources', 'ui_files', 'moc_headers', 'moc_sources', 'moc_extra_arguments', 'sources', 'include_directories', pop = True)
  112. sources += args[1:]
  113. method = kwargs.get('method', 'auto')
  114. self._detect_tools(state.environment, method)
  115. err_msg = "{0} sources specified and couldn't find {1}, " \
  116. "please check your qt{2} installation"
  117. if len(moc_headers) + len(moc_sources) > 0 and not self.moc.found():
  118. raise MesonException(err_msg.format('MOC', 'moc-qt{}'.format(self.qt_version), self.qt_version))
  119. if len(rcc_files) > 0:
  120. if not self.rcc.found():
  121. raise MesonException(err_msg.format('RCC', 'rcc-qt{}'.format(self.qt_version), self.qt_version))
  122. # custom output name set? -> one output file, multiple otherwise
  123. if len(args) > 0:
  124. qrc_deps = []
  125. for i in rcc_files:
  126. qrc_deps += self.parse_qrc(state, i)
  127. name = args[0]
  128. rcc_kwargs = {'input': rcc_files,
  129. 'output': name + '.cpp',
  130. 'command': [self.rcc, '-name', name, '-o', '@OUTPUT@', '@INPUT@'],
  131. 'depend_files': qrc_deps}
  132. res_target = build.CustomTarget(name, state.subdir, state.subproject, rcc_kwargs)
  133. sources.append(res_target)
  134. else:
  135. for rcc_file in rcc_files:
  136. qrc_deps = self.parse_qrc(state, rcc_file)
  137. if type(rcc_file) is str:
  138. basename = os.path.basename(rcc_file)
  139. elif type(rcc_file) is File:
  140. basename = os.path.basename(rcc_file.fname)
  141. name = 'qt' + str(self.qt_version) + '-' + basename.replace('.', '_')
  142. rcc_kwargs = {'input': rcc_file,
  143. 'output': name + '.cpp',
  144. 'command': [self.rcc, '-name', '@BASENAME@', '-o', '@OUTPUT@', '@INPUT@'],
  145. 'depend_files': qrc_deps}
  146. res_target = build.CustomTarget(name, state.subdir, state.subproject, rcc_kwargs)
  147. sources.append(res_target)
  148. if len(ui_files) > 0:
  149. if not self.uic.found():
  150. raise MesonException(err_msg.format('UIC', 'uic-qt' + self.qt_version))
  151. ui_kwargs = {'output': 'ui_@BASENAME@.h',
  152. 'arguments': ['-o', '@OUTPUT@', '@INPUT@']}
  153. ui_gen = build.Generator([self.uic], ui_kwargs)
  154. ui_output = ui_gen.process_files('Qt{} ui'.format(self.qt_version), ui_files, state)
  155. sources.append(ui_output)
  156. inc = get_include_args(include_dirs=include_directories)
  157. if len(moc_headers) > 0:
  158. arguments = moc_extra_arguments + inc + ['@INPUT@', '-o', '@OUTPUT@']
  159. moc_kwargs = {'output': 'moc_@BASENAME@.cpp',
  160. 'arguments': arguments}
  161. moc_gen = build.Generator([self.moc], moc_kwargs)
  162. moc_output = moc_gen.process_files('Qt{} moc header'.format(self.qt_version), moc_headers, state)
  163. sources.append(moc_output)
  164. if len(moc_sources) > 0:
  165. arguments = moc_extra_arguments + inc + ['@INPUT@', '-o', '@OUTPUT@']
  166. moc_kwargs = {'output': '@BASENAME@.moc',
  167. 'arguments': arguments}
  168. moc_gen = build.Generator([self.moc], moc_kwargs)
  169. moc_output = moc_gen.process_files('Qt{} moc source'.format(self.qt_version), moc_sources, state)
  170. sources.append(moc_output)
  171. return ModuleReturnValue(sources, sources)
  172. @FeatureNewKwargs('build target', '0.40.0', ['build_by_default'])
  173. @permittedKwargs({'ts_files', 'install', 'install_dir', 'build_by_default', 'method'})
  174. def compile_translations(self, state, args, kwargs):
  175. ts_files, install_dir = extract_as_list(kwargs, 'ts_files', 'install_dir', pop=True)
  176. self._detect_tools(state.environment, kwargs.get('method', 'auto'))
  177. translations = []
  178. for ts in ts_files:
  179. cmd = [self.lrelease, '@INPUT@', '-qm', '@OUTPUT@']
  180. lrelease_kwargs = {'output': '@BASENAME@.qm',
  181. 'input': ts,
  182. 'install': kwargs.get('install', False),
  183. 'build_by_default': kwargs.get('build_by_default', False),
  184. 'command': cmd}
  185. if install_dir is not None:
  186. lrelease_kwargs['install_dir'] = install_dir
  187. lrelease_target = build.CustomTarget('qt{}-compile-{}'.format(self.qt_version, ts), state.subdir, state.subproject, lrelease_kwargs)
  188. translations.append(lrelease_target)
  189. return ModuleReturnValue(translations, translations)