qt.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  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, unholder
  15. from ..dependencies import Dependency, Qt4Dependency, Qt5Dependency
  16. import xml.etree.ElementTree as ET
  17. from . import ModuleReturnValue, get_include_args, ExtensionModule
  18. from ..interpreterbase import noPosargs, permittedKwargs, FeatureNew, FeatureNewKwargs
  19. from ..interpreter import extract_required_kwarg
  20. _QT_DEPS_LUT = {
  21. 4: Qt4Dependency,
  22. 5: Qt5Dependency
  23. }
  24. class QtBaseModule(ExtensionModule):
  25. tools_detected = False
  26. def __init__(self, interpreter, qt_version=5):
  27. ExtensionModule.__init__(self, interpreter)
  28. self.snippets.add('has_tools')
  29. self.qt_version = qt_version
  30. def _detect_tools(self, env, method):
  31. if self.tools_detected:
  32. return
  33. mlog.log('Detecting Qt{version} tools'.format(version=self.qt_version))
  34. # FIXME: We currently require QtX to exist while importing the module.
  35. # We should make it gracefully degrade and not create any targets if
  36. # the import is marked as 'optional' (not implemented yet)
  37. kwargs = {'required': 'true', 'modules': 'Core', 'silent': 'true', 'method': method}
  38. qt = _QT_DEPS_LUT[self.qt_version](env, kwargs)
  39. # Get all tools and then make sure that they are the right version
  40. self.moc, self.uic, self.rcc, self.lrelease = qt.compilers_detect(self.interpreter)
  41. # Moc, uic and rcc write their version strings to stderr.
  42. # Moc and rcc return a non-zero result when doing so.
  43. # What kind of an idiot thought that was a good idea?
  44. for compiler, compiler_name in ((self.moc, "Moc"), (self.uic, "Uic"), (self.rcc, "Rcc"), (self.lrelease, "lrelease")):
  45. if compiler.found():
  46. # Workaround since there is no easy way to know which tool/version support which flag
  47. for flag in ['-v', '-version']:
  48. p, stdout, stderr = Popen_safe(compiler.get_command() + [flag])[0:3]
  49. if p.returncode == 0:
  50. break
  51. stdout = stdout.strip()
  52. stderr = stderr.strip()
  53. if 'Qt {}'.format(self.qt_version) in stderr:
  54. compiler_ver = stderr
  55. elif 'version {}.'.format(self.qt_version) in stderr:
  56. compiler_ver = stderr
  57. elif ' {}.'.format(self.qt_version) in stdout:
  58. compiler_ver = stdout
  59. else:
  60. raise MesonException('{name} preprocessor is not for Qt {version}. Output:\n{stdo}\n{stderr}'.format(
  61. name=compiler_name, version=self.qt_version, stdo=stdout, stderr=stderr))
  62. mlog.log(' {}:'.format(compiler_name.lower()), mlog.green('YES'), '({path}, {version})'.format(
  63. path=compiler.get_path(), version=compiler_ver.split()[-1]))
  64. else:
  65. mlog.log(' {}:'.format(compiler_name.lower()), mlog.red('NO'))
  66. self.tools_detected = True
  67. def parse_qrc(self, state, rcc_file):
  68. if type(rcc_file) is str:
  69. abspath = os.path.join(state.environment.source_dir, state.subdir, rcc_file)
  70. rcc_dirname = os.path.dirname(abspath)
  71. elif type(rcc_file) is File:
  72. abspath = rcc_file.absolute_path(state.environment.source_dir, state.environment.build_dir)
  73. rcc_dirname = os.path.dirname(abspath)
  74. try:
  75. tree = ET.parse(abspath)
  76. root = tree.getroot()
  77. result = []
  78. for child in root[0]:
  79. if child.tag != 'file':
  80. mlog.warning("malformed rcc file: ", os.path.join(state.subdir, rcc_file))
  81. break
  82. else:
  83. resource_path = child.text
  84. # We need to guess if the pointed resource is:
  85. # a) in build directory -> implies a generated file
  86. # b) in source directory
  87. # c) somewhere else external dependency file to bundle
  88. #
  89. # Also from qrc documentation: relative path are always from qrc file
  90. # So relative path must always be computed from qrc file !
  91. if os.path.isabs(resource_path):
  92. # a)
  93. if resource_path.startswith(os.path.abspath(state.environment.build_dir)):
  94. resource_relpath = os.path.relpath(resource_path, state.environment.build_dir)
  95. result.append(File(is_built=True, subdir='', fname=resource_relpath))
  96. # either b) or c)
  97. else:
  98. result.append(File(is_built=False, subdir=state.subdir, fname=resource_path))
  99. else:
  100. path_from_rcc = os.path.normpath(os.path.join(rcc_dirname, resource_path))
  101. # a)
  102. if path_from_rcc.startswith(state.environment.build_dir):
  103. result.append(File(is_built=True, subdir=state.subdir, fname=resource_path))
  104. # b)
  105. else:
  106. result.append(File(is_built=False, subdir=state.subdir, fname=path_from_rcc))
  107. return result
  108. except Exception:
  109. return []
  110. @noPosargs
  111. @permittedKwargs({'method', 'required'})
  112. @FeatureNew('qt.has_tools', '0.54.0')
  113. def has_tools(self, interpreter, state, args, kwargs):
  114. method = kwargs.get('method', 'auto')
  115. disabled, required, feature = extract_required_kwarg(kwargs, state.subproject, default=False)
  116. if disabled:
  117. mlog.log('qt.has_tools skipped: feature', mlog.bold(feature), 'disabled')
  118. return False
  119. self._detect_tools(state.environment, method)
  120. for tool in (self.moc, self.uic, self.rcc, self.lrelease):
  121. if not tool.found():
  122. if required:
  123. raise MesonException('Qt tools not found')
  124. return False
  125. return True
  126. @FeatureNewKwargs('qt.preprocess', '0.49.0', ['uic_extra_arguments'])
  127. @FeatureNewKwargs('qt.preprocess', '0.44.0', ['moc_extra_arguments'])
  128. @FeatureNewKwargs('qt.preprocess', '0.49.0', ['rcc_extra_arguments'])
  129. @permittedKwargs({'moc_headers', 'moc_sources', 'uic_extra_arguments', 'moc_extra_arguments', 'rcc_extra_arguments', 'include_directories', 'dependencies', 'ui_files', 'qresources', 'method'})
  130. def preprocess(self, state, args, kwargs):
  131. rcc_files, ui_files, moc_headers, moc_sources, uic_extra_arguments, moc_extra_arguments, rcc_extra_arguments, sources, include_directories, dependencies \
  132. = [extract_as_list(kwargs, c, pop=True) for c in ['qresources', 'ui_files', 'moc_headers', 'moc_sources', 'uic_extra_arguments', 'moc_extra_arguments', 'rcc_extra_arguments', 'sources', 'include_directories', 'dependencies']]
  133. sources += args[1:]
  134. method = kwargs.get('method', 'auto')
  135. self._detect_tools(state.environment, method)
  136. err_msg = "{0} sources specified and couldn't find {1}, " \
  137. "please check your qt{2} installation"
  138. if (moc_headers or moc_sources) and not self.moc.found():
  139. raise MesonException(err_msg.format('MOC', 'moc-qt{}'.format(self.qt_version), self.qt_version))
  140. if rcc_files:
  141. if not self.rcc.found():
  142. raise MesonException(err_msg.format('RCC', 'rcc-qt{}'.format(self.qt_version), self.qt_version))
  143. # custom output name set? -> one output file, multiple otherwise
  144. if args:
  145. qrc_deps = []
  146. for i in rcc_files:
  147. qrc_deps += self.parse_qrc(state, i)
  148. name = args[0]
  149. rcc_kwargs = {'input': rcc_files,
  150. 'output': name + '.cpp',
  151. 'command': [self.rcc, '-name', name, '-o', '@OUTPUT@', rcc_extra_arguments, '@INPUT@'],
  152. 'depend_files': qrc_deps}
  153. res_target = build.CustomTarget(name, state.subdir, state.subproject, rcc_kwargs)
  154. sources.append(res_target)
  155. else:
  156. for rcc_file in rcc_files:
  157. qrc_deps = self.parse_qrc(state, rcc_file)
  158. if type(rcc_file) is str:
  159. basename = os.path.basename(rcc_file)
  160. elif type(rcc_file) is File:
  161. basename = os.path.basename(rcc_file.fname)
  162. name = 'qt' + str(self.qt_version) + '-' + basename.replace('.', '_')
  163. rcc_kwargs = {'input': rcc_file,
  164. 'output': name + '.cpp',
  165. 'command': [self.rcc, '-name', '@BASENAME@', '-o', '@OUTPUT@', rcc_extra_arguments, '@INPUT@'],
  166. 'depend_files': qrc_deps}
  167. res_target = build.CustomTarget(name, state.subdir, state.subproject, rcc_kwargs)
  168. sources.append(res_target)
  169. if ui_files:
  170. if not self.uic.found():
  171. raise MesonException(err_msg.format('UIC', 'uic-qt{}'.format(self.qt_version), self.qt_version))
  172. arguments = uic_extra_arguments + ['-o', '@OUTPUT@', '@INPUT@']
  173. ui_kwargs = {'output': 'ui_@BASENAME@.h',
  174. 'arguments': arguments}
  175. ui_gen = build.Generator([self.uic], ui_kwargs)
  176. ui_output = ui_gen.process_files('Qt{} ui'.format(self.qt_version), ui_files, state)
  177. sources.append(ui_output)
  178. inc = get_include_args(include_dirs=include_directories)
  179. compile_args = []
  180. for dep in unholder(dependencies):
  181. if isinstance(dep, Dependency):
  182. for arg in dep.get_compile_args():
  183. if arg.startswith('-I') or arg.startswith('-D'):
  184. compile_args.append(arg)
  185. else:
  186. raise MesonException('Argument is of an unacceptable type {!r}.\nMust be '
  187. 'either an external dependency (returned by find_library() or '
  188. 'dependency()) or an internal dependency (returned by '
  189. 'declare_dependency()).'.format(type(dep).__name__))
  190. if moc_headers:
  191. arguments = moc_extra_arguments + inc + compile_args + ['@INPUT@', '-o', '@OUTPUT@']
  192. moc_kwargs = {'output': 'moc_@BASENAME@.cpp',
  193. 'arguments': arguments}
  194. moc_gen = build.Generator([self.moc], moc_kwargs)
  195. moc_output = moc_gen.process_files('Qt{} moc header'.format(self.qt_version), moc_headers, state)
  196. sources.append(moc_output)
  197. if moc_sources:
  198. arguments = moc_extra_arguments + inc + compile_args + ['@INPUT@', '-o', '@OUTPUT@']
  199. moc_kwargs = {'output': '@BASENAME@.moc',
  200. 'arguments': arguments}
  201. moc_gen = build.Generator([self.moc], moc_kwargs)
  202. moc_output = moc_gen.process_files('Qt{} moc source'.format(self.qt_version), moc_sources, state)
  203. sources.append(moc_output)
  204. return ModuleReturnValue(sources, sources)
  205. @FeatureNew('qt.compile_translations', '0.44.0')
  206. @permittedKwargs({'ts_files', 'install', 'install_dir', 'build_by_default', 'method'})
  207. def compile_translations(self, state, args, kwargs):
  208. ts_files, install_dir = [extract_as_list(kwargs, c, pop=True) for c in ['ts_files', 'install_dir']]
  209. self._detect_tools(state.environment, kwargs.get('method', 'auto'))
  210. translations = []
  211. for ts in ts_files:
  212. if not self.lrelease.found():
  213. raise MesonException('qt.compile_translations: ' +
  214. self.lrelease.name + ' not found')
  215. cmd = [self.lrelease, '@INPUT@', '-qm', '@OUTPUT@']
  216. lrelease_kwargs = {'output': '@BASENAME@.qm',
  217. 'input': ts,
  218. 'install': kwargs.get('install', False),
  219. 'build_by_default': kwargs.get('build_by_default', False),
  220. 'command': cmd}
  221. if install_dir is not None:
  222. lrelease_kwargs['install_dir'] = install_dir
  223. lrelease_target = build.CustomTarget('qt{}-compile-{}'.format(self.qt_version, ts), state.subdir, state.subproject, lrelease_kwargs)
  224. translations.append(lrelease_target)
  225. return ModuleReturnValue(translations, translations)