gnome.py 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481
  1. # Copyright 2015-2016 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 module provides helper functions for Gnome/GLib related
  12. functionality such as gobject-introspection, gresources and gtk-doc'''
  13. import os
  14. import copy
  15. import subprocess
  16. from .. import build
  17. from .. import mlog
  18. from .. import mesonlib
  19. from .. import compilers
  20. from .. import interpreter
  21. from . import GResourceTarget, GResourceHeaderTarget, GirTarget, TypelibTarget, VapiTarget
  22. from . import get_include_args
  23. from . import ExtensionModule
  24. from . import ModuleReturnValue
  25. from ..mesonlib import MesonException, OrderedSet, Popen_safe, extract_as_list
  26. from ..dependencies import Dependency, PkgConfigDependency, InternalDependency
  27. from ..interpreterbase import noKwargs, permittedKwargs, FeatureNew, FeatureNewKwargs
  28. # gresource compilation is broken due to the way
  29. # the resource compiler and Ninja clash about it
  30. #
  31. # https://github.com/ninja-build/ninja/issues/1184
  32. # https://bugzilla.gnome.org/show_bug.cgi?id=774368
  33. gresource_dep_needed_version = '>= 2.51.1'
  34. native_glib_version = None
  35. girwarning_printed = False
  36. gdbuswarning_printed = False
  37. gresource_warning_printed = False
  38. _gir_has_extra_lib_arg = None
  39. def gir_has_extra_lib_arg(intr_obj):
  40. global _gir_has_extra_lib_arg
  41. if _gir_has_extra_lib_arg is not None:
  42. return _gir_has_extra_lib_arg
  43. _gir_has_extra_lib_arg = False
  44. try:
  45. g_ir_scanner = intr_obj.find_program_impl('g-ir-scanner').get_command()
  46. opts = Popen_safe(g_ir_scanner + ['--help'], stderr=subprocess.STDOUT)[1]
  47. _gir_has_extra_lib_arg = '--extra-library' in opts
  48. except (MesonException, FileNotFoundError, subprocess.CalledProcessError):
  49. pass
  50. return _gir_has_extra_lib_arg
  51. class GnomeModule(ExtensionModule):
  52. gir_dep = None
  53. @staticmethod
  54. def _get_native_glib_version(state):
  55. global native_glib_version
  56. if native_glib_version is None:
  57. glib_dep = PkgConfigDependency('glib-2.0', state.environment,
  58. {'native': True, 'required': False})
  59. if glib_dep.found():
  60. native_glib_version = glib_dep.get_version()
  61. else:
  62. mlog.warning('Could not detect glib version, assuming 2.54. '
  63. 'You may get build errors if your glib is older.')
  64. native_glib_version = '2.54'
  65. return native_glib_version
  66. def __print_gresources_warning(self, state):
  67. global gresource_warning_printed
  68. if not gresource_warning_printed:
  69. if not mesonlib.version_compare(self._get_native_glib_version(state), gresource_dep_needed_version):
  70. mlog.warning('GLib compiled dependencies do not work reliably with \n'
  71. 'the current version of GLib. See the following upstream issue:',
  72. mlog.bold('https://bugzilla.gnome.org/show_bug.cgi?id=774368'))
  73. gresource_warning_printed = True
  74. return []
  75. @staticmethod
  76. def _print_gdbus_warning():
  77. global gdbuswarning_printed
  78. if not gdbuswarning_printed:
  79. mlog.warning('Code generated with gdbus_codegen() requires the root directory be added to\n'
  80. ' include_directories of targets with GLib < 2.51.3:',
  81. mlog.bold('https://github.com/mesonbuild/meson/issues/1387'))
  82. gdbuswarning_printed = True
  83. @FeatureNewKwargs('gnome.compile_resources', '0.37.0', ['gresource_bundle', 'export', 'install_header'])
  84. @permittedKwargs({'source_dir', 'c_name', 'dependencies', 'export', 'gresource_bundle', 'install_header',
  85. 'install', 'install_dir', 'extra_args', 'build_by_default'})
  86. def compile_resources(self, state, args, kwargs):
  87. self.__print_gresources_warning(state)
  88. glib_version = self._get_native_glib_version(state)
  89. cmd = ['glib-compile-resources', '@INPUT@']
  90. source_dirs, dependencies = mesonlib.extract_as_list(kwargs, 'source_dir', 'dependencies', pop=True)
  91. if len(args) < 2:
  92. raise MesonException('Not enough arguments; the name of the resource '
  93. 'and the path to the XML file are required')
  94. # Validate dependencies
  95. for (ii, dep) in enumerate(dependencies):
  96. if hasattr(dep, 'held_object'):
  97. dependencies[ii] = dep = dep.held_object
  98. if not isinstance(dep, (mesonlib.File, build.CustomTarget, build.CustomTargetIndex)):
  99. m = 'Unexpected dependency type {!r} for gnome.compile_resources() ' \
  100. '"dependencies" argument.\nPlease pass the return value of ' \
  101. 'custom_target() or configure_file()'
  102. raise MesonException(m.format(dep))
  103. if isinstance(dep, (build.CustomTarget, build.CustomTargetIndex)):
  104. if not mesonlib.version_compare(glib_version, gresource_dep_needed_version):
  105. m = 'The "dependencies" argument of gnome.compile_resources() can not\n' \
  106. 'be used with the current version of glib-compile-resources due to\n' \
  107. '<https://bugzilla.gnome.org/show_bug.cgi?id=774368>'
  108. raise MesonException(m)
  109. ifile = args[1]
  110. if isinstance(ifile, mesonlib.File):
  111. # glib-compile-resources will be run inside the source dir,
  112. # so we need either 'src_to_build' or the absolute path.
  113. # Absolute path is the easiest choice.
  114. if ifile.is_built:
  115. ifile = os.path.join(state.environment.get_build_dir(), ifile.subdir, ifile.fname)
  116. else:
  117. ifile = os.path.join(ifile.subdir, ifile.fname)
  118. elif isinstance(ifile, str):
  119. ifile = os.path.join(state.subdir, ifile)
  120. elif isinstance(ifile, (interpreter.CustomTargetHolder,
  121. interpreter.CustomTargetIndexHolder,
  122. interpreter.GeneratedObjectsHolder)):
  123. m = 'Resource xml files generated at build-time cannot be used ' \
  124. 'with gnome.compile_resources() because we need to scan ' \
  125. 'the xml for dependencies. Use configure_file() instead ' \
  126. 'to generate it at configure-time.'
  127. raise MesonException(m)
  128. else:
  129. raise MesonException('Invalid file argument: {!r}'.format(ifile))
  130. depend_files, depends, subdirs = self._get_gresource_dependencies(
  131. state, ifile, source_dirs, dependencies)
  132. # Make source dirs relative to build dir now
  133. source_dirs = [os.path.join(state.build_to_src, state.subdir, d) for d in source_dirs]
  134. # Always include current directory, but after paths set by user
  135. source_dirs.append(os.path.join(state.build_to_src, state.subdir))
  136. # Ensure build directories of generated deps are included
  137. source_dirs += subdirs
  138. for source_dir in OrderedSet(source_dirs):
  139. cmd += ['--sourcedir', source_dir]
  140. if 'c_name' in kwargs:
  141. cmd += ['--c-name', kwargs.pop('c_name')]
  142. export = kwargs.pop('export', False)
  143. if not export:
  144. cmd += ['--internal']
  145. cmd += ['--generate', '--target', '@OUTPUT@']
  146. cmd += mesonlib.stringlistify(kwargs.pop('extra_args', []))
  147. gresource = kwargs.pop('gresource_bundle', False)
  148. if gresource:
  149. output = args[0] + '.gresource'
  150. name = args[0] + '_gresource'
  151. else:
  152. output = args[0] + '.c'
  153. name = args[0] + '_c'
  154. if kwargs.get('install', False) and not gresource:
  155. raise MesonException('The install kwarg only applies to gresource bundles, see install_header')
  156. install_header = kwargs.pop('install_header', False)
  157. if install_header and gresource:
  158. raise MesonException('The install_header kwarg does not apply to gresource bundles')
  159. if install_header and not export:
  160. raise MesonException('GResource header is installed yet export is not enabled')
  161. kwargs['input'] = args[1]
  162. kwargs['output'] = output
  163. kwargs['depends'] = depends
  164. if not mesonlib.version_compare(glib_version, gresource_dep_needed_version):
  165. # This will eventually go out of sync if dependencies are added
  166. kwargs['depend_files'] = depend_files
  167. kwargs['command'] = cmd
  168. else:
  169. depfile = kwargs['output'] + '.d'
  170. kwargs['depfile'] = depfile
  171. kwargs['command'] = copy.copy(cmd) + ['--dependency-file', '@DEPFILE@']
  172. target_c = GResourceTarget(name, state.subdir, state.subproject, kwargs)
  173. if gresource: # Only one target for .gresource files
  174. return ModuleReturnValue(target_c, [target_c])
  175. h_kwargs = {
  176. 'command': cmd,
  177. 'input': args[1],
  178. 'output': args[0] + '.h',
  179. # The header doesn't actually care about the files yet it errors if missing
  180. 'depends': depends
  181. }
  182. if 'build_by_default' in kwargs:
  183. h_kwargs['build_by_default'] = kwargs['build_by_default']
  184. if install_header:
  185. h_kwargs['install'] = install_header
  186. h_kwargs['install_dir'] = kwargs.get('install_dir',
  187. state.environment.coredata.get_builtin_option('includedir'))
  188. target_h = GResourceHeaderTarget(args[0] + '_h', state.subdir, state.subproject, h_kwargs)
  189. rv = [target_c, target_h]
  190. return ModuleReturnValue(rv, rv)
  191. def _get_gresource_dependencies(self, state, input_file, source_dirs, dependencies):
  192. cmd = ['glib-compile-resources',
  193. input_file,
  194. '--generate-dependencies']
  195. # Prefer generated files over source files
  196. cmd += ['--sourcedir', state.subdir] # Current build dir
  197. for source_dir in source_dirs:
  198. cmd += ['--sourcedir', os.path.join(state.subdir, source_dir)]
  199. pc, stdout, stderr = Popen_safe(cmd, cwd=state.environment.get_source_dir())
  200. if pc.returncode != 0:
  201. m = 'glib-compile-resources failed to get dependencies for {}:\n{}'
  202. mlog.warning(m.format(cmd[1], stderr))
  203. raise subprocess.CalledProcessError(pc.returncode, cmd)
  204. dep_files = stdout.split('\n')[:-1]
  205. depends = []
  206. subdirs = []
  207. for resfile in dep_files[:]:
  208. resbasename = os.path.basename(resfile)
  209. for dep in dependencies:
  210. if hasattr(dep, 'held_object'):
  211. dep = dep.held_object
  212. if isinstance(dep, mesonlib.File):
  213. if dep.fname != resbasename:
  214. continue
  215. dep_files.remove(resfile)
  216. dep_files.append(dep)
  217. subdirs.append(dep.subdir)
  218. break
  219. elif isinstance(dep, (build.CustomTarget, build.CustomTargetIndex)):
  220. fname = None
  221. outputs = {(o, os.path.basename(o)) for o in dep.get_outputs()}
  222. for o, baseo in outputs:
  223. if baseo == resbasename:
  224. fname = o
  225. break
  226. if fname is not None:
  227. dep_files.remove(resfile)
  228. depends.append(dep)
  229. subdirs.append(dep.get_subdir())
  230. break
  231. else:
  232. # In generate-dependencies mode, glib-compile-resources doesn't raise
  233. # an error for missing resources but instead prints whatever filename
  234. # was listed in the input file. That's good because it means we can
  235. # handle resource files that get generated as part of the build, as
  236. # follows.
  237. #
  238. # If there are multiple generated resource files with the same basename
  239. # then this code will get confused.
  240. try:
  241. f = mesonlib.File.from_source_file(state.environment.get_source_dir(),
  242. ".", resfile)
  243. except MesonException:
  244. raise MesonException(
  245. 'Resource "%s" listed in "%s" was not found. If this is a '
  246. 'generated file, pass the target that generates it to '
  247. 'gnome.compile_resources() using the "dependencies" '
  248. 'keyword argument.' % (resfile, input_file))
  249. dep_files.remove(resfile)
  250. dep_files.append(f)
  251. return dep_files, depends, subdirs
  252. def _get_link_args(self, state, lib, depends, include_rpath=False,
  253. use_gir_args=False):
  254. link_command = []
  255. # Construct link args
  256. if isinstance(lib, build.SharedLibrary):
  257. libdir = os.path.join(state.environment.get_build_dir(), state.backend.get_target_dir(lib))
  258. link_command.append('-L' + libdir)
  259. # Needed for the following binutils bug:
  260. # https://github.com/mesonbuild/meson/issues/1911
  261. # However, g-ir-scanner does not understand -Wl,-rpath
  262. # so we need to use -L instead
  263. for d in state.backend.determine_rpath_dirs(lib):
  264. d = os.path.join(state.environment.get_build_dir(), d)
  265. link_command.append('-L' + d)
  266. if include_rpath:
  267. link_command.append('-Wl,-rpath,' + d)
  268. if include_rpath:
  269. link_command.append('-Wl,-rpath,' + libdir)
  270. depends.append(lib)
  271. if gir_has_extra_lib_arg(self.interpreter) and use_gir_args:
  272. link_command.append('--extra-library=' + lib.name)
  273. else:
  274. link_command.append('-l' + lib.name)
  275. return link_command
  276. def _get_dependencies_flags(self, deps, state, depends, include_rpath=False,
  277. use_gir_args=False):
  278. cflags = OrderedSet()
  279. ldflags = OrderedSet()
  280. gi_includes = OrderedSet()
  281. deps = mesonlib.listify(deps, unholder=True)
  282. for dep in deps:
  283. if isinstance(dep, InternalDependency):
  284. cflags.update(get_include_args(dep.include_directories))
  285. for lib in dep.libraries:
  286. if hasattr(lib, 'held_object'):
  287. lib = lib.held_object
  288. ldflags.update(self._get_link_args(state, lib, depends, include_rpath))
  289. libdepflags = self._get_dependencies_flags(lib.get_external_deps(), state, depends, include_rpath,
  290. use_gir_args)
  291. cflags.update(libdepflags[0])
  292. ldflags.update(libdepflags[1])
  293. gi_includes.update(libdepflags[2])
  294. extdepflags = self._get_dependencies_flags(dep.ext_deps, state, depends, include_rpath,
  295. use_gir_args)
  296. cflags.update(extdepflags[0])
  297. ldflags.update(extdepflags[1])
  298. gi_includes.update(extdepflags[2])
  299. for source in dep.sources:
  300. if hasattr(source, 'held_object'):
  301. source = source.held_object
  302. if isinstance(source, GirTarget):
  303. gi_includes.update([os.path.join(state.environment.get_build_dir(),
  304. source.get_subdir())])
  305. # This should be any dependency other than an internal one.
  306. elif isinstance(dep, Dependency):
  307. cflags.update(dep.get_compile_args())
  308. for lib in dep.get_link_args():
  309. if (os.path.isabs(lib) and
  310. # For PkgConfigDependency only:
  311. getattr(dep, 'is_libtool', False)):
  312. lib_dir = os.path.dirname(lib)
  313. ldflags.update(["-L%s" % lib_dir])
  314. if include_rpath:
  315. ldflags.update(['-Wl,-rpath {}'.format(lib_dir)])
  316. libname = os.path.basename(lib)
  317. if libname.startswith("lib"):
  318. libname = libname[3:]
  319. libname = libname.split(".so")[0]
  320. lib = "-l%s" % libname
  321. # Hack to avoid passing some compiler options in
  322. if lib.startswith("-W"):
  323. continue
  324. ldflags.update([lib])
  325. if isinstance(dep, PkgConfigDependency):
  326. girdir = dep.get_pkgconfig_variable("girdir", {'default': ''})
  327. if girdir:
  328. gi_includes.update([girdir])
  329. elif isinstance(dep, (build.StaticLibrary, build.SharedLibrary)):
  330. cflags.update(get_include_args(dep.get_include_dirs()))
  331. depends.append(dep)
  332. else:
  333. mlog.log('dependency {!r} not handled to build gir files'.format(dep))
  334. continue
  335. if gir_has_extra_lib_arg(self.interpreter) and use_gir_args:
  336. fixed_ldflags = OrderedSet()
  337. for ldflag in ldflags:
  338. if ldflag.startswith("-l"):
  339. fixed_ldflags.add(ldflag.replace('-l', '--extra-library=', 1))
  340. else:
  341. fixed_ldflags.add(ldflag)
  342. ldflags = fixed_ldflags
  343. return cflags, ldflags, gi_includes
  344. @FeatureNewKwargs('build target', '0.40.0', ['build_by_default'])
  345. @permittedKwargs({'sources', 'nsversion', 'namespace', 'symbol_prefix', 'identifier_prefix',
  346. 'export_packages', 'includes', 'dependencies', 'link_with', 'include_directories',
  347. 'install', 'install_dir_gir', 'install_dir_typelib', 'extra_args',
  348. 'packages', 'header', 'build_by_default'})
  349. def generate_gir(self, state, args, kwargs):
  350. if len(args) != 1:
  351. raise MesonException('Gir takes one argument')
  352. if kwargs.get('install_dir'):
  353. raise MesonException('install_dir is not supported with generate_gir(), see "install_dir_gir" and "install_dir_typelib"')
  354. giscanner = self.interpreter.find_program_impl('g-ir-scanner')
  355. gicompiler = self.interpreter.find_program_impl('g-ir-compiler')
  356. girtarget = args[0]
  357. while hasattr(girtarget, 'held_object'):
  358. girtarget = girtarget.held_object
  359. if not isinstance(girtarget, (build.Executable, build.SharedLibrary)):
  360. raise MesonException('Gir target must be an executable or shared library')
  361. try:
  362. if not self.gir_dep:
  363. self.gir_dep = PkgConfigDependency('gobject-introspection-1.0',
  364. state.environment,
  365. {'native': True})
  366. pkgargs = self.gir_dep.get_compile_args()
  367. except Exception:
  368. raise MesonException('gobject-introspection dependency was not found, gir cannot be generated.')
  369. ns = kwargs.pop('namespace')
  370. nsversion = kwargs.pop('nsversion')
  371. libsources = mesonlib.extract_as_list(kwargs, 'sources', pop=True)
  372. girfile = '%s-%s.gir' % (ns, nsversion)
  373. srcdir = os.path.join(state.environment.get_source_dir(), state.subdir)
  374. builddir = os.path.join(state.environment.get_build_dir(), state.subdir)
  375. depends = [girtarget]
  376. gir_inc_dirs = []
  377. scan_command = [giscanner]
  378. scan_command += pkgargs
  379. scan_command += ['--no-libtool', '--namespace=' + ns, '--nsversion=' + nsversion, '--warn-all',
  380. '--output', '@OUTPUT@']
  381. header = kwargs.pop('header', None)
  382. if header:
  383. if not isinstance(header, str):
  384. raise MesonException('header must be a string')
  385. scan_command += ['--c-include=' + header]
  386. extra_args = mesonlib.stringlistify(kwargs.pop('extra_args', []))
  387. scan_command += extra_args
  388. scan_command += ['-I' + srcdir,
  389. '-I' + builddir]
  390. scan_command += get_include_args(girtarget.get_include_dirs())
  391. gir_filelist_dir = state.backend.get_target_private_dir_abs(girtarget)
  392. if not os.path.isdir(gir_filelist_dir):
  393. os.mkdir(gir_filelist_dir)
  394. gir_filelist_filename = os.path.join(gir_filelist_dir, '%s_%s_gir_filelist' % (ns, nsversion))
  395. with open(gir_filelist_filename, 'w', encoding='utf-8') as gir_filelist:
  396. for s in libsources:
  397. if hasattr(s, 'held_object'):
  398. s = s.held_object
  399. if isinstance(s, (build.CustomTarget, build.CustomTargetIndex)):
  400. for custom_output in s.get_outputs():
  401. gir_filelist.write(os.path.join(state.environment.get_build_dir(),
  402. state.backend.get_target_dir(s),
  403. custom_output) + '\n')
  404. elif isinstance(s, mesonlib.File):
  405. gir_filelist.write(s.rel_to_builddir(state.build_to_src) + '\n')
  406. elif isinstance(s, build.GeneratedList):
  407. for gen_src in s.get_outputs():
  408. gir_filelist.write(os.path.join(srcdir, gen_src) + '\n')
  409. else:
  410. gir_filelist.write(os.path.join(srcdir, s) + '\n')
  411. scan_command += ['--filelist=' + gir_filelist_filename]
  412. if 'link_with' in kwargs:
  413. link_with = mesonlib.extract_as_list(kwargs, 'link_with', pop = True)
  414. for link in link_with:
  415. scan_command += self._get_link_args(state, link.held_object, depends,
  416. use_gir_args=True)
  417. if 'includes' in kwargs:
  418. includes = mesonlib.extract_as_list(kwargs, 'includes', pop = True)
  419. for inc in includes:
  420. if hasattr(inc, 'held_object'):
  421. inc = inc.held_object
  422. if isinstance(inc, str):
  423. scan_command += ['--include=%s' % (inc, )]
  424. elif isinstance(inc, GirTarget):
  425. gir_inc_dirs += [
  426. os.path.join(state.environment.get_build_dir(),
  427. inc.get_subdir()),
  428. ]
  429. scan_command += [
  430. "--include-uninstalled=%s" % (os.path.join(inc.get_subdir(), inc.get_basename()), )
  431. ]
  432. depends += [inc]
  433. else:
  434. raise MesonException(
  435. 'Gir includes must be str, GirTarget, or list of them')
  436. cflags = []
  437. ldflags = []
  438. for lang, compiler in girtarget.compilers.items():
  439. # XXX: Can you use g-i with any other language?
  440. if lang in ('c', 'cpp', 'objc', 'objcpp', 'd'):
  441. break
  442. else:
  443. lang = None
  444. compiler = None
  445. if lang and compiler:
  446. if state.global_args.get(lang):
  447. cflags += state.global_args[lang]
  448. if state.project_args.get(lang):
  449. cflags += state.project_args[lang]
  450. if 'b_sanitize' in compiler.base_options:
  451. sanitize = state.environment.coredata.base_options['b_sanitize'].value
  452. cflags += compilers.sanitizer_compile_args(sanitize)
  453. if 'address' in sanitize.split(','):
  454. ldflags += ['-lasan']
  455. # FIXME: Linking directly to libasan is not recommended but g-ir-scanner
  456. # does not understand -f LDFLAGS. https://bugzilla.gnome.org/show_bug.cgi?id=783892
  457. # ldflags += compilers.sanitizer_link_args(sanitize)
  458. if 'symbol_prefix' in kwargs:
  459. sym_prefixes = mesonlib.stringlistify(kwargs.pop('symbol_prefix', []))
  460. scan_command += ['--symbol-prefix=%s' % sym_prefix for sym_prefix in sym_prefixes]
  461. if 'identifier_prefix' in kwargs:
  462. identifier_prefix = kwargs.pop('identifier_prefix')
  463. if not isinstance(identifier_prefix, str):
  464. raise MesonException('Gir identifier prefix must be str')
  465. scan_command += ['--identifier-prefix=%s' % identifier_prefix]
  466. if 'export_packages' in kwargs:
  467. pkgs = kwargs.pop('export_packages')
  468. if isinstance(pkgs, str):
  469. scan_command += ['--pkg-export=%s' % pkgs]
  470. elif isinstance(pkgs, list):
  471. scan_command += ['--pkg-export=%s' % pkg for pkg in pkgs]
  472. else:
  473. raise MesonException('Gir export packages must be str or list')
  474. deps = (girtarget.get_all_link_deps() + girtarget.get_external_deps() +
  475. extract_as_list(kwargs, 'dependencies', pop=True, unholder=True))
  476. # Need to recursively add deps on GirTarget sources from our
  477. # dependencies and also find the include directories needed for the
  478. # typelib generation custom target below.
  479. typelib_includes = []
  480. for dep in deps:
  481. if hasattr(dep, 'held_object'):
  482. dep = dep.held_object
  483. # Add a dependency on each GirTarget listed in dependencies and add
  484. # the directory where it will be generated to the typelib includes
  485. if isinstance(dep, InternalDependency):
  486. for source in dep.sources:
  487. if hasattr(source, 'held_object'):
  488. source = source.held_object
  489. if isinstance(source, GirTarget) and source not in depends:
  490. depends.append(source)
  491. subdir = os.path.join(state.environment.get_build_dir(),
  492. source.get_subdir())
  493. if subdir not in typelib_includes:
  494. typelib_includes.append(subdir)
  495. # Do the same, but for dependencies of dependencies. These are
  496. # stored in the list of generated sources for each link dep (from
  497. # girtarget.get_all_link_deps() above).
  498. # FIXME: Store this in the original form from declare_dependency()
  499. # so it can be used here directly.
  500. elif isinstance(dep, build.SharedLibrary):
  501. for source in dep.generated:
  502. if isinstance(source, GirTarget):
  503. subdir = os.path.join(state.environment.get_build_dir(),
  504. source.get_subdir())
  505. if subdir not in typelib_includes:
  506. typelib_includes.append(subdir)
  507. elif isinstance(dep, PkgConfigDependency):
  508. girdir = dep.get_pkgconfig_variable("girdir", {'default': ''})
  509. if girdir and girdir not in typelib_includes:
  510. typelib_includes.append(girdir)
  511. # ldflags will be misinterpreted by gir scanner (showing
  512. # spurious dependencies) but building GStreamer fails if they
  513. # are not used here.
  514. dep_cflags, dep_ldflags, gi_includes = self._get_dependencies_flags(deps, state, depends,
  515. use_gir_args=True)
  516. cflags += list(dep_cflags)
  517. ldflags += list(dep_ldflags)
  518. scan_command += ['--cflags-begin']
  519. scan_command += cflags
  520. scan_command += state.environment.coredata.get_external_args(lang)
  521. scan_command += ['--cflags-end']
  522. # need to put our output directory first as we need to use the
  523. # generated libraries instead of any possibly installed system/prefix
  524. # ones.
  525. if isinstance(girtarget, build.SharedLibrary):
  526. scan_command += ["-L@PRIVATE_OUTDIR_ABS_%s@" % girtarget.get_id()]
  527. scan_command += list(ldflags)
  528. for i in gi_includes:
  529. scan_command += ['--add-include-path=%s' % i]
  530. inc_dirs = mesonlib.extract_as_list(kwargs, 'include_directories', pop = True)
  531. for incd in inc_dirs:
  532. if not isinstance(incd.held_object, (str, build.IncludeDirs)):
  533. raise MesonException(
  534. 'Gir include dirs should be include_directories().')
  535. scan_command += get_include_args(inc_dirs)
  536. scan_command += get_include_args(gir_inc_dirs + inc_dirs, prefix='--add-include-path=')
  537. if isinstance(girtarget, build.Executable):
  538. scan_command += ['--program', girtarget]
  539. elif isinstance(girtarget, build.SharedLibrary):
  540. libname = girtarget.get_basename()
  541. # Needed for the following binutils bug:
  542. # https://github.com/mesonbuild/meson/issues/1911
  543. # However, g-ir-scanner does not understand -Wl,-rpath
  544. # so we need to use -L instead
  545. for d in state.backend.determine_rpath_dirs(girtarget):
  546. d = os.path.join(state.environment.get_build_dir(), d)
  547. scan_command.append('-L' + d)
  548. scan_command += ['--library', libname]
  549. for link_arg in state.environment.coredata.get_external_link_args(lang):
  550. if link_arg.startswith('-L'):
  551. scan_command.append(link_arg)
  552. scankwargs = {'output': girfile,
  553. 'command': scan_command,
  554. 'depends': depends}
  555. if 'install' in kwargs:
  556. scankwargs['install'] = kwargs['install']
  557. scankwargs['install_dir'] = kwargs.get('install_dir_gir',
  558. os.path.join(state.environment.get_datadir(), 'gir-1.0'))
  559. if 'build_by_default' in kwargs:
  560. scankwargs['build_by_default'] = kwargs['build_by_default']
  561. scan_target = GirTarget(girfile, state.subdir, state.subproject, scankwargs)
  562. typelib_output = '%s-%s.typelib' % (ns, nsversion)
  563. typelib_cmd = [gicompiler, scan_target, '--output', '@OUTPUT@']
  564. typelib_cmd += get_include_args(gir_inc_dirs, prefix='--includedir=')
  565. for incdir in typelib_includes:
  566. typelib_cmd += ["--includedir=" + incdir]
  567. typelib_kwargs = {
  568. 'output': typelib_output,
  569. 'command': typelib_cmd,
  570. }
  571. if 'install' in kwargs:
  572. typelib_kwargs['install'] = kwargs['install']
  573. typelib_kwargs['install_dir'] = kwargs.get('install_dir_typelib',
  574. os.path.join(state.environment.get_libdir(), 'girepository-1.0'))
  575. if 'build_by_default' in kwargs:
  576. typelib_kwargs['build_by_default'] = kwargs['build_by_default']
  577. typelib_target = TypelibTarget(typelib_output, state.subdir, state.subproject, typelib_kwargs)
  578. rv = [scan_target, typelib_target]
  579. return ModuleReturnValue(rv, rv)
  580. @FeatureNewKwargs('build target', '0.40.0', ['build_by_default'])
  581. @permittedKwargs({'build_by_default', 'depend_files'})
  582. def compile_schemas(self, state, args, kwargs):
  583. if args:
  584. raise MesonException('Compile_schemas does not take positional arguments.')
  585. srcdir = os.path.join(state.build_to_src, state.subdir)
  586. outdir = state.subdir
  587. cmd = [self.interpreter.find_program_impl('glib-compile-schemas')]
  588. cmd += ['--targetdir', outdir, srcdir]
  589. kwargs['command'] = cmd
  590. kwargs['input'] = []
  591. kwargs['output'] = 'gschemas.compiled'
  592. if state.subdir == '':
  593. targetname = 'gsettings-compile'
  594. else:
  595. targetname = 'gsettings-compile-' + state.subdir.replace('/', '_')
  596. target_g = build.CustomTarget(targetname, state.subdir, state.subproject, kwargs)
  597. return ModuleReturnValue(target_g, [target_g])
  598. @permittedKwargs({'sources', 'media', 'symlink_media', 'languages'})
  599. def yelp(self, state, args, kwargs):
  600. if len(args) < 1:
  601. raise MesonException('Yelp requires a project id')
  602. project_id = args[0]
  603. sources = mesonlib.stringlistify(kwargs.pop('sources', []))
  604. if not sources:
  605. if len(args) > 1:
  606. sources = mesonlib.stringlistify(args[1:])
  607. if not sources:
  608. raise MesonException('Yelp requires a list of sources')
  609. source_str = '@@'.join(sources)
  610. langs = mesonlib.stringlistify(kwargs.pop('languages', []))
  611. if langs:
  612. mlog.log(mlog.red('DEPRECATION:'), '''The "languages" argument of gnome.yelp() is deprecated.
  613. Use a LINGUAS file in the sources directory instead.
  614. This will become a hard error in the future.''')
  615. media = mesonlib.stringlistify(kwargs.pop('media', []))
  616. symlinks = kwargs.pop('symlink_media', True)
  617. if not isinstance(symlinks, bool):
  618. raise MesonException('symlink_media must be a boolean')
  619. if kwargs:
  620. raise MesonException('Unknown arguments passed: {}'.format(', '.join(kwargs.keys())))
  621. script = state.environment.get_build_command()
  622. args = ['--internal',
  623. 'yelphelper',
  624. 'install',
  625. '--subdir=' + state.subdir,
  626. '--id=' + project_id,
  627. '--installdir=' + os.path.join(state.environment.get_datadir(), 'help'),
  628. '--sources=' + source_str]
  629. if symlinks:
  630. args.append('--symlinks=true')
  631. if media:
  632. args.append('--media=' + '@@'.join(media))
  633. if langs:
  634. args.append('--langs=' + '@@'.join(langs))
  635. inscript = build.RunScript(script, args)
  636. potargs = state.environment.get_build_command() + [
  637. '--internal', 'yelphelper', 'pot',
  638. '--subdir=' + state.subdir,
  639. '--id=' + project_id,
  640. '--sources=' + source_str,
  641. ]
  642. pottarget = build.RunTarget('help-' + project_id + '-pot', potargs[0],
  643. potargs[1:], [], state.subdir, state.subproject)
  644. poargs = state.environment.get_build_command() + [
  645. '--internal', 'yelphelper', 'update-po',
  646. '--subdir=' + state.subdir,
  647. '--id=' + project_id,
  648. '--sources=' + source_str,
  649. '--langs=' + '@@'.join(langs),
  650. ]
  651. potarget = build.RunTarget('help-' + project_id + '-update-po', poargs[0],
  652. poargs[1:], [], state.subdir, state.subproject)
  653. rv = [inscript, pottarget, potarget]
  654. return ModuleReturnValue(None, rv)
  655. @FeatureNewKwargs('gnome.gtkdoc', '0.37.0', ['namespace', 'mode'])
  656. @permittedKwargs({'main_xml', 'main_sgml', 'src_dir', 'dependencies', 'install',
  657. 'install_dir', 'scan_args', 'scanobjs_args', 'gobject_typesfile',
  658. 'fixxref_args', 'html_args', 'html_assets', 'content_files',
  659. 'mkdb_args', 'ignore_headers', 'include_directories',
  660. 'namespace', 'mode', 'expand_content_files'})
  661. def gtkdoc(self, state, args, kwargs):
  662. if len(args) != 1:
  663. raise MesonException('Gtkdoc must have one positional argument.')
  664. modulename = args[0]
  665. if not isinstance(modulename, str):
  666. raise MesonException('Gtkdoc arg must be string.')
  667. if 'src_dir' not in kwargs:
  668. raise MesonException('Keyword argument src_dir missing.')
  669. main_file = kwargs.get('main_sgml', '')
  670. if not isinstance(main_file, str):
  671. raise MesonException('Main sgml keyword argument must be a string.')
  672. main_xml = kwargs.get('main_xml', '')
  673. if not isinstance(main_xml, str):
  674. raise MesonException('Main xml keyword argument must be a string.')
  675. if main_xml != '':
  676. if main_file != '':
  677. raise MesonException('You can only specify main_xml or main_sgml, not both.')
  678. main_file = main_xml
  679. targetname = modulename + '-doc'
  680. command = state.environment.get_build_command()
  681. namespace = kwargs.get('namespace', '')
  682. mode = kwargs.get('mode', 'auto')
  683. VALID_MODES = ('xml', 'sgml', 'none', 'auto')
  684. if mode not in VALID_MODES:
  685. raise MesonException('gtkdoc: Mode {} is not a valid mode: {}'.format(mode, VALID_MODES))
  686. src_dirs = mesonlib.extract_as_list(kwargs, 'src_dir')
  687. header_dirs = []
  688. for src_dir in src_dirs:
  689. if hasattr(src_dir, 'held_object'):
  690. src_dir = src_dir.held_object
  691. if not isinstance(src_dir, build.IncludeDirs):
  692. raise MesonException('Invalid keyword argument for src_dir.')
  693. for inc_dir in src_dir.get_incdirs():
  694. header_dirs.append(os.path.join(state.environment.get_source_dir(),
  695. src_dir.get_curdir(), inc_dir))
  696. header_dirs.append(os.path.join(state.environment.get_build_dir(),
  697. src_dir.get_curdir(), inc_dir))
  698. else:
  699. header_dirs.append(src_dir)
  700. args = ['--internal', 'gtkdoc',
  701. '--sourcedir=' + state.environment.get_source_dir(),
  702. '--builddir=' + state.environment.get_build_dir(),
  703. '--subdir=' + state.subdir,
  704. '--headerdirs=' + '@@'.join(header_dirs),
  705. '--mainfile=' + main_file,
  706. '--modulename=' + modulename,
  707. '--mode=' + mode]
  708. if namespace:
  709. args.append('--namespace=' + namespace)
  710. args += self._unpack_args('--htmlargs=', 'html_args', kwargs)
  711. args += self._unpack_args('--scanargs=', 'scan_args', kwargs)
  712. args += self._unpack_args('--scanobjsargs=', 'scanobjs_args', kwargs)
  713. args += self._unpack_args('--gobjects-types-file=', 'gobject_typesfile', kwargs, state)
  714. args += self._unpack_args('--fixxrefargs=', 'fixxref_args', kwargs)
  715. args += self._unpack_args('--mkdbargs=', 'mkdb_args', kwargs)
  716. args += self._unpack_args('--html-assets=', 'html_assets', kwargs, state)
  717. depends = []
  718. content_files = []
  719. for s in mesonlib.extract_as_list(kwargs, 'content_files'):
  720. if hasattr(s, 'held_object'):
  721. s = s.held_object
  722. if isinstance(s, (build.CustomTarget, build.CustomTargetIndex)):
  723. depends.append(s)
  724. for o in s.get_outputs():
  725. content_files.append(os.path.join(state.environment.get_build_dir(),
  726. state.backend.get_target_dir(s),
  727. o))
  728. elif isinstance(s, mesonlib.File):
  729. content_files.append(s.absolute_path(state.environment.get_source_dir(),
  730. state.environment.get_build_dir()))
  731. elif isinstance(s, build.GeneratedList):
  732. depends.append(s)
  733. for gen_src in s.get_outputs():
  734. content_files.append(os.path.join(state.environment.get_source_dir(),
  735. state.subdir,
  736. gen_src))
  737. elif isinstance(s, str):
  738. content_files.append(os.path.join(state.environment.get_source_dir(),
  739. state.subdir,
  740. s))
  741. else:
  742. raise MesonException(
  743. 'Invalid object type: {!r}'.format(s.__class__.__name__))
  744. args += ['--content-files=' + '@@'.join(content_files)]
  745. args += self._unpack_args('--expand-content-files=', 'expand_content_files', kwargs, state)
  746. args += self._unpack_args('--ignore-headers=', 'ignore_headers', kwargs)
  747. args += self._unpack_args('--installdir=', 'install_dir', kwargs, state)
  748. args += self._get_build_args(kwargs, state, depends)
  749. res = [build.RunTarget(targetname, command[0], command[1:] + args, depends, state.subdir, state.subproject)]
  750. if kwargs.get('install', True):
  751. res.append(build.RunScript(command, args))
  752. return ModuleReturnValue(None, res)
  753. def _get_build_args(self, kwargs, state, depends):
  754. args = []
  755. deps = extract_as_list(kwargs, 'dependencies', unholder=True)
  756. cflags, ldflags, gi_includes = self._get_dependencies_flags(deps, state, depends, include_rpath=True)
  757. inc_dirs = mesonlib.extract_as_list(kwargs, 'include_directories')
  758. for incd in inc_dirs:
  759. if not isinstance(incd.held_object, (str, build.IncludeDirs)):
  760. raise MesonException(
  761. 'Gir include dirs should be include_directories().')
  762. cflags.update(get_include_args(inc_dirs))
  763. cflags.update(state.environment.coredata.get_external_args('c'))
  764. ldflags.update(state.environment.coredata.get_external_link_args('c'))
  765. if cflags:
  766. args += ['--cflags=%s' % ' '.join(cflags)]
  767. if ldflags:
  768. args += ['--ldflags=%s' % ' '.join(ldflags)]
  769. compiler = state.environment.coredata.compilers.get('c')
  770. if compiler:
  771. args += ['--cc=%s' % ' '.join(compiler.get_exelist())]
  772. args += ['--ld=%s' % ' '.join(compiler.get_linker_exelist())]
  773. return args
  774. @noKwargs
  775. def gtkdoc_html_dir(self, state, args, kwargs):
  776. if len(args) != 1:
  777. raise MesonException('Must have exactly one argument.')
  778. modulename = args[0]
  779. if not isinstance(modulename, str):
  780. raise MesonException('Argument must be a string')
  781. return ModuleReturnValue(os.path.join('share/gtk-doc/html', modulename), [])
  782. @staticmethod
  783. def _unpack_args(arg, kwarg_name, kwargs, expend_file_state=None):
  784. if kwarg_name not in kwargs:
  785. return []
  786. new_args = mesonlib.extract_as_list(kwargs, kwarg_name)
  787. args = []
  788. for i in new_args:
  789. if expend_file_state and isinstance(i, mesonlib.File):
  790. i = i.absolute_path(expend_file_state.environment.get_source_dir(), expend_file_state.environment.get_build_dir())
  791. elif expend_file_state and isinstance(i, str):
  792. i = os.path.join(expend_file_state.environment.get_source_dir(), expend_file_state.subdir, i)
  793. elif not isinstance(i, str):
  794. raise MesonException(kwarg_name + ' values must be strings.')
  795. args.append(i)
  796. if args:
  797. return [arg + '@@'.join(args)]
  798. return []
  799. def _get_autocleanup_args(self, kwargs, glib_version):
  800. if not mesonlib.version_compare(glib_version, '>= 2.49.1'):
  801. # Warn if requested, silently disable if not
  802. if 'autocleanup' in kwargs:
  803. mlog.warning('Glib version ({}) is too old to support the \'autocleanup\' '
  804. 'kwarg, need 2.49.1 or newer'.format(glib_version))
  805. return []
  806. autocleanup = kwargs.pop('autocleanup', 'all')
  807. values = ('none', 'objects', 'all')
  808. if autocleanup not in values:
  809. raise MesonException('gdbus_codegen does not support {!r} as an autocleanup value, '
  810. 'must be one of: {!r}'.format(autocleanup, ', '.join(values)))
  811. return ['--c-generate-autocleanup', autocleanup]
  812. @FeatureNewKwargs('build target', '0.46.0', ['install_header', 'install_dir', 'sources'])
  813. @FeatureNewKwargs('build target', '0.40.0', ['build_by_default'])
  814. @FeatureNewKwargs('build target', '0.47.0', ['extra_args', 'autocleanup'])
  815. @permittedKwargs({'interface_prefix', 'namespace', 'extra_args', 'autocleanup', 'object_manager', 'build_by_default',
  816. 'annotations', 'docbook', 'install_header', 'install_dir', 'sources'})
  817. def gdbus_codegen(self, state, args, kwargs):
  818. if len(args) not in (1, 2):
  819. raise MesonException('gdbus_codegen takes at most two arguments, name and xml file.')
  820. namebase = args[0]
  821. xml_files = args[1:]
  822. target_name = namebase + '-gdbus'
  823. cmd = [self.interpreter.find_program_impl('gdbus-codegen')]
  824. extra_args = mesonlib.stringlistify(kwargs.pop('extra_args', []))
  825. cmd += extra_args
  826. # Autocleanup supported?
  827. glib_version = self._get_native_glib_version(state)
  828. cmd += self._get_autocleanup_args(kwargs, glib_version)
  829. if 'interface_prefix' in kwargs:
  830. cmd += ['--interface-prefix', kwargs.pop('interface_prefix')]
  831. if 'namespace' in kwargs:
  832. cmd += ['--c-namespace', kwargs.pop('namespace')]
  833. if kwargs.get('object_manager', False):
  834. cmd += ['--c-generate-object-manager']
  835. if 'sources' in kwargs:
  836. xml_files += mesonlib.listify(kwargs.pop('sources'))
  837. build_by_default = kwargs.get('build_by_default', False)
  838. # Annotations are a bit ugly in that they are a list of lists of strings...
  839. annotations = kwargs.pop('annotations', [])
  840. if not isinstance(annotations, list):
  841. raise MesonException('annotations takes a list')
  842. if annotations and isinstance(annotations, list) and not isinstance(annotations[0], list):
  843. annotations = [annotations]
  844. for annotation in annotations:
  845. if len(annotation) != 3 or not all(isinstance(i, str) for i in annotation):
  846. raise MesonException('Annotations must be made up of 3 strings for ELEMENT, KEY, and VALUE')
  847. cmd += ['--annotate'] + annotation
  848. targets = []
  849. install_header = kwargs.get('install_header', False)
  850. install_dir = kwargs.get('install_dir', state.environment.coredata.get_builtin_option('includedir'))
  851. output = namebase + '.c'
  852. # Added in https://gitlab.gnome.org/GNOME/glib/commit/e4d68c7b3e8b01ab1a4231bf6da21d045cb5a816 (2.55.2)
  853. # Fixed in https://gitlab.gnome.org/GNOME/glib/commit/cd1f82d8fc741a2203582c12cc21b4dacf7e1872 (2.56.2)
  854. if mesonlib.version_compare(glib_version, '>= 2.56.2'):
  855. custom_kwargs = {'input': xml_files,
  856. 'output': output,
  857. 'command': cmd + ['--body', '--output', '@OUTPUT@', '@INPUT@'],
  858. 'build_by_default': build_by_default
  859. }
  860. else:
  861. if 'docbook' in kwargs:
  862. docbook = kwargs['docbook']
  863. if not isinstance(docbook, str):
  864. raise MesonException('docbook value must be a string.')
  865. cmd += ['--generate-docbook', docbook]
  866. # https://git.gnome.org/browse/glib/commit/?id=ee09bb704fe9ccb24d92dd86696a0e6bb8f0dc1a
  867. if mesonlib.version_compare(glib_version, '>= 2.51.3'):
  868. cmd += ['--output-directory', '@OUTDIR@', '--generate-c-code', namebase, '@INPUT@']
  869. else:
  870. self._print_gdbus_warning()
  871. cmd += ['--generate-c-code', '@OUTDIR@/' + namebase, '@INPUT@']
  872. custom_kwargs = {'input': xml_files,
  873. 'output': output,
  874. 'command': cmd,
  875. 'build_by_default': build_by_default
  876. }
  877. cfile_custom_target = build.CustomTarget(output, state.subdir, state.subproject, custom_kwargs)
  878. targets.append(cfile_custom_target)
  879. output = namebase + '.h'
  880. if mesonlib.version_compare(glib_version, '>= 2.56.2'):
  881. custom_kwargs = {'input': xml_files,
  882. 'output': output,
  883. 'command': cmd + ['--header', '--output', '@OUTPUT@', '@INPUT@'],
  884. 'build_by_default': build_by_default,
  885. 'install': install_header,
  886. 'install_dir': install_dir
  887. }
  888. else:
  889. custom_kwargs = {'input': xml_files,
  890. 'output': output,
  891. 'command': cmd,
  892. 'build_by_default': build_by_default,
  893. 'install': install_header,
  894. 'install_dir': install_dir,
  895. 'depends': cfile_custom_target
  896. }
  897. hfile_custom_target = build.CustomTarget(output, state.subdir, state.subproject, custom_kwargs)
  898. targets.append(hfile_custom_target)
  899. if 'docbook' in kwargs:
  900. docbook = kwargs['docbook']
  901. if not isinstance(docbook, str):
  902. raise MesonException('docbook value must be a string.')
  903. docbook_cmd = cmd + ['--output-directory', '@OUTDIR@', '--generate-docbook', docbook, '@INPUT@']
  904. # The docbook output is always ${docbook}-${name_of_xml_file}
  905. output = namebase + '-docbook'
  906. outputs = []
  907. for f in xml_files:
  908. outputs.append('{}-{}'.format(docbook, f))
  909. if mesonlib.version_compare(glib_version, '>= 2.56.2'):
  910. custom_kwargs = {'input': xml_files,
  911. 'output': outputs,
  912. 'command': docbook_cmd,
  913. 'build_by_default': build_by_default
  914. }
  915. else:
  916. custom_kwargs = {'input': xml_files,
  917. 'output': outputs,
  918. 'command': cmd,
  919. 'build_by_default': build_by_default,
  920. 'depends': cfile_custom_target
  921. }
  922. docbook_custom_target = build.CustomTarget(output, state.subdir, state.subproject, custom_kwargs)
  923. targets.append(docbook_custom_target)
  924. return ModuleReturnValue(targets, targets)
  925. @permittedKwargs({'sources', 'c_template', 'h_template', 'install_header', 'install_dir',
  926. 'comments', 'identifier_prefix', 'symbol_prefix', 'eprod', 'vprod',
  927. 'fhead', 'fprod', 'ftail', 'vhead', 'vtail', 'depends'})
  928. def mkenums(self, state, args, kwargs):
  929. if len(args) != 1:
  930. raise MesonException('Mkenums requires one positional argument.')
  931. basename = args[0]
  932. if 'sources' not in kwargs:
  933. raise MesonException('Missing keyword argument "sources".')
  934. sources = kwargs.pop('sources')
  935. if isinstance(sources, str):
  936. sources = [sources]
  937. elif not isinstance(sources, list):
  938. raise MesonException(
  939. 'Sources keyword argument must be a string or array.')
  940. cmd = []
  941. known_kwargs = ['comments', 'eprod', 'fhead', 'fprod', 'ftail',
  942. 'identifier_prefix', 'symbol_prefix', 'template',
  943. 'vhead', 'vprod', 'vtail']
  944. known_custom_target_kwargs = ['install_dir', 'build_always',
  945. 'depends', 'depend_files']
  946. c_template = h_template = None
  947. install_header = False
  948. for arg, value in kwargs.items():
  949. if arg == 'sources':
  950. raise AssertionError("sources should've already been handled")
  951. elif arg == 'c_template':
  952. c_template = value
  953. if isinstance(c_template, mesonlib.File):
  954. c_template = c_template.absolute_path(state.environment.source_dir, state.environment.build_dir)
  955. if 'template' in kwargs:
  956. raise MesonException('Mkenums does not accept both '
  957. 'c_template and template keyword '
  958. 'arguments at the same time.')
  959. elif arg == 'h_template':
  960. h_template = value
  961. if isinstance(h_template, mesonlib.File):
  962. h_template = h_template.absolute_path(state.environment.source_dir, state.environment.build_dir)
  963. if 'template' in kwargs:
  964. raise MesonException('Mkenums does not accept both '
  965. 'h_template and template keyword '
  966. 'arguments at the same time.')
  967. elif arg == 'install_header':
  968. install_header = value
  969. elif arg in known_kwargs:
  970. cmd += ['--' + arg.replace('_', '-'), value]
  971. elif arg not in known_custom_target_kwargs:
  972. raise MesonException(
  973. 'Mkenums does not take a %s keyword argument.' % (arg, ))
  974. cmd = [self.interpreter.find_program_impl(['glib-mkenums', 'mkenums'])] + cmd
  975. custom_kwargs = {}
  976. for arg in known_custom_target_kwargs:
  977. if arg in kwargs:
  978. custom_kwargs[arg] = kwargs[arg]
  979. targets = []
  980. if h_template is not None:
  981. h_output = os.path.basename(os.path.splitext(h_template)[0])
  982. # We always set template as the first element in the source array
  983. # so --template consumes it.
  984. h_cmd = cmd + ['--template', '@INPUT@']
  985. h_sources = [h_template] + sources
  986. custom_kwargs['install'] = install_header
  987. if 'install_dir' not in custom_kwargs:
  988. custom_kwargs['install_dir'] = \
  989. state.environment.coredata.get_builtin_option('includedir')
  990. h_target = self._make_mkenum_custom_target(state, h_sources,
  991. h_output, h_cmd,
  992. custom_kwargs)
  993. targets.append(h_target)
  994. if c_template is not None:
  995. c_output = os.path.basename(os.path.splitext(c_template)[0])
  996. # We always set template as the first element in the source array
  997. # so --template consumes it.
  998. c_cmd = cmd + ['--template', '@INPUT@']
  999. c_sources = [c_template] + sources
  1000. # Never install the C file. Complain on bug tracker if you need it.
  1001. custom_kwargs['install'] = False
  1002. if h_template is not None:
  1003. if 'depends' in custom_kwargs:
  1004. custom_kwargs['depends'] += [h_target]
  1005. else:
  1006. custom_kwargs['depends'] = h_target
  1007. c_target = self._make_mkenum_custom_target(state, c_sources,
  1008. c_output, c_cmd,
  1009. custom_kwargs)
  1010. targets.insert(0, c_target)
  1011. if c_template is None and h_template is None:
  1012. generic_cmd = cmd + ['@INPUT@']
  1013. custom_kwargs['install'] = install_header
  1014. if 'install_dir' not in custom_kwargs:
  1015. custom_kwargs['install_dir'] = \
  1016. state.environment.coredata.get_builtin_option('includedir')
  1017. target = self._make_mkenum_custom_target(state, sources, basename,
  1018. generic_cmd, custom_kwargs)
  1019. return ModuleReturnValue(target, [target])
  1020. elif len(targets) == 1:
  1021. return ModuleReturnValue(targets[0], [targets[0]])
  1022. else:
  1023. return ModuleReturnValue(targets, targets)
  1024. @FeatureNew('gnome.mkenums_simple', '0.42.0')
  1025. def mkenums_simple(self, state, args, kwargs):
  1026. hdr_filename = args[0] + '.h'
  1027. body_filename = args[0] + '.c'
  1028. # not really needed, just for sanity checking
  1029. forbidden_kwargs = ['c_template', 'h_template', 'eprod', 'fhead',
  1030. 'fprod', 'ftail', 'vhead', 'vtail', 'comments']
  1031. for arg in forbidden_kwargs:
  1032. if arg in kwargs:
  1033. raise MesonException('mkenums_simple() does not take a %s keyword argument' % (arg, ))
  1034. # kwargs to pass as-is from mkenums_simple() to mkenums()
  1035. shared_kwargs = ['sources', 'install_header', 'install_dir',
  1036. 'identifier_prefix', 'symbol_prefix']
  1037. mkenums_kwargs = {}
  1038. for arg in shared_kwargs:
  1039. if arg in kwargs:
  1040. mkenums_kwargs[arg] = kwargs[arg]
  1041. # .c file generation
  1042. c_file_kwargs = copy.deepcopy(mkenums_kwargs)
  1043. if 'sources' not in kwargs:
  1044. raise MesonException('Missing keyword argument "sources".')
  1045. sources = kwargs['sources']
  1046. if isinstance(sources, str):
  1047. sources = [sources]
  1048. elif not isinstance(sources, list):
  1049. raise MesonException(
  1050. 'Sources keyword argument must be a string or array.')
  1051. # The `install_header` argument will be used by mkenums() when
  1052. # not using template files, so we need to forcibly unset it
  1053. # when generating the C source file, otherwise we will end up
  1054. # installing it
  1055. c_file_kwargs['install_header'] = False
  1056. header_prefix = kwargs.get('header_prefix', '')
  1057. decl_decorator = kwargs.get('decorator', '')
  1058. func_prefix = kwargs.get('function_prefix', '')
  1059. body_prefix = kwargs.get('body_prefix', '')
  1060. # Maybe we should write our own template files into the build dir
  1061. # instead, but that seems like much more work, nice as it would be.
  1062. fhead = ''
  1063. if body_prefix != '':
  1064. fhead += '%s\n' % body_prefix
  1065. fhead += '#include "%s"\n' % hdr_filename
  1066. for hdr in sources:
  1067. fhead += '#include "%s"\n' % os.path.basename(str(hdr))
  1068. fhead += '''
  1069. #define C_ENUM(v) ((gint) v)
  1070. #define C_FLAGS(v) ((guint) v)
  1071. '''
  1072. c_file_kwargs['fhead'] = fhead
  1073. c_file_kwargs['fprod'] = '''
  1074. /* enumerations from "@basename@" */
  1075. '''
  1076. c_file_kwargs['vhead'] = '''
  1077. GType
  1078. %s@enum_name@_get_type (void)
  1079. {
  1080. static volatile gsize gtype_id = 0;
  1081. static const G@Type@Value values[] = {''' % func_prefix
  1082. c_file_kwargs['vprod'] = ' { C_@TYPE@(@VALUENAME@), "@VALUENAME@", "@valuenick@" },'
  1083. c_file_kwargs['vtail'] = ''' { 0, NULL, NULL }
  1084. };
  1085. if (g_once_init_enter (&gtype_id)) {
  1086. GType new_type = g_@type@_register_static ("@EnumName@", values);
  1087. g_once_init_leave (&gtype_id, new_type);
  1088. }
  1089. return (GType) gtype_id;
  1090. }'''
  1091. rv = self.mkenums(state, [body_filename], c_file_kwargs)
  1092. c_file = rv.return_value
  1093. # .h file generation
  1094. h_file_kwargs = copy.deepcopy(mkenums_kwargs)
  1095. h_file_kwargs['fhead'] = '''#pragma once
  1096. #include <glib-object.h>
  1097. {}
  1098. G_BEGIN_DECLS
  1099. '''.format(header_prefix)
  1100. h_file_kwargs['fprod'] = '''
  1101. /* enumerations from "@basename@" */
  1102. '''
  1103. h_file_kwargs['vhead'] = '''
  1104. {}
  1105. GType {}@enum_name@_get_type (void);
  1106. #define @ENUMPREFIX@_TYPE_@ENUMSHORT@ ({}@enum_name@_get_type())'''.format(decl_decorator, func_prefix, func_prefix)
  1107. h_file_kwargs['ftail'] = '''
  1108. G_END_DECLS'''
  1109. rv = self.mkenums(state, [hdr_filename], h_file_kwargs)
  1110. h_file = rv.return_value
  1111. return ModuleReturnValue([c_file, h_file], [c_file, h_file])
  1112. @staticmethod
  1113. def _make_mkenum_custom_target(state, sources, output, cmd, kwargs):
  1114. custom_kwargs = {
  1115. 'input': sources,
  1116. 'output': output,
  1117. 'capture': True,
  1118. 'command': cmd
  1119. }
  1120. custom_kwargs.update(kwargs)
  1121. return build.CustomTarget(output, state.subdir, state.subproject, custom_kwargs,
  1122. # https://github.com/mesonbuild/meson/issues/973
  1123. absolute_paths=True)
  1124. @permittedKwargs({'sources', 'prefix', 'install_header', 'install_dir', 'stdinc',
  1125. 'nostdinc', 'internal', 'skip_source', 'valist_marshallers',
  1126. 'extra_args'})
  1127. def genmarshal(self, state, args, kwargs):
  1128. if len(args) != 1:
  1129. raise MesonException(
  1130. 'Genmarshal requires one positional argument.')
  1131. output = args[0]
  1132. if 'sources' not in kwargs:
  1133. raise MesonException('Missing keyword argument "sources".')
  1134. sources = kwargs.pop('sources')
  1135. if isinstance(sources, str):
  1136. sources = [sources]
  1137. elif not isinstance(sources, list):
  1138. raise MesonException(
  1139. 'Sources keyword argument must be a string or array.')
  1140. new_genmarshal = mesonlib.version_compare(self._get_native_glib_version(state), '>= 2.53.3')
  1141. cmd = [self.interpreter.find_program_impl('glib-genmarshal')]
  1142. known_kwargs = ['internal', 'nostdinc', 'skip_source', 'stdinc',
  1143. 'valist_marshallers', 'extra_args']
  1144. known_custom_target_kwargs = ['build_always', 'depends',
  1145. 'depend_files', 'install_dir',
  1146. 'install_header']
  1147. for arg, value in kwargs.items():
  1148. if arg == 'prefix':
  1149. cmd += ['--prefix', value]
  1150. elif arg == 'extra_args':
  1151. if new_genmarshal:
  1152. cmd += mesonlib.stringlistify(value)
  1153. else:
  1154. mlog.warning('The current version of GLib does not support extra arguments \n'
  1155. 'for glib-genmarshal. You need at least GLib 2.53.3. See ',
  1156. mlog.bold('https://github.com/mesonbuild/meson/pull/2049'))
  1157. elif arg in known_kwargs and value:
  1158. cmd += ['--' + arg.replace('_', '-')]
  1159. elif arg not in known_custom_target_kwargs:
  1160. raise MesonException(
  1161. 'Genmarshal does not take a %s keyword argument.' % (
  1162. arg, ))
  1163. install_header = kwargs.pop('install_header', False)
  1164. install_dir = kwargs.pop('install_dir', None)
  1165. custom_kwargs = {
  1166. 'input': sources,
  1167. }
  1168. # https://github.com/GNOME/glib/commit/0fbc98097fac4d3e647684f344e508abae109fdf
  1169. if mesonlib.version_compare(self._get_native_glib_version(state), '>= 2.51.0'):
  1170. cmd += ['--output', '@OUTPUT@']
  1171. else:
  1172. custom_kwargs['capture'] = True
  1173. for arg in known_custom_target_kwargs:
  1174. if arg in kwargs:
  1175. custom_kwargs[arg] = kwargs[arg]
  1176. header_file = output + '.h'
  1177. custom_kwargs['command'] = cmd + ['--body', '@INPUT@']
  1178. if mesonlib.version_compare(self._get_native_glib_version(state), '>= 2.53.4'):
  1179. # Silence any warnings about missing prototypes
  1180. custom_kwargs['command'] += ['--include-header', header_file]
  1181. custom_kwargs['output'] = output + '.c'
  1182. body = build.CustomTarget(output + '_c', state.subdir, state.subproject, custom_kwargs)
  1183. custom_kwargs['install'] = install_header
  1184. if install_dir is not None:
  1185. custom_kwargs['install_dir'] = install_dir
  1186. if new_genmarshal:
  1187. cmd += ['--pragma-once']
  1188. custom_kwargs['command'] = cmd + ['--header', '@INPUT@']
  1189. custom_kwargs['output'] = header_file
  1190. header = build.CustomTarget(output + '_h', state.subdir, state.subproject, custom_kwargs)
  1191. rv = [body, header]
  1192. return ModuleReturnValue(rv, rv)
  1193. @staticmethod
  1194. def _vapi_args_to_command(prefix, variable, kwargs, accept_vapi=False):
  1195. arg_list = mesonlib.extract_as_list(kwargs, variable)
  1196. ret = []
  1197. for arg in arg_list:
  1198. if not isinstance(arg, str):
  1199. types = 'strings' + ' or InternalDependencys' if accept_vapi else ''
  1200. raise MesonException('All {} must be {}'.format(variable, types))
  1201. ret.append(prefix + arg)
  1202. return ret
  1203. def _extract_vapi_packages(self, state, kwargs):
  1204. '''
  1205. Packages are special because we need to:
  1206. - Get a list of packages for the .deps file
  1207. - Get a list of depends for any VapiTargets
  1208. - Get package name from VapiTargets
  1209. - Add include dirs for any VapiTargets
  1210. '''
  1211. arg_list = kwargs.get('packages')
  1212. if not arg_list:
  1213. return [], [], [], []
  1214. arg_list = mesonlib.listify(arg_list)
  1215. vapi_depends = []
  1216. vapi_packages = []
  1217. vapi_includes = []
  1218. ret = []
  1219. remaining_args = []
  1220. for arg in arg_list:
  1221. if hasattr(arg, 'held_object'):
  1222. arg = arg.held_object
  1223. if isinstance(arg, InternalDependency):
  1224. targets = [t for t in arg.sources if isinstance(t, VapiTarget)]
  1225. for target in targets:
  1226. srcdir = os.path.join(state.environment.get_source_dir(),
  1227. target.get_subdir())
  1228. outdir = os.path.join(state.environment.get_build_dir(),
  1229. target.get_subdir())
  1230. outfile = target.get_outputs()[0][:-5] # Strip .vapi
  1231. ret.append('--vapidir=' + outdir)
  1232. ret.append('--girdir=' + outdir)
  1233. ret.append('--pkg=' + outfile)
  1234. vapi_depends.append(target)
  1235. vapi_packages.append(outfile)
  1236. vapi_includes.append(srcdir)
  1237. else:
  1238. vapi_packages.append(arg)
  1239. remaining_args.append(arg)
  1240. kwargs['packages'] = remaining_args
  1241. vapi_args = ret + self._vapi_args_to_command('--pkg=', 'packages', kwargs, accept_vapi=True)
  1242. return vapi_args, vapi_depends, vapi_packages, vapi_includes
  1243. def _generate_deps(self, state, library, packages, install_dir):
  1244. outdir = state.environment.scratch_dir
  1245. fname = os.path.join(outdir, library + '.deps')
  1246. with open(fname, 'w') as ofile:
  1247. for package in packages:
  1248. ofile.write(package + '\n')
  1249. return build.Data(mesonlib.File(True, outdir, fname), install_dir)
  1250. def _get_vapi_link_with(self, target):
  1251. link_with = []
  1252. for dep in target.get_target_dependencies():
  1253. if isinstance(dep, build.SharedLibrary):
  1254. link_with.append(dep)
  1255. elif isinstance(dep, GirTarget):
  1256. link_with += self._get_vapi_link_with(dep)
  1257. return link_with
  1258. @permittedKwargs({'sources', 'packages', 'metadata_dirs', 'gir_dirs',
  1259. 'vapi_dirs', 'install', 'install_dir'})
  1260. def generate_vapi(self, state, args, kwargs):
  1261. if len(args) != 1:
  1262. raise MesonException('The library name is required')
  1263. if not isinstance(args[0], str):
  1264. raise MesonException('The first argument must be the name of the library')
  1265. created_values = []
  1266. library = args[0]
  1267. build_dir = os.path.join(state.environment.get_build_dir(), state.subdir)
  1268. source_dir = os.path.join(state.environment.get_source_dir(), state.subdir)
  1269. pkg_cmd, vapi_depends, vapi_packages, vapi_includes = self._extract_vapi_packages(state, kwargs)
  1270. if 'VAPIGEN' in os.environ:
  1271. cmd = [self.interpreter.find_program_impl(os.environ['VAPIGEN'])]
  1272. else:
  1273. cmd = [self.interpreter.find_program_impl('vapigen')]
  1274. cmd += ['--quiet', '--library=' + library, '--directory=' + build_dir]
  1275. cmd += self._vapi_args_to_command('--vapidir=', 'vapi_dirs', kwargs)
  1276. cmd += self._vapi_args_to_command('--metadatadir=', 'metadata_dirs', kwargs)
  1277. cmd += self._vapi_args_to_command('--girdir=', 'gir_dirs', kwargs)
  1278. cmd += pkg_cmd
  1279. cmd += ['--metadatadir=' + source_dir]
  1280. if 'sources' not in kwargs:
  1281. raise MesonException('sources are required to generate the vapi file')
  1282. inputs = mesonlib.extract_as_list(kwargs, 'sources')
  1283. link_with = []
  1284. for i in inputs:
  1285. if isinstance(i, str):
  1286. cmd.append(os.path.join(source_dir, i))
  1287. elif hasattr(i, 'held_object') and isinstance(i.held_object, GirTarget):
  1288. link_with += self._get_vapi_link_with(i.held_object)
  1289. subdir = os.path.join(state.environment.get_build_dir(),
  1290. i.held_object.get_subdir())
  1291. gir_file = os.path.join(subdir, i.held_object.get_outputs()[0])
  1292. cmd.append(gir_file)
  1293. else:
  1294. raise MesonException('Input must be a str or GirTarget')
  1295. vapi_output = library + '.vapi'
  1296. custom_kwargs = {
  1297. 'command': cmd,
  1298. 'input': inputs,
  1299. 'output': vapi_output,
  1300. 'depends': vapi_depends,
  1301. }
  1302. install_dir = kwargs.get('install_dir',
  1303. os.path.join(state.environment.coredata.get_builtin_option('datadir'),
  1304. 'vala', 'vapi'))
  1305. if kwargs.get('install'):
  1306. custom_kwargs['install'] = kwargs['install']
  1307. custom_kwargs['install_dir'] = install_dir
  1308. # We shouldn't need this locally but we install it
  1309. deps_target = self._generate_deps(state, library, vapi_packages, install_dir)
  1310. created_values.append(deps_target)
  1311. vapi_target = VapiTarget(vapi_output, state.subdir, state.subproject, custom_kwargs)
  1312. # So to try our best to get this to just work we need:
  1313. # - link with with the correct library
  1314. # - include the vapi and dependent vapi files in sources
  1315. # - add relevant directories to include dirs
  1316. incs = [build.IncludeDirs(state.subdir, ['.'] + vapi_includes, False)]
  1317. sources = [vapi_target] + vapi_depends
  1318. rv = InternalDependency(None, incs, [], [], link_with, [], sources, [])
  1319. created_values.append(rv)
  1320. return ModuleReturnValue(rv, created_values)
  1321. def initialize(*args, **kwargs):
  1322. return GnomeModule(*args, **kwargs)