Debian Codegraph @

mesonbuild/modules/_qt.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2015 The Meson development team
3 # Copyright © 2021-2025 Intel Corporation
4
5 from __future__ import annotations
6
7 import os
8 import shutil
9 import typing as T
10 import xml.etree.ElementTree as ET
11 import re
12
13 from . import ModuleReturnValue, ExtensionModule
14 from .. import build
15 from .. import mlog
16 from ..dependencies import DependencyMethods, find_external_dependency, Dependency, ExternalLibrary, InternalDependency
17 from ..mesonlib import MesonException, File, FileMode, version_compare, Popen_safe
18 from ..interpreter import extract_required_kwarg
19 from ..interpreter.type_checking import DEPENDENCY_METHOD_KW, INSTALL_DIR_KW, INSTALL_KW, REQUIRED_KW, NoneType
20 from ..interpreterbase import ContainerTypeInfo, FeatureDeprecated, KwargInfo, noPosargs, FeatureNew, typed_kwargs, typed_pos_args
21 from ..programs import NonExistingExternalProgram
22
23 if T.TYPE_CHECKING:
24 from . import ModuleState
25 from ..build import TargetSources
26 from ..dependencies.qt import QtPkgConfigDependency, QmakeQtDependency
27 from ..dependencies.base import DependencyObjectKWs
28 from ..interpreter import Interpreter
29 from ..interpreter import kwargs
30 from ..interpreter.interpreter import CustomTargetSources
31 from ..mesonlib import FileOrString
32 from ..programs import CommandList, Program
33 from typing_extensions import Literal
34
35 QtDependencyType = T.Union[QtPkgConfigDependency, QmakeQtDependency]
36
37 from typing_extensions import TypedDict
38
39 class ResourceCompilerKwArgs(TypedDict):
40
41 """Keyword arguments for the Resource Compiler method."""
42
43 name: T.Optional[str]
44 sources: T.List[str | build.TargetSources]
45 extra_args: T.List[str]
46 method: DependencyMethods
47
48 class UICompilerKwArgs(TypedDict):
49
50 """Keyword arguments for the Ui Compiler method."""
51
52 sources: T.List[str | build.TargetSources]
53 extra_args: T.List[str]
54 method: DependencyMethods
55 preserve_paths: bool
56
57 class MocCompilerKwArgs(TypedDict):
58
59 """Keyword arguments for the Moc Compiler method."""
60
61 sources: T.List[str | build.TargetSources]
62 headers: T.List[str | build.TargetSources]
63 extra_args: T.List[str]
64 method: DependencyMethods
65 include_directories: T.List[T.Union[str, build.IncludeDirs]]
66 dependencies: T.List[T.Union[Dependency, ExternalLibrary]]
67 preserve_paths: bool
68 output_json: bool
69
70 class PreprocessKwArgs(TypedDict):
71
72 sources: T.List[FileOrString]
73 moc_sources: T.List[str | build.TargetSources]
74 moc_headers: T.List[str | build.TargetSources]
75 qresources: T.List[FileOrString]
76 ui_files: T.List[str | build.TargetSources]
77 moc_extra_arguments: T.List[str]
78 rcc_extra_arguments: T.List[str]
79 uic_extra_arguments: T.List[str]
80 moc_output_json: bool
81 include_directories: T.List[T.Union[str, build.IncludeDirs]]
82 dependencies: T.List[T.Union[Dependency, ExternalLibrary]]
83 method: DependencyMethods
84 preserve_paths: bool
85
86 class HasToolKwArgs(kwargs.ExtractRequired):
87
88 method: DependencyMethods
89 tools: T.List[Literal['moc', 'uic', 'rcc', 'lrelease', 'qmlcachegen', 'qmltyperegistrar']]
90 version: T.List[str]
91
92 class CompileTranslationsKwArgs(TypedDict):
93
94 build_by_default: bool
95 install: bool
96 install_dir: T.Optional[str]
97 method: DependencyMethods
98 qresource: T.Optional[str]
99 rcc_extra_arguments: T.List[str]
100 ts_files: T.List[str | build.TargetSources]
101
102 class GenQrcKwArgs(TypedDict):
103
104 sources: T.List[File]
105 aliases: T.List[str]
106 prefix: str
107 output: str
108
109 class GenQmldirKwArgs(TypedDict):
110
111 module_name: str
112 module_version: str
113 module_prefix: str
114 qml_sources: T.List[str | build.TargetSources]
115 qml_singletons: T.List[str | build.TargetSources]
116 qml_internals: T.List[str | build.TargetSources]
117 designer_supported: bool
118 imports: T.List[str]
119 optional_imports: T.List[str]
120 default_imports: T.List[str]
121 depends_imports: T.List[str]
122 typeinfo: str
123 output: str
124
125 class GenQmlCachegenKwArgs(TypedDict):
126
127 target_name: str
128 qml_sources: T.List[str | build.TargetSources]
129 qml_qrc: File
130 extra_args: T.List[str]
131 module_prefix: str
132 method: DependencyMethods
133
134 class GenQmlTypeRegistrarKwArgs(TypedDict):
135
136 target_name: str
137 import_name: str
138 major_version: str
139 minor_version: str
140 namespace: str
141 typeinfo: str
142 generate_qmltype: bool
143 collected_json: T.Optional[T.Union[File, build.CustomTarget]]
144 extra_args: T.List[str]
145 method: DependencyMethods
146 install: bool
147 install_dir: T.Optional[str]
148
149 class MocJsonCollectKwArgs(TypedDict):
150
151 target_name: str
152 moc_json: T.Sequence[build.GeneratedList]
153 method: DependencyMethods
154
155 class QmlModuleKwArgs(TypedDict):
156
157 version: str
158 qml_sources: T.List[str | build.TargetSources]
159 qml_singletons: T.List[str | build.TargetSources]
160 qml_internals: T.List[str | build.TargetSources]
161 resources_prefix: str
162 moc_headers: T.List[str | build.TargetSources]
163 include_directories: T.List[T.Union[str, build.IncludeDirs]]
164 imports: T.List[str]
165 optional_imports: T.List[str]
166 default_imports: T.List[str]
167 depends_imports: T.List[str]
168 designer_supported: bool
169 namespace: str
170 typeinfo: str
171 moc_extra_arguments: T.List[str]
172 rcc_extra_arguments: T.List[str]
173 qmlcachegen_extra_arguments: T.List[str]
174 qmltyperegistrar_extra_arguments: T.List[str]
175 generate_qmldir: bool
176 generate_qmltype: bool
177 cachegen: bool
178 dependencies: T.List[T.Union[Dependency, ExternalLibrary]]
179 method: DependencyMethods
180 preserve_paths: bool
181 install_dir: str
182 install: bool
183
184 def _list_in_set_validator(choices: T.Set[str]) -> T.Callable[[T.List[str]], T.Optional[str]]:
185 """Check that the choice given was one of the given set."""
186 def inner(checklist: T.List[str]) -> T.Optional[str]:
187 invalid = set(checklist).difference(choices)
188 if invalid:
189 return f"invalid selections {', '.join(sorted(invalid))}, valid elements are {', '.join(sorted(choices))}."
190 return None
191
192 return inner
193
194 #While Qt recomment module name to a be dot separated alphanum, it can technically be
195 #any well-formed ECMAScript Identifier Name.
196 #As best effort here we just check for illegal characters
197 #see https://doc.qt.io/qt-6/qtqml-modules-identifiedmodules.html
198 _MODULE_NAME_PUNCT = r'- {}<>()[\].:;~%?&,+^=|!\/*"\''
199 _MODULE_NAME_RE = f'[^{_MODULE_NAME_PUNCT}0-9][^{_MODULE_NAME_PUNCT}]*(\\.[^{_MODULE_NAME_PUNCT}0-9][^{_MODULE_NAME_PUNCT}]*)*'
200
201 class QtBaseModule(ExtensionModule):
202 _tools_detected = False
203 _rcc_supports_depfiles = False
204 _moc_supports_depfiles = False
205 _set_of_qt_tools = {'moc', 'uic', 'rcc', 'lrelease', 'qmlcachegen', 'qmltyperegistrar'}
206 _moc_supports_json = False
207 _support_qml_module = False
208
209 def __init__(self, interpreter: Interpreter, qt_version: int = 5):
210 ExtensionModule.__init__(self, interpreter)
211 self.qt_version = qt_version
212 # It is important that this list does not change order as the order of
213 # the returned ExternalPrograms will change as well
214 self.tools: T.Dict[str, Program] = {
215 tool: NonExistingExternalProgram(tool) for tool in self._set_of_qt_tools
216 }
217 self.methods.update({
218 'has_tools': self.has_tools,
219 'preprocess': self.preprocess,
220 'compile_translations': self.compile_translations,
221 'compile_resources': self.compile_resources,
222 'compile_ui': self.compile_ui,
223 'compile_moc': self.compile_moc,
224 'qml_module': self.qml_module,
225 })
226
227 def compilers_detect(self, state: ModuleState, qt_dep: QtDependencyType) -> None:
228 """Detect Qt (4 or 5) moc, uic, rcc in the specified bindir or in PATH"""
229 wanted = f'== {qt_dep.version}'
230
231 def gen_bins() -> T.Generator[T.Tuple[str, str], None, None]:
232 for b in self.tools:
233 if qt_dep.bindir:
234 yield os.path.join(qt_dep.bindir, b), b
235 if qt_dep.libexecdir:
236 yield os.path.join(qt_dep.libexecdir, b), b
237 # prefer the (official) <tool><version> or (unofficial) <tool>-qt<version>
238 # of the tool to the plain one, as we
239 # don't know what the unsuffixed one points to without calling it.
240 yield f'{b}{qt_dep.qtver}', b
241 yield f'{b}-qt{qt_dep.qtver}', b
242 yield b, b
243
244 for b, name in gen_bins():
245 if self.tools[name].found():
246 continue
247
248 if name == 'lrelease':
249 arg = ['-version']
250 elif version_compare(qt_dep.version, '>= 5'):
251 arg = ['--version']
252 else:
253 arg = ['-v']
254
255 # Ensure that the version of qt and each tool are the same
256 def get_version(p: Program) -> str:
257 _, out, err = Popen_safe(p.get_command() + arg)
258 if name == 'lrelease' or not qt_dep.version.startswith('4'):
259 care = out
260 else:
261 care = err
262 return care.rsplit(' ', maxsplit=1)[-1].replace(')', '').strip()
263
264 p = state.find_program(b, required=False,
265 version_func=get_version,
266 wanted=wanted)
267 if p.found():
268 self.tools[name] = p
269
270 def _detect_tools(self, state: ModuleState, method: DependencyMethods, required: bool = True, version: T.Optional[T.List[str]] = None) -> None:
271 if self._tools_detected:
272 return
273 self._tools_detected = True
274 mlog.log(f'Detecting Qt{self.qt_version} tools')
275 native = state.machine_map.host
276 version = version or []
277 kwargs: DependencyObjectKWs = {'required': required, 'modules': ['Core'], 'method': method, 'native': native, 'version': version}
278 # Just pick one to make mypy happy
279 qt = T.cast('QtPkgConfigDependency', find_external_dependency(f'qt{self.qt_version}', state.environment, kwargs))
280 if qt.found():
281 # Get all tools and then make sure that they are the right version
282 self.compilers_detect(state, qt)
283 if version_compare(qt.version, '>=6.2.0'):
284 #5.1x supports qmlcachegen and other tools to some extend, but arguments/build process marginally differs
285 self._support_qml_module = True
286 if version_compare(qt.version, '>=5.15.0'):
287 self._moc_supports_depfiles = True
288 self._moc_supports_json = True
289 else:
290 mlog.warning('moc dependencies will not work properly until you move to Qt >= 5.15', fatal=False)
291 if version_compare(qt.version, '>=5.14.0'):
292 self._rcc_supports_depfiles = True
293 else:
294 mlog.warning('rcc dependencies will not work properly until you move to Qt >= 5.14:',
295 mlog.bold('https://bugreports.qt.io/browse/QTBUG-45460'), fatal=False)
296 else:
297 suffix = f'-qt{self.qt_version}'
298 self.tools['moc'] = NonExistingExternalProgram(name='moc' + suffix)
299 self.tools['uic'] = NonExistingExternalProgram(name='uic' + suffix)
300 self.tools['rcc'] = NonExistingExternalProgram(name='rcc' + suffix)
301 self.tools['lrelease'] = NonExistingExternalProgram(name='lrelease' + suffix)
302
303 @staticmethod
304 def _qrc_nodes(state: ModuleState, rcc_file: FileOrString) -> T.Tuple[str, T.List[str]]:
305 abspath: str
306 if isinstance(rcc_file, str):
307 abspath = os.path.join(state.environment.source_dir, state.subdir, rcc_file)
308 else:
309 abspath = rcc_file.absolute_path(state.environment.source_dir, state.environment.build_dir)
310 rcc_dirname = os.path.dirname(abspath)
311
312 # FIXME: what error are we actually trying to check here? (probably parse errors?)
313 try:
314 tree = ET.parse(abspath)
315 root = tree.getroot()
316 result: T.List[str] = []
317 for child in root[0]:
318 if child.tag != 'file':
319 mlog.warning("malformed rcc file: ", os.path.join(state.subdir, str(rcc_file)))
320 break
321 elif child.text is None:
322 raise MesonException(f'<file> element without a path in {os.path.join(state.subdir, str(rcc_file))}')
323 else:
324 result.append(child.text)
325
326 return rcc_dirname, result
327 except MesonException:
328 raise
329 except Exception:
330 raise MesonException(f'Unable to parse resource file {abspath}')
331
332 def _parse_qrc_deps(self, state: ModuleState, rcc_file_: FileOrString) -> T.List[File]:
333 result: T.List[File] = []
334 inputs: T.Sequence['FileOrString'] = [rcc_file_]
335
336 for rcc_file in inputs:
337 rcc_dirname, nodes = self._qrc_nodes(state, rcc_file)
338 for resource_path in nodes:
339 # We need to guess if the pointed resource is:
340 # a) in build directory -> implies a generated file
341 # b) in source directory
342 # c) somewhere else external dependency file to bundle
343 #
344 # Also from qrc documentation: relative path are always from qrc file
345 # So relative path must always be computed from qrc file !
346 if os.path.isabs(resource_path):
347 # a)
348 if resource_path.startswith(os.path.abspath(state.environment.build_dir)):
349 resource_relpath = os.path.relpath(resource_path, state.environment.build_dir)
350 result.append(File(is_built=True, subdir='', fname=resource_relpath))
351 # either b) or c)
352 else:
353 result.append(File(is_built=False, subdir=state.subdir, fname=resource_path))
354 else:
355 path_from_rcc = os.path.normpath(os.path.join(rcc_dirname, resource_path))
356 # a)
357 if path_from_rcc.startswith(state.environment.build_dir):
358 result.append(File(is_built=True, subdir=state.subdir, fname=resource_path))
359 # b)
360 else:
361 result.append(File(is_built=False, subdir=state.subdir, fname=path_from_rcc))
362 return result
363
364 @FeatureNew('qt.has_tools', '0.54.0')
365 @noPosargs
366 @typed_kwargs(
367 'qt.has_tools',
368 DEPENDENCY_METHOD_KW,
369 REQUIRED_KW.evolve(default=False),
370 KwargInfo('tools', ContainerTypeInfo(list, str), listify=True,
371 default=['moc', 'uic', 'rcc', 'lrelease'],
372 validator=_list_in_set_validator(_set_of_qt_tools),
373 since='1.6.0'),
374 KwargInfo('version', ContainerTypeInfo(list, str), listify=True, default=[], since='1.11'),
375 )
376 def has_tools(self, state: ModuleState, args: T.Tuple, kwargs: HasToolKwArgs) -> bool:
377 method = kwargs['method']
378 # We have to cast here because TypedDicts are invariant, even though
379 # ExtractRequiredKwArgs is a subset of HasToolKwArgs, type checkers
380 # will insist this is wrong
381 disabled, required, feature = extract_required_kwarg(kwargs, state.subproject, default=False)
382 if disabled:
383 mlog.log('qt.has_tools skipped: feature', mlog.bold(feature), 'disabled')
384 return False
385 self._detect_tools(state, method, required=False, version=kwargs['version'])
386 for tool in kwargs['tools']:
387 assert tool in self._set_of_qt_tools, f'tools must be in {self._set_of_qt_tools}'
388 if not self.tools[tool].found():
389 if required:
390 raise MesonException('Qt tools not found')
391 return False
392 return True
393
394 @FeatureNew('qt.compile_resources', '0.59.0')
395 @noPosargs
396 @typed_kwargs(
397 'qt.compile_resources',
398 DEPENDENCY_METHOD_KW,
399 KwargInfo('name', (str, NoneType)),
400 KwargInfo(
401 'sources',
402 ContainerTypeInfo(list, (File, str, build.CustomTarget, build.CustomTargetIndex, build.GeneratedList), allow_empty=False),
403 listify=True,
404 required=True,
405 ),
406 KwargInfo('extra_args', ContainerTypeInfo(list, str), listify=True, default=[]),
407 )
408 def compile_resources(self, state: 'ModuleState', args: T.Tuple, kwargs: 'ResourceCompilerKwArgs') -> ModuleReturnValue:
409 """Compile Qt resources files.
410
411 Uses CustomTargets to generate .cpp files from .qrc files.
412 """
413 if any(isinstance(s, (build.CustomTarget, build.CustomTargetIndex, build.GeneratedList)) for s in kwargs['sources']):
414 FeatureNew.single_use('qt.compile_resources: custom_target or generator for "sources" keyword argument',
415 '0.60.0', state.subproject, location=state.current_node)
416 out = self._compile_resources_impl(state, kwargs)
417 return ModuleReturnValue(out, [out])
418
419 def _compile_resources_impl(self, state: 'ModuleState', kwargs: 'ResourceCompilerKwArgs') -> T.List[build.CustomTarget]:
420 # Avoid the FeatureNew when dispatching from preprocess
421 self._detect_tools(state, kwargs['method'])
422 if not self.tools['rcc'].found():
423 err_msg = ("{0} sources specified and couldn't find {1}, "
424 "please check your qt{2} installation")
425 raise MesonException(err_msg.format('RCC', f'rcc-qt{self.qt_version}', self.qt_version))
426
427 # List of generated CustomTargets
428 targets: T.List[build.CustomTarget] = []
429
430 # depfile arguments
431 DEPFILE_ARGS: T.List[str] = ['--depfile', '@DEPFILE@'] if self._rcc_supports_depfiles else []
432
433 name = kwargs['name']
434 sources: T.List[File] = []
435 for s in kwargs['sources']:
436 if isinstance(s, str):
437 sources.append(File.from_source_file(state.environment.source_dir, state.subdir, s))
438 elif isinstance(s, File):
439 sources.append(s)
440 else:
441 # TODO: this could be fixed with dyndeps
442 raise MesonException('Resource xml files generated at build-time cannot be used with '
443 'qt.compile_resources() because we need to scan the xml for '
444 'dependencies.\nUse configure_file() instead to generate it at '
445 'configure-time.')
446 extra_args = kwargs['extra_args']
447
448 # If a name was set generate a single .cpp file from all of the qrc
449 # files, otherwise generate one .cpp file per qrc file.
450 cmd: CommandList
451 if name:
452 qrc_deps: T.List[File] = []
453 for s in sources:
454 qrc_deps.extend(self._parse_qrc_deps(state, s))
455 cmd = [self.tools['rcc'], '-name', name, '-o', '@OUTPUT@', *extra_args, '@INPUT@', *DEPFILE_ARGS]
456 res_target = build.CustomTarget(
457 name,
458 state.subdir,
459 state.environment,
460 cmd,
461 sources,
462 [f'{name}.cpp'],
463 state.current_build_project,
464 depend_files=qrc_deps,
465 depfile=f'{name}.d',
466 description='Compiling Qt resources {}',
467 )
468 targets.append(res_target)
469 else:
470 for rcc_file in sources:
471 qrc_deps = self._parse_qrc_deps(state, rcc_file)
472 basename = os.path.basename(rcc_file.fname)
473 name = f'qt{self.qt_version}-{basename.replace(".", "_")}'
474 cmd = [self.tools['rcc'], '-name', '@BASENAME@', '-o', '@OUTPUT@', *extra_args, '@INPUT@', *DEPFILE_ARGS]
475 res_target = build.CustomTarget(
476 name,
477 state.subdir,
478 state.environment,
479 cmd,
480 [rcc_file],
481 [f'{name}.cpp'],
482 state.current_build_project,
483 depend_files=qrc_deps,
484 depfile=f'{name}.d',
485 description='Compiling Qt resources {}',
486 )
487 targets.append(res_target)
488
489 return targets
490
491 @FeatureNew('qt.compile_ui', '0.59.0')
492 @noPosargs
493 @typed_kwargs(
494 'qt.compile_ui',
495 DEPENDENCY_METHOD_KW,
496 KwargInfo(
497 'sources',
498 ContainerTypeInfo(list, (File, str, build.CustomTarget, build.CustomTargetIndex, build.GeneratedList), allow_empty=False),
499 listify=True,
500 required=True,
501 ),
502 KwargInfo('extra_args', ContainerTypeInfo(list, str), listify=True, default=[]),
503 KwargInfo('preserve_paths', bool, default=False, since='1.4.0'),
504 )
505 def compile_ui(self, state: ModuleState, args: T.Tuple, kwargs: UICompilerKwArgs) -> ModuleReturnValue:
506 """Compile UI resources into cpp headers."""
507 if any(isinstance(s, (build.CustomTarget, build.CustomTargetIndex, build.GeneratedList)) for s in kwargs['sources']):
508 FeatureNew.single_use('qt.compile_ui: custom_target or generator for "sources" keyword argument',
509 '0.60.0', state.subproject, location=state.current_node)
510 out = self._compile_ui_impl(state, kwargs)
511 return ModuleReturnValue(out, [out])
512
513 def _compile_ui_impl(self, state: ModuleState, kwargs: UICompilerKwArgs) -> build.GeneratedList:
514 # Avoid the FeatureNew when dispatching from preprocess
515 self._detect_tools(state, kwargs['method'])
516 if not self.tools['uic'].found():
517 err_msg = ("{0} sources specified and couldn't find {1}, "
518 "please check your qt{2} installation")
519 raise MesonException(err_msg.format('UIC', f'uic-qt{self.qt_version}', self.qt_version))
520
521 preserve_path_from = os.path.join(state.source_root, state.subdir) if kwargs['preserve_paths'] else None
522 gen = build.Generator(
523 state.environment,
524 self.tools['uic'],
525 kwargs['extra_args'] + ['-o', '@OUTPUT@', '@INPUT@'],
526 ['ui_@[email protected]'],
527 name=f'Qt{self.qt_version} ui')
528 sources = self.interpreter.source_strings_to_files(kwargs['sources'])
529 return gen.process_files(sources, state.subdir, preserve_path_from)
530
531 @FeatureNew('qt.compile_moc', '0.59.0')
532 @noPosargs
533 @typed_kwargs(
534 'qt.compile_moc',
535 DEPENDENCY_METHOD_KW,
536 KwargInfo(
537 'sources',
538 ContainerTypeInfo(list, (File, str, build.CustomTarget, build.CustomTargetIndex, build.GeneratedList)),
539 listify=True,
540 default=[],
541 ),
542 KwargInfo(
543 'headers',
544 ContainerTypeInfo(list, (File, str, build.CustomTarget, build.CustomTargetIndex, build.GeneratedList)),
545 listify=True,
546 default=[]
547 ),
548 KwargInfo('extra_args', ContainerTypeInfo(list, str), listify=True, default=[]),
549 KwargInfo('include_directories', ContainerTypeInfo(list, (build.IncludeDirs, str)), listify=True, default=[]),
550 KwargInfo('dependencies', ContainerTypeInfo(list, (Dependency, ExternalLibrary)), listify=True, default=[]),
551 KwargInfo('preserve_paths', bool, default=False, since='1.4.0'),
552 KwargInfo('output_json', bool, default=False, since='1.7.0'),
553 )
554 def compile_moc(self, state: ModuleState, args: T.Tuple, kwargs: MocCompilerKwArgs) -> ModuleReturnValue:
555 if any(isinstance(s, (build.CustomTarget, build.CustomTargetIndex, build.GeneratedList)) for s in kwargs['headers']):
556 FeatureNew.single_use('qt.compile_moc: custom_target or generator for "headers" keyword argument',
557 '0.60.0', state.subproject, location=state.current_node)
558 if any(isinstance(s, (build.CustomTarget, build.CustomTargetIndex, build.GeneratedList)) for s in kwargs['sources']):
559 FeatureNew.single_use('qt.compile_moc: custom_target or generator for "sources" keyword argument',
560 '0.60.0', state.subproject, location=state.current_node)
561 out = self._compile_moc_impl(state, kwargs)
562 return ModuleReturnValue(out, [out])
563
564 def _compile_moc_impl(self, state: ModuleState, kwargs: MocCompilerKwArgs) -> T.List[build.GeneratedList]:
565 # Avoid the FeatureNew when dispatching from preprocess
566 self._detect_tools(state, kwargs['method'])
567 if not self.tools['moc'].found():
568 err_msg = ("{0} sources specified and couldn't find {1}, "
569 "please check your qt{2} installation")
570 raise MesonException(err_msg.format('MOC', f'uic-qt{self.qt_version}', self.qt_version))
571
572 if not (kwargs['headers'] or kwargs['sources']):
573 raise build.InvalidArguments('At least one of the "headers" or "sources" keyword arguments must be provided and not empty')
574
575 inc = state.get_include_args(include_dirs=kwargs['include_directories'])
576 compile_args: T.List[str] = []
577 depends: T.List[T.Union[build.BuildTarget, build.CustomTarget, build.CustomTargetIndex]] = []
578 for dep in kwargs['dependencies']:
579 compile_args.extend(a for a in dep.get_all_compile_args() if a.startswith(('-I', '-F', '-D')))
580 if isinstance(dep, InternalDependency):
581 for incl in dep.include_directories:
582 compile_args.extend(f'-I{i}' for i in incl.abs_string_list(self.interpreter.source_root, self.interpreter.environment.build_dir))
583 for src in dep.sources:
584 if isinstance(src, (build.CustomTarget, build.BuildTarget, build.CustomTargetIndex)):
585 depends.append(src)
586
587 output: T.List[build.GeneratedList] = []
588
589 do_output_json: bool = kwargs['output_json']
590 if do_output_json and not self._moc_supports_json:
591 raise MesonException(f'moc-qt{self.qt_version} doesn\'t support "output_json" option')
592
593 # depfile arguments (defaults to <output-name>.d)
594 DEPFILE_ARGS: T.List[str] = ['--output-dep-file'] if self._moc_supports_depfiles else []
595 JSON_ARGS: T.List[str] = ['--output-json'] if do_output_json else []
596
597 arguments = kwargs['extra_args'] + DEPFILE_ARGS + JSON_ARGS + inc + compile_args + ['@INPUT@', '-o', '@OUTPUT0@']
598 preserve_path_from = os.path.join(state.source_root, state.subdir) if kwargs['preserve_paths'] else None
599 if kwargs['headers']:
600 header_gen_output: T.List[str] = ['moc_@[email protected]']
601 if do_output_json:
602 header_gen_output.append('moc_@[email protected]')
603 moc_gen = build.Generator(
604 state.environment,
605 self.tools['moc'], arguments, header_gen_output,
606 depends=depends,
607 depfile='moc_@[email protected]',
608 name=f'Qt{self.qt_version} moc header')
609 headers = self.interpreter.source_strings_to_files(kwargs['headers'])
610 output.append(moc_gen.process_files(headers, state.subdir, preserve_path_from))
611 if kwargs['sources']:
612 source_gen_output: T.List[str] = ['@[email protected]']
613 if do_output_json:
614 source_gen_output.append('@[email protected]')
615 moc_gen = build.Generator(
616 state.environment,
617 self.tools['moc'], arguments, source_gen_output,
618 depfile='@[email protected]',
619 name=f'Qt{self.qt_version} moc source')
620 sources = self.interpreter.source_strings_to_files(kwargs['sources'])
621 output.append(moc_gen.process_files(sources, state.subdir, preserve_path_from))
622
623 return output
624
625 # We can't use typed_pos_args here, the signature is ambiguous
626 @typed_kwargs(
627 'qt.preprocess',
628 DEPENDENCY_METHOD_KW,
629 KwargInfo('sources', ContainerTypeInfo(list, (File, str)), listify=True, default=[], deprecated='0.59.0'),
630 KwargInfo('qresources', ContainerTypeInfo(list, (File, str)), listify=True, default=[]),
631 KwargInfo('ui_files', ContainerTypeInfo(list, (File, str, build.CustomTarget, build.CustomTargetIndex, build.GeneratedList)), listify=True, default=[],
632 since_values={ContainerTypeInfo(list, (build.CustomTargetIndex, build.GeneratedList)): '1.12'}),
633 KwargInfo('moc_sources', ContainerTypeInfo(list, (File, str, build.CustomTarget, build.CustomTargetIndex, build.GeneratedList)), listify=True, default=[],
634 since_values={ContainerTypeInfo(list, (build.CustomTargetIndex, build.GeneratedList)): '1.12'}),
635 KwargInfo('moc_headers', ContainerTypeInfo(list, (File, str, build.CustomTarget, build.CustomTargetIndex, build.GeneratedList)), listify=True, default=[],
636 since_values={ContainerTypeInfo(list, (build.CustomTargetIndex, build.GeneratedList)): '1.12'}),
637 KwargInfo('moc_extra_arguments', ContainerTypeInfo(list, str), listify=True, default=[], since='0.44.0'),
638 KwargInfo('rcc_extra_arguments', ContainerTypeInfo(list, str), listify=True, default=[], since='0.49.0'),
639 KwargInfo('uic_extra_arguments', ContainerTypeInfo(list, str), listify=True, default=[], since='0.49.0'),
640 KwargInfo('include_directories', ContainerTypeInfo(list, (build.IncludeDirs, str)), listify=True, default=[]),
641 KwargInfo('dependencies', ContainerTypeInfo(list, (Dependency, ExternalLibrary)), listify=True, default=[]),
642 KwargInfo('preserve_paths', bool, default=False, since='1.4.0'),
643 KwargInfo('moc_output_json', bool, default=False, since='1.7.0'),
644 )
645 def preprocess(self, state: ModuleState, args: T.List[T.Union[str, File]], kwargs: PreprocessKwArgs) -> ModuleReturnValue:
646 _sources = args[1:]
647 if _sources:
648 FeatureDeprecated.single_use('qt.preprocess positional sources', '0.59', state.subproject, location=state.current_node)
649 # List is invariant, os we have to cast...
650 sources: T.List[str | build.TargetSources] = [*_sources, *kwargs['sources']]
651 for s in sources:
652 if not isinstance(s, (str, File)):
653 raise build.InvalidArguments('Variadic arguments to qt.preprocess must be Strings or Files')
654 method = kwargs['method']
655
656 if kwargs['qresources']:
657 # custom output name set? -> one output file, multiple otherwise
658 rcc_kwargs: ResourceCompilerKwArgs = {'name': '',
659 'sources': T.cast('T.List[str | TargetSources]', kwargs['qresources']),
660 'extra_args': kwargs['rcc_extra_arguments'], 'method': method}
661 if args:
662 name = args[0]
663 if not isinstance(name, str):
664 raise build.InvalidArguments('First argument to qt.preprocess must be a string')
665 rcc_kwargs['name'] = name
666 sources.extend(self._compile_resources_impl(state, rcc_kwargs))
667
668 if kwargs['ui_files']:
669 ui_kwargs: UICompilerKwArgs = {
670 'sources': kwargs['ui_files'],
671 'extra_args': kwargs['uic_extra_arguments'],
672 'method': method,
673 'preserve_paths': kwargs['preserve_paths'],
674 }
675 sources.append(self._compile_ui_impl(state, ui_kwargs))
676
677 if kwargs['moc_headers'] or kwargs['moc_sources']:
678 moc_kwargs: MocCompilerKwArgs = {
679 'extra_args': kwargs['moc_extra_arguments'],
680 'sources': kwargs['moc_sources'],
681 'headers': kwargs['moc_headers'],
682 'include_directories': kwargs['include_directories'],
683 'dependencies': kwargs['dependencies'],
684 'method': method,
685 'preserve_paths': kwargs['preserve_paths'],
686 'output_json': kwargs['moc_output_json']
687 }
688 sources.extend(self._compile_moc_impl(state, moc_kwargs))
689
690 return ModuleReturnValue(sources, [sources])
691
692 @FeatureNew('qt.compile_translations', '0.44.0')
693 @noPosargs
694 @typed_kwargs(
695 'qt.compile_translations',
696 KwargInfo('build_by_default', bool, default=False),
697 DEPENDENCY_METHOD_KW,
698 INSTALL_KW,
699 INSTALL_DIR_KW,
700 KwargInfo('qresource', (str, NoneType), since='0.56.0'),
701 KwargInfo('rcc_extra_arguments', ContainerTypeInfo(list, str), listify=True, default=[], since='0.56.0'),
702 KwargInfo('ts_files', ContainerTypeInfo(list, (str, File, build.CustomTarget, build.CustomTargetIndex, build.GeneratedList)), listify=True, default=[]),
703 )
704 def compile_translations(self, state: ModuleState, args: T.Tuple, kwargs: CompileTranslationsKwArgs) -> ModuleReturnValue:
705 ts_files = kwargs['ts_files']
706 if any(isinstance(s, (build.CustomTarget, build.CustomTargetIndex, build.GeneratedList)) for s in ts_files):
707 FeatureNew.single_use('qt.compile_translations: custom_target or generator for "ts_files" keyword argument',
708 '0.60.0', state.subproject, location=state.current_node)
709 if kwargs['install'] and not kwargs['install_dir']:
710 raise MesonException('qt.compile_translations: "install_dir" keyword argument must be set when "install" is true.')
711 qresource = kwargs['qresource']
712 if qresource:
713 if ts_files:
714 raise MesonException('qt.compile_translations: Cannot specify both ts_files and qresource')
715 if os.path.dirname(qresource) != '':
716 raise MesonException('qt.compile_translations: qresource file name must not contain a subdirectory.')
717 qresource_file = File.from_built_file(state.subdir, qresource)
718 infile_abs = os.path.join(state.environment.source_dir, qresource_file.relative_name())
719 outfile_abs = os.path.join(state.environment.build_dir, qresource_file.relative_name())
720 os.makedirs(os.path.dirname(outfile_abs), exist_ok=True)
721 shutil.copy2(infile_abs, outfile_abs)
722 self.interpreter.add_build_def_file(infile_abs)
723
724 _, nodes = self._qrc_nodes(state, qresource_file)
725 for c in nodes:
726 if c.endswith('.qm'):
727 ts_files.append(c.rstrip('.qm') + '.ts')
728 else:
729 raise MesonException(f'qt.compile_translations: qresource can only contain qm files, found {c}')
730 results = self.preprocess(state, [], {'qresources': qresource_file, 'rcc_extra_arguments': kwargs['rcc_extra_arguments']})
731 self._detect_tools(state, kwargs['method'])
732 translations: T.List[build.CustomTarget] = []
733 for ts in ts_files:
734 if not self.tools['lrelease'].found():
735 raise MesonException('qt.compile_translations: ' +
736 self.tools['lrelease'].name + ' not found')
737 ts_file: CustomTargetSources
738 if qresource:
739 # In this case we know that ts_files is always a List[str], as
740 # it's generated above and no ts_files are passed in. However,
741 # mypy can't figure that out so we use assert to assure it that
742 # what we're doing is safe
743 assert isinstance(ts, str), 'for mypy'
744 outdir = os.path.dirname(os.path.normpath(os.path.join(state.subdir, ts)))
745 ts_file = File.from_source_file(state.environment.source_dir, outdir, os.path.basename(ts))
746 elif isinstance(ts, str):
747 outdir = state.subdir
748 ts_file = File.from_source_file(state.environment.source_dir, state.subdir, ts)
749 else:
750 outdir = state.subdir
751 ts_file = ts
752 cmd: CommandList = [self.tools['lrelease'], '@INPUT@', '-qm', '@OUTPUT@']
753 lrelease_target = build.CustomTarget(
754 f'qt{self.qt_version}-compile-{ts}',
755 outdir,
756 state.environment,
757 cmd,
758 [ts_file],
759 ['@[email protected]'],
760 state.current_build_project,
761 install=kwargs['install'],
762 install_dir=[kwargs['install_dir']],
763 install_tag=['i18n'],
764 build_by_default=kwargs['build_by_default'],
765 description='Compiling Qt translations {}',
766 )
767 translations.append(lrelease_target)
768 if qresource:
769 return ModuleReturnValue(results.return_value[0], [results.new_objects, translations])
770 else:
771 return ModuleReturnValue(translations, [translations])
772
773 def _source_to_files(self, state: ModuleState, sources: T.List[str | build.TargetSources]) -> T.List[File]:
774
775 content_files = []
776 for s in sources:
777 if isinstance(s, (build.CustomTarget, build.CustomTargetIndex)):
778 for o in s.get_outputs():
779 content_files.append(File.from_built_file(state.backend.get_target_dir(s), o))
780 elif isinstance(s, File):
781 content_files.append(s)
782 elif isinstance(s, build.GeneratedList):
783 for gen_src in s.get_outputs():
784 content_files.append(File.from_built_file(state.subdir, gen_src))
785 else:
786 content_files.append(File.from_source_file(
787 state.environment.get_source_dir(),
788 state.subdir,
789 s
790 ))
791 return content_files
792
793 def _gen_qrc(self, state: ModuleState, kwargs: GenQrcKwArgs) -> File:
794
795 fileout = File.from_built_file(state.subdir, kwargs['output'])
796 fileout_abs = os.path.join(state.environment.build_dir, fileout.relative_name())
797 if not os.path.isdir(state.environment.build_dir):
798 os.mkdir(state.environment.build_dir)
799
800 rcc = ET.Element('RCC')
801 qresource = ET.SubElement(rcc, 'qresource', prefix='/' + kwargs['prefix'])
802 assert (len(kwargs['sources']) == len(kwargs['aliases']))
803 for source, alias in zip(kwargs['sources'], kwargs['aliases']):
804 filenode = ET.SubElement(qresource, 'file', alias=alias)
805 filenode.text = source.absolute_path(
806 state.environment.get_source_dir(),
807 state.environment.get_build_dir()
808 )
809
810 tree = ET.ElementTree(rcc)
811 tree.write(fileout_abs)
812 return fileout
813
814 def _gen_qmldir(self, state: ModuleState, kwargs: GenQmldirKwArgs) -> File:
815 module_name: str = kwargs['module_name']
816 module_version: str = kwargs['module_version']
817 module_prefix: str = kwargs['module_prefix']
818 designer_supported: bool = kwargs['designer_supported']
819 typeinfo_file: str = kwargs['typeinfo']
820
821 #Foo.Bar/1.0 foo.bar/auto foo.bar
822 import_re = re.compile(r'^(' + _MODULE_NAME_RE + r')(/((\d+(\.\d+)?)|auto))?$')
823
824 fileout = File.from_built_file(state.subdir, kwargs['output'])
825 fileout_abs = os.path.join(state.environment.build_dir, fileout.relative_name())
826 if not os.path.isdir(state.environment.build_dir):
827 os.mkdir(state.environment.build_dir)
828
829 with open(fileout_abs, 'w', encoding='utf-8') as fd:
830
831 def __gen_import(import_type: str, importlist: T.List[str]) -> None:
832 for import_string in importlist:
833 match = import_re.match(import_string)
834 if not match:
835 raise MesonException(f'invalid syntax for qml import {import_string}')
836 module: str = match.group(1)
837 version: str = match.group(4) or ''
838 fd.write(f'{import_type} {module} {version}\n')
839
840 def __gen_declaration(qualifier: str, version: str, importlist: T.List[str | build.TargetSources]) -> None:
841 importpathlist = self._source_to_files(state, importlist)
842 for s in importpathlist:
843 basename: str = os.path.basename(s.fname)
844 classname: str = basename.rsplit('.', maxsplit=1)[0]
845
846 if not basename.endswith(('.qml', '.js', '.mjs')):
847 raise MesonException(f'unexpected file type declared in qml sources {s}')
848
849 if not classname or '.' in classname or classname[0].islower():
850 raise MesonException(f'{basename} is not a valid QML file name')
851 if version:
852 fd.write(f'{qualifier}{classname} {version} {basename}\n')
853 else:
854 fd.write(f'{qualifier}{classname} {basename}\n')
855
856 fd.write(f'module {module_name}\n')
857 fd.write(f'prefer :/{module_prefix}/\n')
858
859 __gen_import('import', kwargs['imports'])
860 __gen_import('optional import', kwargs['optional_imports'])
861 __gen_import('default import', kwargs['default_imports'])
862 __gen_import('depends', kwargs['depends_imports'])
863 __gen_declaration('', module_version, kwargs['qml_sources'])
864 __gen_declaration('singleton ', module_version, kwargs['qml_singletons'])
865 __gen_declaration('internal ', '', kwargs['qml_internals'])
866
867 if typeinfo_file:
868 fd.write(f'typeinfo {typeinfo_file}\n')
869
870 if designer_supported:
871 fd.write('designersupported\n')
872 return fileout
873
874 def _moc_json_collect(self, state: ModuleState, kwargs: MocJsonCollectKwArgs) -> build.CustomTarget:
875 self._detect_tools(state, kwargs['method'])
876 if not self.tools['moc'].found():
877 raise MesonException('qt.qml_module: ' +
878 self.tools['moc'].name + ' not found')
879
880 target_name: str = kwargs['target_name']
881 moc_json: T.Sequence[build.GeneratedList] = kwargs['moc_json']
882
883 #there may be a better way :-/
884 input_args: T.List[str] = []
885 input_counter = 0
886 for g in moc_json:
887 for fname in g.get_outputs():
888 if fname.endswith('.json'):
889 input_args.append(f'@INPUT{input_counter}@')
890 input_counter += 1
891
892 cmd: CommandList = [self.tools['moc'], '--collect-json', '-o', '@OUTPUT@', *input_args]
893 return build.CustomTarget(
894 f'moc_collect_json_{target_name}',
895 state.subdir,
896 state.environment,
897 cmd,
898 moc_json,
899 [f'{target_name}_json_collect.json'],
900 state.current_build_project,
901 description=f'Collecting json type information for {target_name}',
902 )
903
904 def _gen_qml_cachegen(self, state: ModuleState, kwargs: GenQmlCachegenKwArgs) -> T.List[T.Union[build.CustomTarget, build.GeneratedList]]:
905 self._detect_tools(state, kwargs['method'])
906 if not self.tools['qmlcachegen'].found():
907 raise MesonException('qt.qml_module: ' +
908 self.tools['qmlcachegen'].name + ' not found')
909
910 target_name: str = kwargs['target_name']
911
912 command_args = ['-o', '@OUTPUT@'] + kwargs['extra_args']
913 for qrc in self._source_to_files(state, [kwargs['qml_qrc']]):
914 command_args.extend(['--resource', qrc.absolute_path(
915 state.environment.get_source_dir(),
916 state.environment.get_build_dir()
917 )])
918
919 command_args.append('@INPUT@')
920
921 cache_gen = build.Generator(
922 state.environment,
923 self.tools['qmlcachegen'],
924 command_args,
925 [f'{target_name}_@[email protected]'],
926 name=f'Qml cache generation for {target_name}')
927
928 output: T.List[T.Union[build.CustomTarget, build.GeneratedList]] = []
929 qml_sources = self.interpreter.source_strings_to_files(kwargs['qml_sources'])
930 output.append(cache_gen.process_files(qml_sources, state.subdir))
931
932 cachegen_inputs: T.List[str] = []
933 qml_sources_paths = self._source_to_files(state, kwargs['qml_sources'])
934 for s in qml_sources_paths:
935 source_basename = os.path.basename(s.fname)
936 ressource_path = os.path.join('/', kwargs['module_prefix'], source_basename)
937 cachegen_inputs.append(ressource_path)
938
939 cmd: CommandList = \
940 [self.tools['qmlcachegen'], '-o', '@OUTPUT@', '--resource-name', f'qmlcache_{target_name}',
941 *kwargs['extra_args'], '--resource=@INPUT@', *cachegen_inputs]
942 cacheloader_target = build.CustomTarget(
943 f'cacheloader_{target_name}',
944 state.subdir,
945 state.environment,
946 cmd,
947 [kwargs['qml_qrc']],
948 #output name format matters here
949 [f'{target_name}_qmlcache_loader.cpp'],
950 state.current_build_project,
951 description=f'Qml cache loader for {target_name}',
952 )
953 output.append(cacheloader_target)
954 return output
955
956 def _qml_type_registrar(self, state: ModuleState, kwargs: GenQmlTypeRegistrarKwArgs) -> build.CustomTarget:
957 self._detect_tools(state, kwargs['method'])
958 if not self.tools['qmltyperegistrar'].found():
959 raise MesonException('qt.qml_module: ' +
960 self.tools['qmltyperegistrar'].name + ' not found')
961
962 import_name: str = kwargs['import_name']
963 major_version: str = kwargs['major_version']
964 minor_version: str = kwargs['minor_version']
965 namespace: str = kwargs['namespace']
966 typeinfo: str = kwargs['typeinfo']
967 target_name: str = kwargs['target_name']
968 collected_json: T.Optional[T.Union[File, build.CustomTarget]] = kwargs['collected_json']
969
970 inputs: T.Sequence[T.Union[File, build.CustomTarget]] = [collected_json] if collected_json else []
971 outputs: T.List[str] = [f'{target_name}_qmltyperegistrations.cpp']
972 install_dir: T.List[T.Union[str, Literal[False]]] = [False]
973 install_tag: T.List[T.Union[str, None]] = [None]
974
975 cmd: CommandList = [
976 self.tools['qmltyperegistrar'],
977 '--import-name', import_name,
978 '--major-version', major_version,
979 '--minor-version', minor_version,
980 '-o', '@OUTPUT0@',
981 *kwargs['extra_args'],
982 ]
983
984 if namespace:
985 cmd.extend(['--namespace', namespace])
986
987 if kwargs['generate_qmltype']:
988 cmd.extend(['--generate-qmltypes', '@OUTPUT1@'])
989 if typeinfo == '':
990 outputs.append(f'{target_name}.qmltypes')
991 else:
992 outputs.append(f'{typeinfo}')
993 install_dir.append(kwargs['install_dir'])
994 install_tag.append('devel')
995
996 if collected_json:
997 cmd.append('@INPUT@')
998
999 return build.CustomTarget(
1000 f'typeregistrar_{target_name}',
1001 state.subdir,
1002 state.environment,
1003 cmd,
1004 inputs,
1005 outputs,
1006 state.current_build_project,
1007 install=kwargs['install'],
1008 install_dir=install_dir,
1009 install_tag=install_tag,
1010 description=f'Qml type registration for {target_name}',
1011 )
1012
1013 @FeatureNew('qt.qml_module', '1.7')
1014 @typed_pos_args('qt.qml_module', str)
1015 @typed_kwargs(
1016 'qt.qml_module',
1017 KwargInfo('version', str, default='254.254'),
1018 #qml sources
1019 KwargInfo('qml_sources', ContainerTypeInfo(list, (File, str, build.CustomTarget)), listify=True, default=[]),
1020 KwargInfo('qml_singletons', ContainerTypeInfo(list, (File, str, build.CustomTarget)), listify=True, default=[]),
1021 KwargInfo('qml_internals', ContainerTypeInfo(list, (File, str, build.CustomTarget)), listify=True, default=[]),
1022 KwargInfo('resources_prefix', str, default='qt/qml'),
1023 #qmldir generation
1024 KwargInfo('imports', ContainerTypeInfo(list, (str)), default=[]),
1025 KwargInfo('optional_imports', ContainerTypeInfo(list, (str)), default=[]),
1026 KwargInfo('default_imports', ContainerTypeInfo(list, (str)), default=[]),
1027 #match DEPENDENCIES argument from CMake, but dependencies keyword is already taken
1028 KwargInfo('depends_imports', ContainerTypeInfo(list, (str)), default=[]),
1029 KwargInfo('designer_supported', bool, default=False),
1030 #for type registration, same arguments as moc
1031 #moc_sources is voluntary ommited as typeregistrar needs to import a header
1032 KwargInfo('moc_headers', ContainerTypeInfo(list, (File, str, build.CustomTarget)), listify=True, default=[]),
1033 KwargInfo('include_directories', ContainerTypeInfo(list, (build.IncludeDirs, str)), listify=True, default=[]),
1034 KwargInfo('namespace', str, default=''),
1035 KwargInfo('typeinfo', str, default=''),
1036
1037 KwargInfo('moc_extra_arguments', ContainerTypeInfo(list, str), listify=True, default=[]),
1038 KwargInfo('rcc_extra_arguments', ContainerTypeInfo(list, str), listify=True, default=[]),
1039 KwargInfo('qmlcachegen_extra_arguments', ContainerTypeInfo(list, str), listify=True, default=[]),
1040 KwargInfo('qmltyperegistrar_extra_arguments', ContainerTypeInfo(list, str), listify=True, default=[]),
1041
1042 KwargInfo('generate_qmldir', bool, default=True),
1043 KwargInfo('generate_qmltype', bool, default=True),
1044 KwargInfo('cachegen', bool, default=True),
1045
1046 KwargInfo('dependencies', ContainerTypeInfo(list, (Dependency, ExternalLibrary)), listify=True, default=[]),
1047 INSTALL_DIR_KW,
1048 INSTALL_KW,
1049 DEPENDENCY_METHOD_KW,
1050 KwargInfo('preserve_paths', bool, default=False),
1051 )
1052 def qml_module(self, state: ModuleState, args: T.Tuple[str], kwargs: QmlModuleKwArgs) -> ModuleReturnValue:
1053
1054 self._detect_tools(state, kwargs['method'])
1055 if not self._support_qml_module:
1056 raise MesonException('qt.qml_module is not suppported for this version of Qt')
1057
1058 #Major.Minor(.Patch)
1059 version_re = re.compile(r'^(\d+)\.(\d+)(\.(\d+))?$')
1060 module_name_re = re.compile(_MODULE_NAME_RE)
1061
1062 output: T.List[T.Union[build.CustomTarget, build.GeneratedList]] = []
1063
1064 module_name: str = args[0]
1065 if not module_name_re.fullmatch(module_name):
1066 raise MesonException(f'qml module URI should be in the form Foo.Bar.xxx, got {module_name}')
1067
1068 module_version: str = kwargs['version']
1069 module_version_match = version_re.match(module_version)
1070 if not module_version_match:
1071 raise MesonException(f'qml module version should be in the form Major.Minor, got {module_version}')
1072 module_version_major: str = module_version_match.group(1)
1073 module_version_minor: str = module_version_match.group(2)
1074 #qt ignores .patch version
1075 module_version_short = f'{module_version_major}.{module_version_minor}'
1076
1077 module_prefix_list: T.List[str] = module_name.split('.')
1078 module_prefix: str = os.path.join(*module_prefix_list)
1079 module_prefix_full: str = os.path.join(*(kwargs['resources_prefix'].split('/') + module_prefix_list))
1080
1081 #same format as the one derived from qmltyperegistrar
1082 target_name = re.sub(r'[^A-Za-z0-9]', '_', module_name)
1083
1084 qrc_resouces: T.List[str | build.TargetSources] = []
1085 all_qml: T.List[str | build.TargetSources] = kwargs['qml_sources'] + kwargs['qml_singletons'] + kwargs['qml_internals']
1086 all_qml_files: T.List[File] = self._source_to_files(state, all_qml)
1087 all_qml_basename: T.List[str] = [os.path.basename(p.fname) for p in all_qml_files]
1088
1089 install_dir: str = kwargs['install_dir'] or 'qml'
1090 module_install_dir: str = os.path.join(install_dir, module_prefix)
1091
1092 if len(all_qml) != 0:
1093 qml_qrc_kwargs: GenQrcKwArgs = {
1094 'output': f'{target_name}_qml.qrc',
1095 'sources': all_qml_files,
1096 'aliases': all_qml_basename,
1097 'prefix': module_prefix_full,
1098 }
1099 qml_qrc = self._gen_qrc(state, qml_qrc_kwargs)
1100
1101 if not kwargs['cachegen']:
1102 qrc_resouces.append(qml_qrc)
1103 else:
1104 cachegen_kwargs: GenQmlCachegenKwArgs = {
1105 'target_name': target_name,
1106 'qml_qrc': qml_qrc,
1107 'qml_sources': all_qml,
1108 'module_prefix': module_prefix_full,
1109 'extra_args': kwargs['qmlcachegen_extra_arguments'],
1110 'method': kwargs['method'],
1111 }
1112 output.extend(self._gen_qml_cachegen(state, cachegen_kwargs))
1113
1114 #copy QML files for Qt tools
1115 if kwargs['install']:
1116 self.interpreter.install_data_impl(all_qml_files, module_install_dir,
1117 FileMode(), all_qml_basename, 'devel')
1118
1119 collected_json: T.Optional[T.Union[File, build.CustomTarget]] = None
1120 if kwargs['moc_headers']:
1121 compile_moc_kwargs: MocCompilerKwArgs = {
1122 'sources': [],
1123 'headers': kwargs['moc_headers'],
1124 'extra_args': kwargs['moc_extra_arguments'],
1125 'method': kwargs['method'],
1126 'include_directories': kwargs['include_directories'],
1127 'dependencies': kwargs['dependencies'],
1128 'preserve_paths': kwargs['preserve_paths'],
1129 'output_json': True,
1130 }
1131 moc_output = self._compile_moc_impl(state, compile_moc_kwargs)
1132 output.extend(moc_output)
1133
1134 moc_collect_json_kwargs: MocJsonCollectKwArgs = {
1135 'target_name': target_name,
1136 'moc_json': moc_output,
1137 'method': kwargs['method'],
1138 }
1139 collected_json = self._moc_json_collect(state, moc_collect_json_kwargs)
1140 output.append(collected_json)
1141
1142 typeinfo_file: str = ''
1143 #cmake NO_GENERATE_QMLTYPE disable the whole type registration, not just the .qmltype generation
1144 if kwargs['generate_qmltype']:
1145 qmltyperegistrar_kwargs: GenQmlTypeRegistrarKwArgs = {
1146 'target_name': target_name,
1147 'import_name': module_name,
1148 'major_version': module_version_major,
1149 'minor_version': module_version_minor,
1150 'collected_json': collected_json,
1151 'namespace': kwargs['namespace'],
1152 'generate_qmltype': True,
1153 'extra_args': kwargs['qmltyperegistrar_extra_arguments'],
1154 'typeinfo': kwargs['typeinfo'],
1155 'method': kwargs['method'],
1156 'install': kwargs['install'],
1157 'install_dir': module_install_dir,
1158 }
1159 type_registrar_output = self._qml_type_registrar(state, qmltyperegistrar_kwargs)
1160 output.append(type_registrar_output)
1161 if len(type_registrar_output.get_outputs()) == 2:
1162 typeinfo_file = type_registrar_output.get_outputs()[1]
1163
1164 if kwargs['generate_qmldir']:
1165 qmldir_kwargs: GenQmldirKwArgs = {
1166 'output': f'{target_name}_qmldir',
1167 'module_name': module_name,
1168 'module_version': module_version_short,
1169 'qml_sources': kwargs['qml_sources'],
1170 'qml_singletons': kwargs['qml_singletons'],
1171 'qml_internals': kwargs['qml_internals'],
1172 'imports': kwargs['imports'],
1173 'optional_imports': kwargs['optional_imports'],
1174 'default_imports': kwargs['default_imports'],
1175 'depends_imports': kwargs['depends_imports'],
1176 'designer_supported': kwargs['designer_supported'],
1177 'typeinfo': typeinfo_file,
1178 'module_prefix': module_prefix_full,
1179 }
1180 qmldir_file: File = self._gen_qmldir(state, qmldir_kwargs)
1181
1182 qmldir_qrc_kwargs: GenQrcKwArgs = {
1183 'output': f'{target_name}_qmldir.qrc',
1184 'sources': self._source_to_files(state, [qmldir_file]),
1185 'aliases': ['qmldir'],
1186 'prefix': module_prefix_full,
1187 }
1188 qrc_resouces.append(self._gen_qrc(state, qmldir_qrc_kwargs))
1189
1190 if kwargs['install']:
1191 self.interpreter.install_data_impl([qmldir_file], module_install_dir,
1192 FileMode(), ['qmldir'], 'devel')
1193
1194 if qrc_resouces:
1195 compile_resource_kwargs: ResourceCompilerKwArgs = {
1196 'name': target_name,
1197 'sources': qrc_resouces,
1198 'extra_args': kwargs['rcc_extra_arguments'],
1199 'method': kwargs['method'],
1200 }
1201 output.extend(self._compile_resources_impl(state, compile_resource_kwargs))
1202
1203 return ModuleReturnValue(output, [output])