Debian Codegraph @

mesonbuild/dependencies/qt.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2013-2017 The Meson development team
3 # Copyright © 2021-2025 Intel Corporation
4
5 from __future__ import annotations
6
7 """Dependency finders for the Qt framework."""
8
9 import abc
10 import re
11 import os
12 from pathlib import Path
13 import typing as T
14
15 from .base import DependencyException, DependencyMethods
16 from .configtool import ConfigToolDependency
17 from .detect import packages
18 from .framework import ExtraFrameworkDependency
19 from .pkgconfig import PkgConfigDependency
20 from .factory import DependencyFactory
21 from .. import mlog
22 from .. import mesonlib
23
24 if T.TYPE_CHECKING:
25 from ..compilers.compilers import Compiler
26 from ..envconfig import MachineInfo
27 from ..environment import Environment
28 from ..dependencies import MissingCompiler
29 from .base import DependencyObjectKWs
30
31
32 def _qt_get_private_includes(mod_inc_dir: str, module: str, mod_version: str) -> T.List[str]:
33 # usually Qt5 puts private headers in /QT_INSTALL_HEADERS/module/VERSION/module/private
34 # except for at least QtWebkit and Enginio where the module version doesn't match Qt version
35 # as an example with Qt 5.10.1 on linux you would get:
36 # /usr/include/qt5/QtCore/5.10.1/QtCore/private/
37 # /usr/include/qt5/QtWidgets/5.10.1/QtWidgets/private/
38 # /usr/include/qt5/QtWebKit/5.212.0/QtWebKit/private/
39
40 # on Qt4 when available private folder is directly in module folder
41 # like /usr/include/QtCore/private/
42 if int(mod_version.split('.')[0]) < 5:
43 return []
44
45 private_dir = os.path.join(mod_inc_dir, mod_version)
46 # fallback, let's try to find a directory with the latest version
47 if os.path.isdir(mod_inc_dir) and not os.path.exists(private_dir):
48 dirs = [filename for filename in os.listdir(mod_inc_dir)
49 if os.path.isdir(os.path.join(mod_inc_dir, filename))]
50
51 for dirname in sorted(dirs, reverse=True):
52 if len(dirname.split('.')) == 3:
53 private_dir = dirname
54 break
55 return [private_dir, Path(private_dir, f'Qt{module}').as_posix()]
56
57
58 def get_qmake_host_bins(qvars: T.Dict[str, str]) -> str:
59 # Prefer QT_HOST_BINS (qt5, correct for cross and native compiling)
60 # but fall back to QT_INSTALL_BINS (qt4)
61 if 'QT_HOST_BINS' in qvars:
62 return qvars['QT_HOST_BINS']
63 return qvars['QT_INSTALL_BINS']
64
65
66 def get_qmake_host_libexecs(qvars: T.Dict[str, str]) -> T.Optional[str]:
67 if 'QT_HOST_LIBEXECS' in qvars:
68 return qvars['QT_HOST_LIBEXECS']
69 return qvars.get('QT_INSTALL_LIBEXECS')
70
71
72 def _get_modules_lib_suffix(version: str, info: 'MachineInfo', is_debug: bool) -> str:
73 """Get the module suffix based on platform and debug type."""
74 suffix = ''
75 if info.is_windows():
76 if is_debug:
77 suffix += 'd'
78 if version.startswith('4'):
79 suffix += '4'
80 if info.is_darwin():
81 if is_debug:
82 suffix += '_debug'
83 if mesonlib.version_compare(version, '>= 5.14.0'):
84 if info.is_android():
85 if info.cpu_family == 'x86':
86 suffix += '_x86'
87 elif info.cpu_family == 'x86_64':
88 suffix += '_x86_64'
89 elif info.cpu_family == 'arm':
90 suffix += '_armeabi-v7a'
91 elif info.cpu_family == 'aarch64':
92 suffix += '_arm64-v8a'
93 else:
94 mlog.warning(f'Android target arch "{info.cpu_family}"" for Qt5 is unknown, '
95 'module detection may not work')
96 return suffix
97
98
99 class QtExtraFrameworkDependency(ExtraFrameworkDependency):
100 def __init__(self, name: str, env: 'Environment', kwargs: DependencyObjectKWs, qvars: T.Dict[str, str]):
101 super().__init__(name, env, kwargs)
102 self.mod_name = name[2:]
103 self.qt_extra_include_directory = qvars['QT_INSTALL_HEADERS']
104
105 def get_compile_args(self, with_private_headers: bool = False, qt_version: str = "0") -> T.List[str]:
106 if self.found():
107 mod_inc_dir = os.path.join(self.framework_path, 'Headers')
108 args = ['-I' + mod_inc_dir]
109 if with_private_headers:
110 args += ['-I' + dirname for dirname in _qt_get_private_includes(mod_inc_dir, self.mod_name, qt_version)]
111 if self.qt_extra_include_directory:
112 args += ['-I' + self.qt_extra_include_directory]
113 return args
114 return []
115
116
117 class _QtBase:
118
119 """Mixin class for shared components between PkgConfig and Qmake."""
120
121 link_args: T.List[str]
122 clib_compiler: T.Union['MissingCompiler', 'Compiler']
123 env: 'Environment'
124 libexecdir: T.Optional[str] = None
125 version: str
126
127 def __init__(self, name: str, kwargs: DependencyObjectKWs):
128 self.name = name
129 self.qtname = name.capitalize()
130 self.qtver = name[-1]
131 if self.qtver == "4":
132 self.qtpkgname = 'Qt'
133 else:
134 self.qtpkgname = self.qtname
135
136 self.private_headers = kwargs.get('private_headers', False)
137
138 self.requested_modules = kwargs.get('modules', [])
139 if not self.requested_modules:
140 raise DependencyException('No ' + self.qtname + ' modules specified.')
141
142 self.qtmain = kwargs.get('main', False)
143 if not isinstance(self.qtmain, bool):
144 raise DependencyException('"main" argument must be a boolean')
145
146 def _link_with_qt_winmain(self, is_debug: bool, libdir: T.Union[str, T.List[str]]) -> bool:
147 libdir = mesonlib.listify(libdir) # TODO: shouldn't be necessary
148 base_name = self.get_qt_winmain_base_name(is_debug)
149 qt_winmain = self.clib_compiler.find_library(base_name, libdir)
150 if qt_winmain:
151 self.link_args.append(qt_winmain[0])
152 return True
153 return False
154
155 def get_qt_winmain_base_name(self, is_debug: bool) -> str:
156 return 'qtmaind' if is_debug else 'qtmain'
157
158 def get_exe_args(self, compiler: 'Compiler') -> T.List[str]:
159 # Originally this was -fPIE but nowadays the default
160 # for upstream and distros seems to be -reduce-relocations
161 # which requires -fPIC. This may cause a performance
162 # penalty when using self-built Qt or on platforms
163 # where -fPIC is not required. If this is an issue
164 # for you, patches are welcome.
165 return compiler.get_pic_args()
166
167 def log_details(self) -> str:
168 return f'modules: {", ".join(sorted(self.requested_modules))}'
169
170 def _get_common_defines(self) -> T.List[str]:
171 is_debug = self.env.coredata.optstore.get_value_for('debug')
172 return ['-DQT_DEBUG' if is_debug else '-DQT_NO_DEBUG']
173
174 class QtPkgConfigDependency(_QtBase, PkgConfigDependency, metaclass=mesonlib.SimpleABC):
175
176 """Specialization of the PkgConfigDependency for Qt."""
177
178 def __init__(self, name: str, env: 'Environment', kwargs: DependencyObjectKWs):
179 _QtBase.__init__(self, name, kwargs)
180
181 # Always use QtCore as the "main" dependency, since it has the extra
182 # pkg-config variables that a user would expect to get. If "Core" is
183 # not a requested module, delete the compile and link arguments to
184 # avoid linking with something they didn't ask for
185 PkgConfigDependency.__init__(self, self.qtpkgname + 'Core', env, kwargs)
186 if 'Core' not in self.requested_modules:
187 self.compile_args = []
188 self.link_args = []
189
190 for m in self.requested_modules:
191 mod = PkgConfigDependency(self.qtpkgname + m, self.env, kwargs)
192 if not mod.found():
193 self.is_found = False
194 return
195 if self.private_headers:
196 qt_inc_dir = mod.get_variable(pkgconfig='includedir')
197 mod_private_dir = os.path.join(qt_inc_dir, 'Qt' + m)
198 if not os.path.isdir(mod_private_dir):
199 if self.env.machines[self.for_machine].is_darwin():
200 # On macOS Qt is conventionally shipped as a framework
201 # (e.g. Homebrew's qt@6). pkg-config 'includedir' is
202 # just the prefix include dir and contains no Qt
203 # headers; both public and private headers live under
204 # <libdir>/Qt<Module>.framework/Headers.
205 libdir = mod.get_variable(pkgconfig='libdir', default_value='')
206 framework_inc = os.path.join(libdir, f'Qt{m}.framework', 'Headers')
207 if libdir and os.path.isdir(framework_inc):
208 mod_private_dir = framework_inc
209 if not os.path.isdir(mod_private_dir):
210 # At least some versions of homebrew don't seem to set this
211 # up correctly. /usr/local/opt/qt/include/Qt + m_name is a
212 # symlink to /usr/local/opt/qt/include, but the pkg-config
213 # file points to /usr/local/Cellar/qt/x.y.z/Headers/, and
214 # the Qt + m_name there is not a symlink, it's a file
215 mod_private_dir = qt_inc_dir
216 mod_private_inc = _qt_get_private_includes(mod_private_dir, m, mod.version)
217 for directory in mod_private_inc:
218 mod.compile_args.append('-I' + directory)
219 self._add_sub_dependency([lambda: mod])
220
221 if self.env.machines[self.for_machine].is_windows() and self.qtmain:
222 # Check if we link with debug binaries
223 debug_lib_name = self.qtpkgname + 'Core' + _get_modules_lib_suffix(self.version, self.env.machines[self.for_machine], True)
224 is_debug = False
225 for arg in self.get_link_args():
226 if arg == f'-l{debug_lib_name}' or arg.endswith(f'{debug_lib_name}.lib') or arg.endswith(f'{debug_lib_name}.a'):
227 is_debug = True
228 break
229 libdir = self.get_variable(pkgconfig='libdir')
230 if not self._link_with_qt_winmain(is_debug, libdir):
231 self.is_found = False
232 return
233
234 self.bindir = self.get_pkgconfig_host_bins(self)
235 if not self.bindir:
236 # If exec_prefix is not defined, the pkg-config file is broken
237 prefix = self.get_variable(pkgconfig='exec_prefix')
238 if prefix:
239 self.bindir = os.path.join(prefix, 'bin')
240
241 self.libexecdir = self.get_pkgconfig_host_libexecs(self)
242
243 self.compile_args += self._get_common_defines()
244
245 @staticmethod
246 @abc.abstractmethod
247 def get_pkgconfig_host_bins(core: PkgConfigDependency) -> T.Optional[str]:
248 pass
249
250 @staticmethod
251 @abc.abstractmethod
252 def get_pkgconfig_host_libexecs(core: PkgConfigDependency) -> T.Optional[str]:
253 pass
254
255 @abc.abstractmethod
256 def get_private_includes(self, mod_inc_dir: str, module: str) -> T.List[str]:
257 pass
258
259 def log_info(self) -> str:
260 return 'pkg-config'
261
262
263 class QmakeQtDependency(_QtBase, ConfigToolDependency, metaclass=mesonlib.SimpleABC):
264
265 """Find Qt using Qmake as a config-tool."""
266
267 version: str
268 version_arg = '-v'
269
270 def __init__(self, name: str, env: 'Environment', kwargs: DependencyObjectKWs):
271 _QtBase.__init__(self, name, kwargs)
272 self.tool_name = f'qmake{self.qtver}'
273 self.tools = [f'qmake{self.qtver}', f'qmake-{self.name}', 'qmake']
274
275 # Add additional constraints that the Qt version is met, but preserve
276 # any version requirements the user has set as well. For example, if Qt5
277 # is requested, add "">= 5, < 6", but if the user has ">= 5.6", don't
278 # lose that.
279 kwargs = kwargs.copy()
280 _vers = kwargs.get('version', [])
281 _vers.extend([f'>= {self.qtver}', f'< {int(self.qtver) + 1}'])
282 kwargs['version'] = _vers
283
284 ConfigToolDependency.__init__(self, name, env, kwargs)
285 if not self.found():
286 return
287
288 self.compile_args += self._get_common_defines()
289
290 # Query library path, header path, and binary path
291 stdo = self.get_config_value(['-query'], 'args')
292 qvars: T.Dict[str, str] = {}
293 for line in stdo:
294 line = line.strip()
295 if line == '':
296 continue
297 k, v = line.split(':', 1)
298 qvars[k] = v
299 # Qt on macOS uses a framework, but Qt for iOS/tvOS does not
300 xspec = qvars.get('QMAKE_XSPEC', '')
301 if self.env.machines.host.is_darwin() and not any(s in xspec for s in ['ios', 'tvos']):
302 mlog.debug("Building for macOS, looking for framework")
303 self._framework_detect(qvars, self.requested_modules, kwargs)
304 # Sometimes Qt is built not as a framework (for instance, when using conan pkg manager)
305 # skip and fall back to normal procedure then
306 if self.is_found:
307 return
308 else:
309 mlog.debug("Building for macOS, couldn't find framework, falling back to library search")
310 incdir = qvars['QT_INSTALL_HEADERS']
311 self.compile_args.append('-I' + incdir)
312 libdir = qvars['QT_INSTALL_LIBS']
313 # Used by qt.compilers_detect()
314 self.bindir = get_qmake_host_bins(qvars)
315 self.libexecdir = get_qmake_host_libexecs(qvars)
316
317 # Use the buildtype by default, but look at the b_vscrt option if the
318 # compiler supports it.
319 is_debug = self.env.coredata.optstore.get_value_for('buildtype') == 'debug'
320 if 'b_vscrt' in self.env.coredata.optstore:
321 if self.env.coredata.optstore.get_value_for('b_vscrt') in {'mdd', 'mtd'}:
322 is_debug = True
323 modules_lib_suffix = _get_modules_lib_suffix(self.version, self.env.machines[self.for_machine], is_debug)
324
325 for module in self.requested_modules:
326 mincdir = Path(incdir, f'Qt{module}').as_posix()
327 self.compile_args.append('-I' + mincdir)
328
329 if module == 'QuickTest':
330 define_base = 'QMLTEST'
331 elif module == 'Test':
332 define_base = 'TESTLIB'
333 else:
334 define_base = module.upper()
335 self.compile_args.append(f'-DQT_{define_base}_LIB')
336
337 if self.private_headers:
338 priv_inc = self.get_private_includes(mincdir, module)
339 for directory in priv_inc:
340 self.compile_args.append('-I' + directory)
341 libfiles = self.clib_compiler.find_library(
342 self.qtpkgname + module + modules_lib_suffix,
343 mesonlib.listify(libdir)) # TODO: shouldn't be necessary
344 if libfiles:
345 libfile = libfiles[0]
346 else:
347 mlog.log("Could not find:", module,
348 self.qtpkgname + module + modules_lib_suffix,
349 'in', libdir)
350 self.is_found = False
351 break
352 self.link_args.append(libfile)
353
354 if self.env.machines[self.for_machine].is_windows() and self.qtmain:
355 if not self._link_with_qt_winmain(is_debug, libdir):
356 self.is_found = False
357
358 def _sanitize_version(self, version: str) -> str:
359 m = re.search(rf'({self.qtver}(\.\d+)+)', version)
360 if m:
361 return m.group(0).rstrip('.')
362 return version
363
364 def get_variable_args(self, variable_name: str) -> T.List[str]:
365 return ['-query', f'{variable_name}']
366
367 @abc.abstractmethod
368 def get_private_includes(self, mod_inc_dir: str, module: str) -> T.List[str]:
369 pass
370
371 def _framework_detect(self, qvars: T.Dict[str, str], modules: T.List[str], kwargs: DependencyObjectKWs) -> None:
372 libdir = qvars['QT_INSTALL_LIBS']
373
374 # ExtraFrameworkDependency doesn't support any methods
375 fw_kwargs = kwargs.copy()
376 fw_kwargs.pop('method')
377 fw_kwargs['paths'] = [libdir]
378 fw_kwargs['language'] = self.language
379
380 for m in modules:
381 fname = 'Qt' + m
382 mlog.debug('Looking for qt framework ' + fname)
383 fwdep = QtExtraFrameworkDependency(fname, self.env, fw_kwargs, qvars)
384 if fwdep.found():
385 self.compile_args.append('-F' + libdir)
386 self.compile_args += fwdep.get_compile_args(with_private_headers=self.private_headers,
387 qt_version=self.version)
388 self.link_args += fwdep.get_link_args()
389 else:
390 self.is_found = False
391 break
392 else:
393 self.is_found = True
394 # Used by self.compilers_detect()
395 self.bindir = get_qmake_host_bins(qvars)
396 self.libexecdir = get_qmake_host_libexecs(qvars)
397
398 def log_info(self) -> str:
399 return 'qmake'
400
401
402 class Qt6WinMainMixin:
403
404 def get_qt_winmain_base_name(self, is_debug: bool) -> str:
405 return 'Qt6EntryPointd' if is_debug else 'Qt6EntryPoint'
406
407
408 class Qt4ConfigToolDependency(QmakeQtDependency):
409
410 def get_private_includes(self, mod_inc_dir: str, module: str) -> T.List[str]:
411 return []
412
413
414 class Qt5ConfigToolDependency(QmakeQtDependency):
415
416 def get_private_includes(self, mod_inc_dir: str, module: str) -> T.List[str]:
417 return _qt_get_private_includes(mod_inc_dir, module, self.version)
418
419
420 class Qt6ConfigToolDependency(Qt6WinMainMixin, QmakeQtDependency):
421
422 def get_private_includes(self, mod_inc_dir: str, module: str) -> T.List[str]:
423 return _qt_get_private_includes(mod_inc_dir, module, self.version)
424
425
426 class Qt4PkgConfigDependency(QtPkgConfigDependency):
427
428 @staticmethod
429 def get_pkgconfig_host_bins(core: PkgConfigDependency) -> T.Optional[str]:
430 # Only return one bins dir, because the tools are generally all in one
431 # directory for Qt4, in Qt5, they must all be in one directory. Return
432 # the first one found among the bin variables, in case one tool is not
433 # configured to be built.
434 applications = ['moc', 'uic', 'rcc', 'lupdate', 'lrelease']
435 for application in applications:
436 try:
437 return os.path.dirname(core.get_variable(pkgconfig=f'{application}_location'))
438 except mesonlib.MesonException:
439 pass
440 return None
441
442 def get_private_includes(self, mod_inc_dir: str, module: str) -> T.List[str]:
443 return []
444
445 @staticmethod
446 def get_pkgconfig_host_libexecs(core: PkgConfigDependency) -> str:
447 return None
448
449
450 class Qt5PkgConfigDependency(QtPkgConfigDependency):
451
452 @staticmethod
453 def get_pkgconfig_host_bins(core: PkgConfigDependency) -> str:
454 return core.get_variable(pkgconfig='host_bins')
455
456 @staticmethod
457 def get_pkgconfig_host_libexecs(core: PkgConfigDependency) -> str:
458 return None
459
460 def get_private_includes(self, mod_inc_dir: str, module: str) -> T.List[str]:
461 return _qt_get_private_includes(mod_inc_dir, module, self.version)
462
463
464 class Qt6PkgConfigDependency(Qt6WinMainMixin, QtPkgConfigDependency):
465
466 def __init__(self, name: str, env: 'Environment', kwargs: DependencyObjectKWs):
467 super().__init__(name, env, kwargs)
468 if not self.libexecdir:
469 mlog.debug(f'detected Qt6 {self.version} pkg-config dependency does not '
470 'have proper tools support, ignoring')
471 self.is_found = False
472
473 @staticmethod
474 def get_pkgconfig_host_bins(core: PkgConfigDependency) -> str:
475 return core.get_variable(pkgconfig='bindir')
476
477 @staticmethod
478 def get_pkgconfig_host_libexecs(core: PkgConfigDependency) -> str:
479 # Qt6 pkg-config for Qt defines libexecdir from 6.3+
480 return core.get_variable(pkgconfig='libexecdir')
481
482 def get_private_includes(self, mod_inc_dir: str, module: str) -> T.List[str]:
483 return _qt_get_private_includes(mod_inc_dir, module, self.version)
484
485
486 packages['qt4'] = qt4_factory = DependencyFactory(
487 'qt4',
488 [DependencyMethods.PKGCONFIG, DependencyMethods.CONFIG_TOOL],
489 pkgconfig=Qt4PkgConfigDependency,
490 configtool=Qt4ConfigToolDependency,
491 )
492
493 packages['qt5'] = qt5_factory = DependencyFactory(
494 'qt5',
495 [DependencyMethods.PKGCONFIG, DependencyMethods.CONFIG_TOOL],
496 pkgconfig=Qt5PkgConfigDependency,
497 configtool=Qt5ConfigToolDependency,
498 )
499
500 packages['qt6'] = qt6_factory = DependencyFactory(
501 'qt6',
502 [DependencyMethods.PKGCONFIG, DependencyMethods.CONFIG_TOOL],
503 pkgconfig=Qt6PkgConfigDependency,
504 configtool=Qt6ConfigToolDependency,
505 )