ui.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. # Copyright 2013-2017 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. # This file contains the detection logic for external dependencies that
  12. # are UI-related.
  13. import os
  14. import re
  15. import shutil
  16. import subprocess
  17. from collections import OrderedDict
  18. from .. import mlog
  19. from .. import mesonlib
  20. from ..mesonlib import MesonException, Popen_safe, version_compare
  21. from ..environment import for_windows
  22. from .base import DependencyException, DependencyMethods
  23. from .base import ExternalDependency, ExternalProgram
  24. from .base import ExtraFrameworkDependency, PkgConfigDependency
  25. class GLDependency(ExternalDependency):
  26. def __init__(self, environment, kwargs):
  27. super().__init__('gl', environment, None, kwargs)
  28. if DependencyMethods.PKGCONFIG in self.methods:
  29. try:
  30. pcdep = PkgConfigDependency('gl', environment, kwargs)
  31. if pcdep.found():
  32. self.type_name = 'pkgconfig'
  33. self.is_found = True
  34. self.compile_args = pcdep.get_compile_args()
  35. self.link_args = pcdep.get_link_args()
  36. self.version = pcdep.get_version()
  37. return
  38. except Exception:
  39. pass
  40. if DependencyMethods.SYSTEM in self.methods:
  41. if mesonlib.is_osx():
  42. self.is_found = True
  43. # FIXME: Use AppleFrameworks dependency
  44. self.link_args = ['-framework', 'OpenGL']
  45. # FIXME: Detect version using self.compiler
  46. self.version = '1'
  47. return
  48. if mesonlib.is_windows():
  49. self.is_found = True
  50. # FIXME: Use self.compiler.find_library()
  51. self.link_args = ['-lopengl32']
  52. # FIXME: Detect version using self.compiler
  53. self.version = '1'
  54. return
  55. def get_methods(self):
  56. if mesonlib.is_osx() or mesonlib.is_windows():
  57. return [DependencyMethods.PKGCONFIG, DependencyMethods.SYSTEM]
  58. else:
  59. return [DependencyMethods.PKGCONFIG]
  60. class GnuStepDependency(ExternalDependency):
  61. def __init__(self, environment, kwargs):
  62. super().__init__('gnustep', environment, 'objc', kwargs)
  63. self.modules = kwargs.get('modules', [])
  64. self.detect()
  65. def detect(self):
  66. self.confprog = 'gnustep-config'
  67. try:
  68. gp = Popen_safe([self.confprog, '--help'])[0]
  69. except (FileNotFoundError, PermissionError):
  70. mlog.log('Dependency GnuStep found:', mlog.red('NO'), '(no gnustep-config)')
  71. return
  72. if gp.returncode != 0:
  73. mlog.log('Dependency GnuStep found:', mlog.red('NO'))
  74. return
  75. if 'gui' in self.modules:
  76. arg = '--gui-libs'
  77. else:
  78. arg = '--base-libs'
  79. fp, flagtxt, flagerr = Popen_safe([self.confprog, '--objc-flags'])
  80. if fp.returncode != 0:
  81. raise DependencyException('Error getting objc-args: %s %s' % (flagtxt, flagerr))
  82. args = flagtxt.split()
  83. self.compile_args = self.filter_args(args)
  84. fp, libtxt, liberr = Popen_safe([self.confprog, arg])
  85. if fp.returncode != 0:
  86. raise DependencyException('Error getting objc-lib args: %s %s' % (libtxt, liberr))
  87. self.link_args = self.weird_filter(libtxt.split())
  88. self.version = self.detect_version()
  89. self.is_found = True
  90. mlog.log('Dependency', mlog.bold('GnuStep'), 'found:',
  91. mlog.green('YES'), self.version)
  92. def weird_filter(self, elems):
  93. """When building packages, the output of the enclosing Make
  94. is sometimes mixed among the subprocess output. I have no idea
  95. why. As a hack filter out everything that is not a flag."""
  96. return [e for e in elems if e.startswith('-')]
  97. def filter_args(self, args):
  98. """gnustep-config returns a bunch of garbage args such
  99. as -O2 and so on. Drop everything that is not needed."""
  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. def detect_version(self):
  110. gmake = self.get_variable('GNUMAKE')
  111. makefile_dir = self.get_variable('GNUSTEP_MAKEFILES')
  112. # This Makefile has the GNUStep version set
  113. base_make = os.path.join(makefile_dir, 'Additional', 'base.make')
  114. # Print the Makefile variable passed as the argument. For instance, if
  115. # you run the make target `print-SOME_VARIABLE`, this will print the
  116. # value of the variable `SOME_VARIABLE`.
  117. printver = "print-%:\n\t@echo '$($*)'"
  118. env = os.environ.copy()
  119. # See base.make to understand why this is set
  120. env['FOUNDATION_LIB'] = 'gnu'
  121. p, o, e = Popen_safe([gmake, '-f', '-', '-f', base_make,
  122. 'print-GNUSTEP_BASE_VERSION'],
  123. env=env, write=printver, stdin=subprocess.PIPE)
  124. version = o.strip()
  125. if not version:
  126. mlog.debug("Couldn't detect GNUStep version, falling back to '1'")
  127. # Fallback to setting some 1.x version
  128. version = '1'
  129. return version
  130. def get_variable(self, var):
  131. p, o, e = Popen_safe([self.confprog, '--variable=' + var])
  132. if p.returncode != 0 and self.required:
  133. raise DependencyException('{!r} for variable {!r} failed to run'
  134. ''.format(self.confprog, var))
  135. return o.strip()
  136. class QtBaseDependency(ExternalDependency):
  137. def __init__(self, name, env, kwargs):
  138. super().__init__(name, env, 'cpp', kwargs)
  139. self.qtname = name.capitalize()
  140. self.qtver = name[-1]
  141. if self.qtver == "4":
  142. self.qtpkgname = 'Qt'
  143. else:
  144. self.qtpkgname = self.qtname
  145. self.root = '/usr'
  146. self.bindir = None
  147. mods = kwargs.get('modules', [])
  148. if isinstance(mods, str):
  149. mods = [mods]
  150. if not mods:
  151. raise DependencyException('No ' + self.qtname + ' modules specified.')
  152. type_text = 'cross' if env.is_cross_build() else 'native'
  153. found_msg = '{} {} {{}} dependency (modules: {}) found:' \
  154. ''.format(self.qtname, type_text, ', '.join(mods))
  155. from_text = 'pkg-config'
  156. # Keep track of the detection methods used, for logging purposes.
  157. methods = []
  158. # Prefer pkg-config, then fallback to `qmake -query`
  159. if DependencyMethods.PKGCONFIG in self.methods:
  160. self._pkgconfig_detect(mods, kwargs)
  161. methods.append('pkgconfig')
  162. if not self.is_found and DependencyMethods.QMAKE in self.methods:
  163. from_text = self._qmake_detect(mods, kwargs)
  164. methods.append('qmake-' + self.name)
  165. methods.append('qmake')
  166. if not self.is_found:
  167. # Reset compile args and link args
  168. self.compile_args = []
  169. self.link_args = []
  170. from_text = '(checked {})'.format(mlog.format_list(methods))
  171. self.version = 'none'
  172. if self.required:
  173. err_msg = '{} {} dependency not found {}' \
  174. ''.format(self.qtname, type_text, from_text)
  175. raise DependencyException(err_msg)
  176. if not self.silent:
  177. mlog.log(found_msg.format(from_text), mlog.red('NO'))
  178. return
  179. from_text = '`{}`'.format(from_text)
  180. if not self.silent:
  181. mlog.log(found_msg.format(from_text), mlog.green('YES'))
  182. def compilers_detect(self):
  183. "Detect Qt (4 or 5) moc, uic, rcc in the specified bindir or in PATH"
  184. if self.bindir:
  185. moc = ExternalProgram(os.path.join(self.bindir, 'moc'), silent=True)
  186. uic = ExternalProgram(os.path.join(self.bindir, 'uic'), silent=True)
  187. rcc = ExternalProgram(os.path.join(self.bindir, 'rcc'), silent=True)
  188. else:
  189. # We don't accept unsuffixed 'moc', 'uic', and 'rcc' because they
  190. # are sometimes older, or newer versions.
  191. moc = ExternalProgram('moc-' + self.name, silent=True)
  192. uic = ExternalProgram('uic-' + self.name, silent=True)
  193. rcc = ExternalProgram('rcc-' + self.name, silent=True)
  194. return moc, uic, rcc
  195. def _pkgconfig_detect(self, mods, kwargs):
  196. # We set the value of required to False so that we can try the
  197. # qmake-based fallback if pkg-config fails.
  198. kwargs['required'] = False
  199. modules = OrderedDict()
  200. for module in mods:
  201. modules[module] = PkgConfigDependency(self.qtpkgname + module, self.env, kwargs)
  202. for m in modules.values():
  203. if not m.found():
  204. self.is_found = False
  205. return
  206. self.compile_args += m.get_compile_args()
  207. self.link_args += m.get_link_args()
  208. self.is_found = True
  209. self.version = m.version
  210. # Try to detect moc, uic, rcc
  211. if 'Core' in modules:
  212. core = modules['Core']
  213. else:
  214. corekwargs = {'required': 'false', 'silent': 'true'}
  215. core = PkgConfigDependency(self.qtpkgname + 'Core', self.env, corekwargs)
  216. # Used by self.compilers_detect()
  217. self.bindir = self.get_pkgconfig_host_bins(core)
  218. if not self.bindir:
  219. # If exec_prefix is not defined, the pkg-config file is broken
  220. prefix = core.get_pkgconfig_variable('exec_prefix')
  221. if prefix:
  222. self.bindir = os.path.join(prefix, 'bin')
  223. def _find_qmake(self, qmake):
  224. # Even when cross-compiling, if we don't get a cross-info qmake, we
  225. # fallback to using the qmake in PATH because that's what we used to do
  226. if self.env.is_cross_build():
  227. qmake = self.env.cross_info.config['binaries'].get('qmake', qmake)
  228. return ExternalProgram(qmake, silent=True)
  229. def _qmake_detect(self, mods, kwargs):
  230. for qmake in ('qmake-' + self.name, 'qmake'):
  231. self.qmake = self._find_qmake(qmake)
  232. if not self.qmake.found():
  233. continue
  234. # Check that the qmake is for qt5
  235. pc, stdo = Popen_safe(self.qmake.get_command() + ['-v'])[0:2]
  236. if pc.returncode != 0:
  237. continue
  238. if not 'Qt version ' + self.qtver in stdo:
  239. mlog.log('QMake is not for ' + self.qtname)
  240. continue
  241. # Found qmake for Qt5!
  242. break
  243. else:
  244. # Didn't find qmake :(
  245. self.is_found = False
  246. return
  247. self.version = re.search(self.qtver + '(\.\d+)+', stdo).group(0)
  248. # Query library path, header path, and binary path
  249. mlog.log("Found qmake:", mlog.bold(self.qmake.get_name()), '(%s)' % self.version)
  250. stdo = Popen_safe(self.qmake.get_command() + ['-query'])[1]
  251. qvars = {}
  252. for line in stdo.split('\n'):
  253. line = line.strip()
  254. if line == '':
  255. continue
  256. (k, v) = tuple(line.split(':', 1))
  257. qvars[k] = v
  258. if mesonlib.is_osx():
  259. return self._framework_detect(qvars, mods, kwargs)
  260. incdir = qvars['QT_INSTALL_HEADERS']
  261. self.compile_args.append('-I' + incdir)
  262. libdir = qvars['QT_INSTALL_LIBS']
  263. # Used by self.compilers_detect()
  264. self.bindir = self.get_qmake_host_bins(qvars)
  265. self.is_found = True
  266. for module in mods:
  267. mincdir = os.path.join(incdir, 'Qt' + module)
  268. self.compile_args.append('-I' + mincdir)
  269. if for_windows(self.env.is_cross_build(), self.env):
  270. libfile = os.path.join(libdir, self.qtpkgname + module + '.lib')
  271. if not os.path.isfile(libfile):
  272. # MinGW can link directly to .dll
  273. libfile = os.path.join(self.bindir, self.qtpkgname + module + '.dll')
  274. if not os.path.isfile(libfile):
  275. self.is_found = False
  276. break
  277. else:
  278. libfile = os.path.join(libdir, 'lib{}{}.so'.format(self.qtpkgname, module))
  279. if not os.path.isfile(libfile):
  280. self.is_found = False
  281. break
  282. self.link_args.append(libfile)
  283. return qmake
  284. def _framework_detect(self, qvars, modules, kwargs):
  285. libdir = qvars['QT_INSTALL_LIBS']
  286. for m in modules:
  287. fname = 'Qt' + m
  288. fwdep = ExtraFrameworkDependency(fname, False, libdir, self.env,
  289. self.language, kwargs)
  290. self.compile_args.append('-F' + libdir)
  291. if fwdep.found():
  292. self.is_found = True
  293. self.compile_args += fwdep.get_compile_args()
  294. self.link_args += fwdep.get_link_args()
  295. # Used by self.compilers_detect()
  296. self.bindir = self.get_qmake_host_bins(qvars)
  297. def get_qmake_host_bins(self, qvars):
  298. # Prefer QT_HOST_BINS (qt5, correct for cross and native compiling)
  299. # but fall back to QT_INSTALL_BINS (qt4)
  300. if 'QT_HOST_BINS' in qvars:
  301. return qvars['QT_HOST_BINS']
  302. else:
  303. return qvars['QT_INSTALL_BINS']
  304. def get_methods(self):
  305. return [DependencyMethods.PKGCONFIG, DependencyMethods.QMAKE]
  306. def get_exe_args(self, compiler):
  307. # Originally this was -fPIE but nowadays the default
  308. # for upstream and distros seems to be -reduce-relocations
  309. # which requires -fPIC. This may cause a performance
  310. # penalty when using self-built Qt or on platforms
  311. # where -fPIC is not required. If this is an issue
  312. # for you, patches are welcome.
  313. return compiler.get_pic_args()
  314. class Qt4Dependency(QtBaseDependency):
  315. def __init__(self, env, kwargs):
  316. QtBaseDependency.__init__(self, 'qt4', env, kwargs)
  317. def get_pkgconfig_host_bins(self, core):
  318. # Only return one bins dir, because the tools are generally all in one
  319. # directory for Qt4, in Qt5, they must all be in one directory. Return
  320. # the first one found among the bin variables, in case one tool is not
  321. # configured to be built.
  322. applications = ['moc', 'uic', 'rcc', 'lupdate', 'lrelease']
  323. for application in applications:
  324. try:
  325. return os.path.dirname(core.get_pkgconfig_variable('%s_location' % application))
  326. except MesonException:
  327. pass
  328. class Qt5Dependency(QtBaseDependency):
  329. def __init__(self, env, kwargs):
  330. QtBaseDependency.__init__(self, 'qt5', env, kwargs)
  331. def get_pkgconfig_host_bins(self, core):
  332. return core.get_pkgconfig_variable('host_bins')
  333. # There are three different ways of depending on SDL2:
  334. # sdl2-config, pkg-config and OSX framework
  335. class SDL2Dependency(ExternalDependency):
  336. def __init__(self, environment, kwargs):
  337. super().__init__('sdl2', environment, None, kwargs)
  338. if DependencyMethods.PKGCONFIG in self.methods:
  339. try:
  340. kwargs['required'] = False
  341. pcdep = PkgConfigDependency('sdl2', environment, kwargs)
  342. if pcdep.found():
  343. self.type_name = 'pkgconfig'
  344. self.is_found = True
  345. self.compile_args = pcdep.get_compile_args()
  346. self.link_args = pcdep.get_link_args()
  347. self.version = pcdep.get_version()
  348. return
  349. except Exception as e:
  350. mlog.debug('SDL 2 not found via pkgconfig. Trying next, error was:', str(e))
  351. pass
  352. if DependencyMethods.SDLCONFIG in self.methods:
  353. sdlconf = shutil.which('sdl2-config')
  354. if sdlconf:
  355. stdo = Popen_safe(['sdl2-config', '--cflags'])[1]
  356. self.compile_args = stdo.strip().split()
  357. stdo = Popen_safe(['sdl2-config', '--libs'])[1]
  358. self.link_args = stdo.strip().split()
  359. stdo = Popen_safe(['sdl2-config', '--version'])[1]
  360. self.version = stdo.strip()
  361. self.is_found = True
  362. mlog.log('Dependency', mlog.bold('sdl2'), 'found:', mlog.green('YES'),
  363. self.version, '(%s)' % sdlconf)
  364. return
  365. mlog.debug('Could not find sdl2-config binary, trying next.')
  366. if DependencyMethods.EXTRAFRAMEWORK in self.methods:
  367. if mesonlib.is_osx():
  368. fwdep = ExtraFrameworkDependency('sdl2', False, None, self.env,
  369. self.language, kwargs)
  370. if fwdep.found():
  371. self.is_found = True
  372. self.compile_args = fwdep.get_compile_args()
  373. self.link_args = fwdep.get_link_args()
  374. self.version = '2' # FIXME
  375. return
  376. mlog.log('Dependency', mlog.bold('sdl2'), 'found:', mlog.red('NO'))
  377. def get_methods(self):
  378. if mesonlib.is_osx():
  379. return [DependencyMethods.PKGCONFIG, DependencyMethods.SDLCONFIG, DependencyMethods.EXTRAFRAMEWORK]
  380. else:
  381. return [DependencyMethods.PKGCONFIG, DependencyMethods.SDLCONFIG]
  382. class WxDependency(ExternalDependency):
  383. wx_found = None
  384. def __init__(self, environment, kwargs):
  385. super().__init__('wx', environment, None, kwargs)
  386. self.version = 'none'
  387. if WxDependency.wx_found is None:
  388. self.check_wxconfig()
  389. else:
  390. self.wxc = WxDependency.wx_found
  391. if not WxDependency.wx_found:
  392. mlog.log("Neither wx-config-3.0 nor wx-config found; can't detect dependency")
  393. return
  394. # FIXME: This should print stdout and stderr using mlog.debug
  395. p, out = Popen_safe([self.wxc, '--version'])[0:2]
  396. if p.returncode != 0:
  397. mlog.log('Dependency wxwidgets found:', mlog.red('NO'))
  398. else:
  399. self.version = out.strip()
  400. # FIXME: Support multiple version reqs like PkgConfigDependency
  401. version_req = kwargs.get('version', None)
  402. if version_req is not None:
  403. if not version_compare(self.version, version_req, strict=True):
  404. mlog.log('Wxwidgets version %s does not fullfill requirement %s' %
  405. (self.version, version_req))
  406. return
  407. mlog.log('Dependency wxwidgets found:', mlog.green('YES'))
  408. self.is_found = True
  409. self.requested_modules = self.get_requested(kwargs)
  410. # wx-config seems to have a cflags as well but since it requires C++,
  411. # this should be good, at least for now.
  412. p, out = Popen_safe([self.wxc, '--cxxflags'])[0:2]
  413. # FIXME: this error should only be raised if required is true
  414. if p.returncode != 0:
  415. raise DependencyException('Could not generate cargs for wxwidgets.')
  416. self.compile_args = out.split()
  417. # FIXME: this error should only be raised if required is true
  418. p, out = Popen_safe([self.wxc, '--libs'] + self.requested_modules)[0:2]
  419. if p.returncode != 0:
  420. raise DependencyException('Could not generate libs for wxwidgets.')
  421. self.link_args = out.split()
  422. def get_requested(self, kwargs):
  423. modules = 'modules'
  424. if modules not in kwargs:
  425. return []
  426. candidates = kwargs[modules]
  427. if not isinstance(candidates, list):
  428. candidates = [candidates]
  429. for c in candidates:
  430. if not isinstance(c, str):
  431. raise DependencyException('wxwidgets module argument is not a string')
  432. return candidates
  433. def check_wxconfig(self):
  434. for wxc in ['wx-config-3.0', 'wx-config']:
  435. try:
  436. p, out = Popen_safe([wxc, '--version'])[0:2]
  437. if p.returncode == 0:
  438. mlog.log('Found wx-config:', mlog.bold(shutil.which(wxc)),
  439. '(%s)' % out.strip())
  440. self.wxc = wxc
  441. WxDependency.wx_found = wxc
  442. return
  443. except (FileNotFoundError, PermissionError):
  444. pass
  445. WxDependency.wxconfig_found = False
  446. mlog.log('Found wx-config:', mlog.red('NO'))