Debian Codegraph @

mesonbuild/dependencies/ui.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2013-2017 The Meson development team
3
4 # This file contains the detection logic for external dependencies that
5 # are UI-related.
6 from __future__ import annotations
7
8 import os
9 import re
10 import subprocess
11 import typing as T
12
13 from .. import mlog
14 from .. import mesonlib
15 from ..mesonlib import (
16 Popen_safe, version_compare_many
17 )
18
19 from .base import DependencyCandidate, DependencyException, DependencyMethods, DependencyTypeName, SystemDependency
20 from .cmake import CMakeDependency
21 from .configtool import ConfigToolDependency
22 from .detect import packages
23 from .factory import DependencyFactory
24
25 if T.TYPE_CHECKING:
26 from ..environment import Environment
27 from .base import DependencyObjectKWs
28
29
30 class GLDependencySystem(SystemDependency):
31 def __init__(self, name: str, environment: 'Environment', kwargs: DependencyObjectKWs) -> None:
32 super().__init__(name, environment, kwargs)
33
34 if self.env.machines[self.for_machine].is_darwin():
35 self.is_found = True
36 # FIXME: Use AppleFrameworks dependency
37 self.link_args = ['-framework', 'OpenGL']
38 # FIXME: Detect version using self.clib_compiler
39 return
40 elif self.env.machines[self.for_machine].is_windows():
41 self.is_found = True
42 # FIXME: Use self.clib_compiler.find_library()
43 self.link_args = ['-lopengl32']
44 # FIXME: Detect version using self.clib_compiler
45 return
46 else:
47 links = self.clib_compiler.find_library('GL', [])
48 has_header = self.clib_compiler.has_header('GL/gl.h', '')[0]
49 if links and has_header:
50 self.is_found = True
51 self.link_args = links
52 elif links:
53 raise DependencyException('Found GL runtime library but no development header files')
54
55 class GnuStepDependency(ConfigToolDependency):
56
57 tools = ['gnustep-config']
58 tool_name = 'gnustep-config'
59
60 def __init__(self, name: str, environment: 'Environment', kwargs: DependencyObjectKWs) -> None:
61 kwargs['language'] = 'objc'
62 super().__init__(name, environment, kwargs)
63 if not self.is_found:
64 return
65 self.modules = kwargs.get('modules', [])
66 self.compile_args = self.filter_args(
67 self.get_config_value(['--objc-flags'], 'compile_args'))
68 self.link_args = self.weird_filter(self.get_config_value(
69 ['--gui-libs' if 'gui' in self.modules else '--base-libs'],
70 'link_args'))
71
72 def find_config(self, versions: T.Optional[T.List[str]] = None, returncode: int = 0, exclude_paths: T.Optional[T.List[str]] = None) -> T.Tuple[T.Optional[T.List[str]], T.Optional[str]]:
73 tool = [self.tools[0]]
74 try:
75 p, out = Popen_safe(tool + ['--help'])[:2]
76 except (FileNotFoundError, PermissionError):
77 return (None, None)
78 if p.returncode != returncode:
79 return (None, None)
80 self.config = tool
81 found_version = self.detect_version()
82 if versions and not version_compare_many(found_version, versions)[0]:
83 return (None, found_version)
84
85 return (tool, found_version)
86
87 @staticmethod
88 def weird_filter(elems: T.List[str]) -> T.List[str]:
89 """When building packages, the output of the enclosing Make is
90 sometimes mixed among the subprocess output. I have no idea why. As a
91 hack filter out everything that is not a flag.
92 """
93 return [e for e in elems if e.startswith('-')]
94
95 @staticmethod
96 def filter_args(args: T.List[str]) -> T.List[str]:
97 """gnustep-config returns a bunch of garbage args such as -O2 and so
98 on. Drop everything that is not needed.
99 """
100 result = []
101 for f in args:
102 if f.startswith('-D') \
103 or f.startswith('-f') \
104 or f.startswith('-I') \
105 or f == '-pthread' \
106 or (f.startswith('-W') and not f == '-Wall'):
107 result.append(f)
108 return result
109
110 def detect_version(self) -> str:
111 gmake = self.get_config_value(['--variable=GNUMAKE'], 'variable')[0]
112 makefile_dir = self.get_config_value(['--variable=GNUSTEP_MAKEFILES'], 'variable')[0]
113 # This Makefile has the GNUStep version set
114 base_make = os.path.join(makefile_dir, 'Additional', 'base.make')
115 # Print the Makefile variable passed as the argument. For instance, if
116 # you run the make target `print-SOME_VARIABLE`, this will print the
117 # value of the variable `SOME_VARIABLE`.
118 printver = "print-%:\n\t@echo '$($*)'"
119 env = os.environ.copy()
120 # See base.make to understand why this is set
121 env['FOUNDATION_LIB'] = 'gnu'
122 p, o, e = Popen_safe([gmake, '-f', '-', '-f', base_make,
123 'print-GNUSTEP_BASE_VERSION'],
124 env=env, write=printver, stdin=subprocess.PIPE)
125 version = o.strip()
126 if not version:
127 mlog.debug("Couldn't detect GNUStep version, falling back to '1'")
128 # Fallback to setting some 1.x version
129 version = '1'
130 return version
131
132 packages['gnustep'] = GnuStepDependency
133
134
135 class SDL2DependencyConfigTool(ConfigToolDependency):
136
137 tools = ['sdl2-config']
138 tool_name = 'sdl2-config'
139
140 def __init__(self, name: str, environment: 'Environment', kwargs: DependencyObjectKWs):
141 super().__init__(name, environment, kwargs)
142 if not self.is_found:
143 return
144 self.compile_args = self.get_config_value(['--cflags'], 'compile_args')
145 self.link_args = self.get_config_value(['--libs'], 'link_args')
146
147
148 class WxDependency(ConfigToolDependency):
149
150 tools = ['wx-config-3.0', 'wx-config-3.1', 'wx-config', 'wx-config-gtk3']
151 tool_name = 'wx-config'
152
153 # name is intentionally ignored to maintain existing capitalization,
154 # but is needed for polymorphism
155 def __init__(self, name: str, environment: 'Environment', kwargs: DependencyObjectKWs):
156 kwargs['language'] = 'cpp'
157 super().__init__('WxWidgets', environment, kwargs)
158 if not self.is_found:
159 return
160 self.requested_modules = kwargs.get('modules', [])
161
162 extra_args = []
163 if self.static:
164 extra_args.append('--static=yes')
165
166 # Check to make sure static is going to work
167 err = Popen_safe(self.config + extra_args)[2]
168 if 'No config found to match' in err:
169 mlog.debug('WxWidgets is missing static libraries.')
170 self.is_found = False
171 return
172
173 # wx-config seems to have a cflags as well but since it requires C++,
174 # this should be good, at least for now.
175 self.compile_args = self.get_config_value(['--cxxflags'] + extra_args + self.requested_modules, 'compile_args')
176 self.link_args = self.get_config_value(['--libs'] + extra_args + self.requested_modules, 'link_args')
177
178 packages['wxwidgets'] = WxDependency
179
180 class VulkanDependencySystem(SystemDependency):
181
182 def __init__(self, name: str, environment: 'Environment', kwargs: DependencyObjectKWs) -> None:
183 super().__init__(name, environment, kwargs)
184
185 self.vulkan_sdk = os.environ.get('VULKAN_SDK', os.environ.get('VK_SDK_PATH'))
186 if self.vulkan_sdk and not os.path.isabs(self.vulkan_sdk):
187 raise DependencyException('VULKAN_SDK must be an absolute path.')
188
189 if self.vulkan_sdk:
190 # TODO: this config might not work on some platforms, fix bugs as reported
191 # we should at least detect other 64-bit platforms (e.g. armv8)
192 lib_name = 'vulkan'
193 lib_dir = 'lib'
194 inc_dir = 'include'
195 if self.env.machines[self.for_machine].is_windows():
196 lib_name = 'vulkan-1'
197 lib_dir = ''
198 inc_dir = 'Include'
199 build_cpu = self.env.machines.build.cpu_family
200 host_cpu = self.env.machines.host.cpu_family
201 if build_cpu == 'x86_64':
202 if host_cpu == build_cpu:
203 lib_dir = 'Lib'
204 elif host_cpu == 'aarch64':
205 lib_dir = 'Lib-ARM64'
206 elif host_cpu == 'x86':
207 lib_dir = 'Lib32'
208 elif build_cpu == 'aarch64':
209 if host_cpu == build_cpu:
210 lib_dir = 'Lib'
211 elif host_cpu == 'x86_64':
212 lib_dir = 'Lib-x64'
213 elif host_cpu == 'x86':
214 lib_dir = 'Lib32'
215 elif build_cpu == 'x86':
216 if host_cpu == build_cpu:
217 lib_dir = 'Lib32'
218 if host_cpu == 'aarch64':
219 lib_dir = 'Lib-ARM64'
220 elif host_cpu == 'x86_64':
221 lib_dir = 'Lib'
222
223 if lib_dir == '':
224 raise DependencyException(f'Target architecture \'{host_cpu}\' is not supported for this Vulkan SDK.')
225
226 # make sure header and lib are valid
227 inc_path = os.path.join(self.vulkan_sdk, inc_dir)
228 header = os.path.join(inc_path, 'vulkan', 'vulkan.h')
229 lib_path = os.path.join(self.vulkan_sdk, lib_dir)
230 find_lib = self.clib_compiler.find_library(lib_name, [lib_path])
231
232 if not find_lib:
233 raise DependencyException('VULKAN_SDK point to invalid directory (no lib)')
234
235 if not os.path.isfile(header):
236 raise DependencyException('VULKAN_SDK point to invalid directory (no include)')
237
238 # XXX: this is very odd, and may deserve being removed
239 self.type_name = DependencyTypeName('vulkan_sdk')
240 self.is_found = True
241 self.compile_args.append('-I' + inc_path)
242 self.link_args.append('-L' + lib_path)
243 self.link_args.append('-l' + lib_name)
244 else:
245 # simply try to guess it, usually works on linux
246 libs = self.clib_compiler.find_library('vulkan', [])
247 if libs is not None and self.clib_compiler.has_header('vulkan/vulkan.h', '', disable_cache=True)[0]:
248 self.is_found = True
249 for lib in libs:
250 self.link_args.append(lib)
251
252 if self.is_found:
253 try:
254 # VK_VERSION_* is deprecated and replaced by VK_API_VERSION_*. We'll continue to use the old one in
255 # order to support older Vulkan versions that don't have the new one yet, but we might have to update
256 # this code to also check VK_API_VERSION in the future if they decide to drop the old one at some point.
257 components = [str(self.clib_compiler.compute_int(f'VK_VERSION_{c}(VK_HEADER_VERSION_COMPLETE)',
258 low=0, high=None, guess=e,
259 prefix='#include <vulkan/vulkan.h>',
260 extra_args=self.compile_args,
261 dependencies=None))
262 # list containing vulkan version components and their expected value
263 for c, e in [('MAJOR', 1), ('MINOR', 3), ('PATCH', None)]]
264 self.version = '.'.join(components)
265 except mesonlib.EnvironmentException:
266 if self.vulkan_sdk:
267 # fall back to heuristics: detect version number in path
268 # matches the default install path on Windows
269 match = re.search(rf'VulkanSDK{re.escape(os.path.sep)}([0-9]+(?:\.[0-9]+)+)', self.vulkan_sdk)
270 if match:
271 self.version = match.group(1)
272 else:
273 mlog.warning(f'Environment variable VULKAN_SDK={self.vulkan_sdk} is present, but Vulkan version could not be extracted.')
274
275 packages['gl'] = gl_factory = DependencyFactory(
276 'gl',
277 [DependencyMethods.PKGCONFIG, DependencyMethods.SYSTEM],
278 system=GLDependencySystem,
279 )
280
281 packages['sdl2'] = sdl2_factory = DependencyFactory(
282 'sdl2',
283 [DependencyMethods.PKGCONFIG, DependencyMethods.CONFIG_TOOL, DependencyMethods.EXTRAFRAMEWORK, DependencyMethods.CMAKE],
284 configtool=SDL2DependencyConfigTool,
285 cmake=DependencyCandidate.from_dependency('SDL2', CMakeDependency),
286 )
287
288 packages['vulkan'] = vulkan_factory = DependencyFactory(
289 'vulkan',
290 [DependencyMethods.PKGCONFIG, DependencyMethods.SYSTEM],
291 system=VulkanDependencySystem,
292 )