home *** CD-ROM | disk | FTP | other *** search
/ PC Welt 2006 November (DVD) / PCWELT_11_2006.ISO / casper / filesystem.squashfs / usr / share / python-support / python-gobject / gtk-2.0 / dsextras.py
Encoding:
Python Source  |  2006-08-28  |  13.0 KB  |  388 lines

  1. #
  2. # dsextras.py - Extra classes and utilities
  3. #
  4. # TODO:
  5. # Make it possible to import codegen from another dir
  6. #
  7.  
  8. from distutils.command.build_ext import build_ext
  9. from distutils.command.install_lib import install_lib
  10. from distutils.command.install_data import install_data
  11. from distutils.extension import Extension
  12. import fnmatch
  13. import os
  14. import re
  15. import string
  16. import sys
  17.  
  18. GLOBAL_INC = []
  19. GLOBAL_MACROS = []
  20.  
  21. def get_m4_define(varname):
  22.     """Return the value of a m4_define variable as set in configure.in."""
  23.     pattern = re.compile("m4_define\(" + varname + "\,\s*(.+)\)")
  24.     if os.path.exists('configure.ac'):
  25.         fname = 'configure.ac'
  26.     elif os.path.exists('configure.in'):
  27.         fname = 'configure.in'
  28.     else:
  29.         raise SystemExit('could not find configure file')
  30.  
  31.     for line in open(fname).readlines():
  32.         match_obj = pattern.match(line)
  33.         if match_obj:
  34.             return match_obj.group(1)
  35.  
  36.     return None
  37.  
  38. def getoutput(cmd):
  39.     """Return output (stdout or stderr) of executing cmd in a shell."""
  40.     return getstatusoutput(cmd)[1]
  41.  
  42. def getstatusoutput(cmd):
  43.     """Return (status, output) of executing cmd in a shell."""
  44.     if sys.platform == 'win32':
  45.         pipe = os.popen(cmd, 'r')
  46.         text = pipe.read()
  47.         sts = pipe.close() or 0
  48.         if text[-1:] == '\n':
  49.             text = text[:-1]
  50.         return sts, text
  51.     else:
  52.         from commands import getstatusoutput
  53.         return getstatusoutput(cmd)
  54.  
  55. def have_pkgconfig():
  56.     """Checks for the existence of pkg-config"""
  57.     if (sys.platform == 'win32' and
  58.         os.system('pkg-config --version > NUL') == 0):
  59.         return 1
  60.     else:
  61.         if getstatusoutput('pkg-config')[0] == 256:
  62.             return 1
  63.  
  64. def list_files(dir):
  65.     """List all files in a dir, with filename match support:
  66.     for example: glade/*.glade will return all files in the glade directory
  67.     that matches *.glade. It also looks up the full path"""
  68.     if dir.find(os.sep) != -1:
  69.         parts = dir.split(os.sep)
  70.         dir = string.join(parts[:-1], os.sep)
  71.         pattern = parts[-1]
  72.     else:
  73.         pattern = dir
  74.         dir = '.'
  75.  
  76.     dir = os.path.abspath(dir)
  77.     retval = []
  78.     for file in os.listdir(dir):
  79.         if fnmatch.fnmatch(file, pattern):
  80.             retval.append(os.path.join(dir, file))
  81.     return retval
  82.  
  83. def pkgc_version_check(name, longname, req_version):
  84.     is_installed = not os.system('pkg-config --exists %s' % name)
  85.     if not is_installed:
  86.         print "Could not find %s" % longname
  87.         return 0
  88.  
  89.     orig_version = getoutput('pkg-config --modversion %s' % name)
  90.     version = map(int, orig_version.split('.'))
  91.     pkc_version = map(int, req_version.split('.'))
  92.  
  93.     if version >= pkc_version:
  94.         return 1
  95.     else:
  96.         print "Warning: Too old version of %s" % longname
  97.         print "         Need %s, but %s is installed" % \
  98.               (pkc_version, orig_version)
  99.         self.can_build_ok = 0
  100.         return 0
  101.  
  102. class BuildExt(build_ext):
  103.     def init_extra_compile_args(self):
  104.         self.extra_compile_args = []
  105.         if sys.platform == 'win32' and \
  106.            self.compiler.compiler_type == 'mingw32':
  107.             # MSVC compatible struct packing is required.
  108.             # Note gcc2 uses -fnative-struct while gcc3
  109.             # uses -mms-bitfields. Based on the version
  110.             # the proper flag is used below.
  111.             msnative_struct = { '2' : '-fnative-struct',
  112.                                 '3' : '-mms-bitfields' }
  113.             gcc_version = getoutput('gcc -dumpversion')
  114.             print 'using MinGW GCC version %s with %s option' % \
  115.                   (gcc_version, msnative_struct[gcc_version[0]])
  116.             self.extra_compile_args.append(msnative_struct[gcc_version[0]])
  117.  
  118.     def modify_compiler(self):
  119.         if sys.platform == 'win32' and \
  120.            self.compiler.compiler_type == 'mingw32':
  121.             # Remove '-static' linker option to prevent MinGW ld
  122.             # from trying to link with MSVC import libraries.
  123.             if self.compiler.linker_so.count('-static'):
  124.                 self.compiler.linker_so.remove('-static')
  125.  
  126.     def build_extensions(self):
  127.         # Init self.extra_compile_args
  128.         self.init_extra_compile_args()
  129.         # Modify default compiler settings
  130.         self.modify_compiler()
  131.         # Invoke base build_extensions()
  132.         build_ext.build_extensions(self)
  133.  
  134.     def build_extension(self, ext):
  135.         # Add self.extra_compile_args to ext.extra_compile_args
  136.         ext.extra_compile_args += self.extra_compile_args
  137.         # Generate eventual templates before building
  138.         if hasattr(ext, 'generate'):
  139.             ext.generate()
  140.         # Filter out 'c' and 'm' libs when compilic w/ msvc
  141.         if sys.platform == 'win32' and self.compiler.compiler_type == 'msvc':
  142.             save_libs = ext.libraries
  143.             ext.libraries = [lib for lib in ext.libraries 
  144.                              if lib not in ['c', 'm']]
  145.         else:
  146.             save_libs = ext.libraries
  147.         # Invoke base build_extension()
  148.         build_ext.build_extension(self, ext)
  149.         if save_libs != None and save_libs != ext.libraries:
  150.             ext.libraries = save_libs
  151.  
  152. class InstallLib(install_lib):
  153.  
  154.     local_outputs = []
  155.     local_inputs = []
  156.  
  157.     def set_install_dir(self, install_dir):
  158.         self.install_dir = install_dir
  159.  
  160.     def get_outputs(self):
  161.         return install_lib.get_outputs(self) + self.local_outputs
  162.  
  163.     def get_inputs(self):
  164.         return install_lib.get_inputs(self) + self.local_inputs
  165.  
  166. class InstallData(install_data):
  167.  
  168.     local_outputs = []
  169.     local_inputs = []
  170.     template_options = {}
  171.  
  172.     def prepare(self):
  173.         if os.name == "nt":
  174.             self.prefix = os.sep.join(self.install_dir.split(os.sep)[:-3])
  175.         else:
  176.             # default: os.name == "posix"
  177.             self.prefix = os.sep.join(self.install_dir.split(os.sep)[:-4])
  178.  
  179.         self.exec_prefix = '${prefix}/bin'
  180.         self.includedir = '${prefix}/include'
  181.         self.libdir = '${prefix}/lib'
  182.         self.datarootdir = '${prefix}/share'
  183.         self.datadir = '${prefix}/share'
  184.  
  185.         self.add_template_option('prefix', self.prefix)
  186.         self.add_template_option('exec_prefix', self.exec_prefix)
  187.         self.add_template_option('includedir', self.includedir)
  188.         self.add_template_option('libdir', self.libdir)
  189.         self.add_template_option('datarootdir', self.datarootdir)
  190.         self.add_template_option('datadir', self.datadir)
  191.         self.add_template_option('PYTHON', sys.executable)
  192.         self.add_template_option('THREADING_CFLAGS', '')
  193.  
  194.     def set_install_dir(self, install_dir):
  195.         self.install_dir = install_dir
  196.  
  197.     def add_template_option(self, name, value):
  198.         self.template_options['@%s@' % name] = value
  199.  
  200.     def install_template(self, filename, install_dir):
  201.         """Install template filename into target directory install_dir."""
  202.         output_file = os.path.split(filename)[-1][:-3]
  203.  
  204.         template = open(filename).read()
  205.         for key, value in self.template_options.items():
  206.             template = template.replace(key, value)
  207.  
  208.         output = os.path.join(install_dir, output_file)
  209.         self.mkpath(install_dir)
  210.         open(output, 'w').write(template)
  211.         self.local_inputs.append(filename)
  212.         self.local_outputs.append(output)
  213.         return output
  214.  
  215.     def get_outputs(self):
  216.         return install_lib.get_outputs(self) + self.local_outputs
  217.  
  218.     def get_inputs(self):
  219.         return install_lib.get_inputs(self) + self.local_inputs
  220.  
  221. class PkgConfigExtension(Extension):
  222.     # Name of pygobject package extension depends on, can be None
  223.     pygobject_pkc = 'pygobject-2.0'
  224.     can_build_ok = None
  225.     def __init__(self, **kwargs):
  226.         name = kwargs['pkc_name']
  227.         kwargs['include_dirs'] = self.get_include_dirs(name) + GLOBAL_INC
  228.         kwargs['define_macros'] = GLOBAL_MACROS
  229.         kwargs['libraries'] = self.get_libraries(name)
  230.         kwargs['library_dirs'] = self.get_library_dirs(name)
  231.         if 'pygobject_pkc' in kwargs:
  232.             self.pygobject_pkc = kwargs.pop('pygobject_pkc')
  233.         if self.pygobject_pkc:
  234.             kwargs['include_dirs'] += self.get_include_dirs(self.pygobject_pkc)
  235.             kwargs['libraries'] += self.get_libraries(self.pygobject_pkc)
  236.             kwargs['library_dirs'] += self.get_library_dirs(self.pygobject_pkc)
  237.         self.name = kwargs['name']
  238.         self.pkc_name = kwargs['pkc_name']
  239.         self.pkc_version = kwargs['pkc_version']
  240.         del kwargs['pkc_name'], kwargs['pkc_version']
  241.         Extension.__init__(self, **kwargs)
  242.  
  243.     def get_include_dirs(self, names):
  244.         if type(names) != tuple:
  245.             names = (names,)
  246.         retval = []
  247.         for name in names:
  248.             output = getoutput('pkg-config --cflags-only-I %s' % name)
  249.             retval.extend(output.replace('-I', '').split())
  250.         return retval
  251.  
  252.     def get_libraries(self, names):
  253.         if type(names) != tuple:
  254.             names = (names,)
  255.         retval = []
  256.         for name in names:
  257.             output = getoutput('pkg-config --libs-only-l %s' % name)
  258.             retval.extend(output.replace('-l', '').split())
  259.         return retval
  260.  
  261.     def get_library_dirs(self, names):
  262.         if type(names) != tuple:
  263.             names = (names,)
  264.         retval = []
  265.         for name in names:
  266.             output = getoutput('pkg-config --libs-only-L %s' % name)
  267.             retval.extend(output.replace('-L', '').split())
  268.         return retval
  269.  
  270.     def can_build(self):
  271.         """If the pkg-config version found is good enough"""
  272.         if self.can_build_ok != None:
  273.             return self.can_build_ok
  274.  
  275.         if type(self.pkc_name) != tuple:
  276.             reqs = [(self.pkc_name, self.pkc_version)]
  277.         else:
  278.             reqs = zip(self.pkc_name, self.pkc_version)
  279.  
  280.         for package, version in reqs:
  281.             retval = os.system('pkg-config --exists %s' % package)
  282.             if retval:
  283.                 print ("* %s.pc could not be found, bindings for %s"
  284.                        " will not be built." % (package, self.name))
  285.                 self.can_build_ok = 0
  286.                 return 0
  287.  
  288.             orig_version = getoutput('pkg-config --modversion %s' %
  289.                                      package)
  290.             if (map(int, orig_version.split('.')) >=
  291.                 map(int, version.split('.'))):
  292.                 self.can_build_ok = 1
  293.                 return 1
  294.             else:
  295.                 print "Warning: Too old version of %s" % self.pkc_name
  296.                 print "         Need %s, but %s is installed" % \
  297.                       (package, orig_version)
  298.                 self.can_build_ok = 0
  299.                 return 0
  300.  
  301.     def generate(self):
  302.         pass
  303.  
  304. class Template:
  305.     def __init__(self, override, output, defs, prefix,
  306.                  register=[], load_types=None):
  307.         self.override = override
  308.         self.defs = defs
  309.         self.register = register
  310.         self.output = output
  311.         self.prefix = prefix
  312.         self.load_types = load_types
  313.  
  314.     def check_dates(self):
  315.         if not os.path.exists(self.output):
  316.             return 0
  317.  
  318.         files = self.register[:]
  319.         files.append(self.override)
  320. #        files.append('setup.py')
  321.         files.append(self.defs)
  322.  
  323.         newest = 0
  324.         for file in files:
  325.             test = os.stat(file)[8]
  326.             if test > newest:
  327.                 newest = test
  328.  
  329.         if newest < os.stat(self.output)[8]:
  330.             return 1
  331.         return 0
  332.  
  333.     def generate(self):
  334.         # We must insert it first, otherwise python will try '.' first,
  335.         # in which it exist a "bogus" codegen (the third import line
  336.         # here will fail)
  337.         sys.path.insert(0, 'codegen')
  338.         from override import Overrides
  339.         from defsparser import DefsParser
  340.         from codegen import register_types, write_source, FileOutput
  341.  
  342.         if self.check_dates():
  343.             return
  344.  
  345.         for item in self.register:
  346.             dp = DefsParser(item,dict(GLOBAL_MACROS))
  347.             dp.startParsing()
  348.             register_types(dp)
  349.  
  350.         if self.load_types:
  351.             globals = {}
  352.             execfile(self.load_types, globals)
  353.  
  354.         dp = DefsParser(self.defs,dict(GLOBAL_MACROS))
  355.         dp.startParsing()
  356.         register_types(dp)
  357.  
  358.         fd = open(self.output, 'w')
  359.         write_source(dp,
  360.                      Overrides(self.override),
  361.                      self.prefix,
  362.                      FileOutput(fd, self.output))
  363.         fd.close()
  364.  
  365. class TemplateExtension(PkgConfigExtension):
  366.     def __init__(self, **kwargs):
  367.         name = kwargs['name']
  368.         defs = kwargs['defs']
  369.         output = defs[:-5] + '.c'
  370.         override = kwargs['override']
  371.         load_types = kwargs.get('load_types')
  372.         self.templates = []
  373.         self.templates.append(Template(override, output, defs, 'py' + name,
  374.                                        kwargs['register'], load_types))
  375.  
  376.         del kwargs['register'], kwargs['override'], kwargs['defs']
  377.         if load_types:
  378.             del kwargs['load_types']
  379.  
  380.         if kwargs.has_key('output'):
  381.             kwargs['name'] = kwargs['output']
  382.             del kwargs['output']
  383.  
  384.         PkgConfigExtension.__init__(self, **kwargs)
  385.  
  386.     def generate(self):
  387.         map(lambda x: x.generate(), self.templates)
  388.