#!/usr/bin/env python## This is the distutils setup script for pygame.# Full instructions are in "install.txt" or "install.html"## To configure, compile, install, just run this script.DESCRIPTION="""Pygame is a Python wrapper module for theSDL multimedia library. It contains python functions and classesthat will allow you to use SDL's support for playing cdroms,audio and video output, and keyboard, mouse and joystick input."""EXTRAS={}METADATA={"name":"pygame","version":"1.9.2pre","license":"LGPL","url":"http://www.pygame.org","author":"Pete Shinners, Rene Dudfield, Marcus von Appen, Bob Pendleton, others...","author_email":"pygame@seul.org","description":"Python Game Development","long_description":DESCRIPTION,}importsysif"bdist_msi"insys.argv:# hack the version name to a format msi doesn't have trouble withMETADATA["version"]=METADATA["version"].replace("pre","a0")METADATA["version"]=METADATA["version"].replace("rc","b0")METADATA["version"]=METADATA["version"].replace("release","")ifnothasattr(sys,'version_info')orsys.version_info<(2,3):raiseSystemExit("Pygame requires Python version 2.3 or above.")#get us to the correct directoryimportos,syspath=os.path.split(os.path.abspath(sys.argv[0]))[0]os.chdir(path)#os.environ["CFLAGS"] = "-W -Wall -Wpointer-arith -Wcast-qual -Winline " + \# "-Wcast-align -Wconversion -Wstrict-prototypes " + \# "-Wmissing-prototypes -Wmissing-declarations " + \# "-Wnested-externs -Wshadow -Wredundant-decls"if"-warnings"insys.argv:os.environ["CFLAGS"]="-W -Wimplicit-int "+ \
"-Wimplicit-function-declaration "+ \
"-Wimplicit -Wmain -Wreturn-type -Wunused -Wswitch "+ \
"-Wcomment -Wtrigraphs -Wformat -Wchar-subscripts "+ \
"-Wuninitialized -Wparentheses "+\
"-Wpointer-arith -Wcast-qual -Winline -Wcast-align "+ \
"-Wconversion -Wstrict-prototypes "+ \
"-Wmissing-prototypes -Wmissing-declarations "+ \
"-Wnested-externs -Wshadow -Wredundant-decls"sys.argv.remove("-warnings")importos.path,glob,stat,shutilimportdistutils.sysconfigfromdistutils.coreimportsetup,Extension,Commandfromdistutils.extensionimportread_setup_filefromdistutils.command.install_dataimportinstall_data# Python 3.0 patchifsys.version_info[0:2]==(3,0):importdistutils.versiondef_cmp(x,y):try:ifx<y:return-1elifx==y:return0return1exceptTypeError:returnNotImplementeddistutils.version.cmp=_cmpdel_cmpdefadd_datafiles(data_files,dest_dir,pattern):"""Add directory structures to data files according to a pattern"""src_dir,elements=patterndefdo_directory(root_dest_path,root_src_path,elements):files=[]foreinelements:ifisinstance(e,list):src_dir,elems=edest_path='/'.join([root_dest_path,src_dir])src_path=os.path.join(root_src_path,src_dir)do_directory(dest_path,src_path,elems)else:files.extend(glob.glob(os.path.join(root_src_path,e)))iffiles:data_files.append((root_dest_path,files))do_directory(dest_dir,src_dir,elements)# allow optionally using setuptools for bdist_egg.if"-setuptools"insys.argv:fromsetuptoolsimportsetup,find_packagessys.argv.remove("-setuptools")# NOTE: the bdist_mpkg_support is for darwin.try:importbdist_mpkg_supportfromsetuptoolsimportsetup,ExtensionexceptImportError:passelse:EXTRAS.update({'options':bdist_mpkg_support.options,'setup_requires':['bdist_mpkg>=0.4.2'],#'install_requires': ['pyobjc'],#'dependency_links': ['http://rene.f0o.com/~rene/stuff/macosx/']})#headers to installheaders=glob.glob(os.path.join('src','*.h'))headers.remove(os.path.join('src','numeric_arrayobject.h'))headers.remove(os.path.join('src','scale.h'))# option for not installing the headers.if"-noheaders"insys.argv:headers=[]sys.argv.remove("-noheaders")#sanity check for any argumentsiflen(sys.argv)==1:reply=raw_input('\nNo Arguments Given, Perform Default Install? [Y/n]')ifnotreplyorreply[0].lower()!='n':sys.argv.append('install')#make sure there is a Setup fileifnotos.path.isfile('Setup'):print('\n\nWARNING, No "Setup" File Exists, Running "config.py"')importconfigconfig.main()print('\nContinuing With "setup.py"')try:s_mtime=os.stat("Setup")[stat.ST_MTIME]sin_mtime=os.stat("Setup.in")[stat.ST_MTIME]ifsin_mtime>s_mtime:print('\n\nWARNING, "Setup.in" newer than "Setup",''you might need to modify "Setup".')except:pass# get compile info for all extensionstry:extensions=read_setup_file('Setup')except:print("""Error with the "Setup" file,perhaps make a clean copy from "Setup.in".""")raise#python 3.x: remove modules not yet portedifsys.version_info>=(3,0,0):python3_skip=['_movie','_numericsurfarray','_numericsndarray',]# if (sys.platform != 'linux2'):# python3_skip.append('scrap')tmp_extensions=extensionsextensions=[]foreintmp_extensions:ife.nameinpython3_skip:print("Skipping module %s for Python %s build."%(e.name,sys.version))else:extensions.append(e)deltmp_extensions# if not building font, try replacing with ftfontalternate_font=os.path.join('lib','font.py')ifos.path.exists(alternate_font):os.remove(alternate_font)have_font=Falsehave_freetype=Falseforeinextensions:ife.name=='font':have_font=Trueife.name=='_freetype':have_freetype=Trueifnothave_fontandhave_freetype:shutil.copyfile(os.path.join('lib','ftfont.py'),alternate_font)#extra files to installdata_path=os.path.join(distutils.sysconfig.get_python_lib(),'pygame')pygame_data_files=[]data_files=[('pygame',pygame_data_files)]#add files in distribution directorypygame_data_files.append('LGPL')pygame_data_files.append('readme.html')pygame_data_files.append('install.html')#add non .py files in lib directoryforfinglob.glob(os.path.join('lib','*')):ifnotf[-3:]=='.py'andnotf[-4:]=='.doc'andos.path.isfile(f):pygame_data_files.append(f)#tests/fixturesadd_datafiles(data_files,'pygame/tests',['test',[['fixtures',[['xbm_cursors',['*.xbm']],['fonts',['*.ttf','*.otf']]]]]])#examplesadd_datafiles(data_files,'pygame/examples',['examples',['readme.rst',['data',['*']],['macosx',['*.py',['aliens_app_example',['*.py','README.txt',['English.lproj',['aliens.icns',['MainMenu.nib',['*']]]]]]]]]])#docsadd_datafiles(data_files,'pygame/docs',['docs',['*.html',# Navigation and help pages'*.gif',# Pygame logos'*.js',# For doc search['ref',# Pygame reference['*.html',# Reference pages'*.js',# Comments script'*.json']],# Comment data['tut',# Tutorials['*.html',['chimp',['*.html','*.gif']],['intro',['*.html','*.gif','*.jpg']],['surfarray',['*.html','*.jpg']],['tom',['*.html','*.png']],['camera',['*.html','*.jpg']]]],['_static',# Sphinx added support files['*.css','*.png','*.ico','*.js']],['_sources',# Used for ref search['*.txt',['ref',['*.txt']]]]]])#required. This will be filled if doing a Windows build.cmdclass={}#try to find DLLs and copy them too (only on windows)ifsys.platform=='win32':fromdistutils.command.build_extimportbuild_ext# mingw32distutils is optional. But we need the mingw32 compiler(s).try:# Allow the choice between Win32 GUI and console DLLs.importmingw32distutilsexceptImportError:mingw32_compilers=['ming32']else:mingw32_compilers=mingw32distutils.compilersifsys.version_info<(2,4):try:importconfig# a separate method for finding dlls with mingw.ifconfig.is_msys_mingw():# fix up the paths for msys compiling.importdistutils_modsdistutils.cygwinccompiler.Mingw32=distutils_mods.mingcompexceptImportError:pass#add dependency DLLs to the projectlib_dependencies={}foreinextensions:ife.name.startswith('COPYLIB_'):lib_dependencies[e.name[8:]]=e.librariesdefdependencies(roots):"""Return a set of dependencies for the list of library file roots The return set is a dictionary keyed on library root name with values of 1. """root_set={}forrootinroots:try:deps=lib_dependencies[root]exceptKeyError:passelse:root_set[root]=1root_set.update(dependencies(deps))returnroot_setthe_dlls={}required_dlls={}foreinextensions:ife.name.startswith('COPYLIB_'):the_dlls[e.name[8:]]=e.library_dirs[0]else:required_dlls.update(dependencies(e.libraries))# join the required_dlls and the_dlls keys together.lib_names={}forlibinlist(required_dlls.keys())+list(the_dlls.keys()):lib_names[lib]=1forlibinlib_names.keys():#next DLL; a distutils bug requires the paths to have Windows separatorsf=the_dlls[lib].replace('/',os.sep)iff=='_':print("WARNING, DLL for %s library not found."%lib)else:pygame_data_files.append(f)classWinBuildExt(build_ext):"""This build_ext sets necessary environment variables for MinGW"""# __sdl_lib_dir is possible location of msvcrt replacement import# libraries, if they exist. Pygame module base only links to SDL so# should have the SDL library directory as its only -L option.foreinextensions:ife.name=='base':__sdl_lib_dir=e.library_dirs[0].replace('/',os.sep)breakdefrun(self):"""Extended to set MINGW_ROOT_DIRECTORY, PATH and LIBRARY_PATH"""ifself.compilerinmingw32_compilers:# Add MinGW environment variables.if'MINGW_ROOT_DIRECTORY'notinos.environ:# Use MinGW setup conifiguration file if present.importmingwcfgtry:mingw_root=mingwcfg.read()exceptIOError:raiseRuntimeError("mingw32: required environment variable"" MINGW_ROOT_DIRECTORY not set")os.environ['MINGW_ROOT_DIRECTORY']=mingw_rootpath=os.environ['PATH']os.environ['PATH']=';'.join([os.path.join(mingw_root,'bin'),path])ifsys.version_info>=(2,6):# The Visual Studio 2008 C library is msvcr90.dll.c_runtime_path=os.path.join(self.__sdl_lib_dir,'msvcr90')elifsys.version_info>=(2,4):# The Visual Studio 2003 C library is msvcr71.dll.c_runtime_path=os.path.join(self.__sdl_lib_dir,'msvcr71')else:# The Visual Studio 6.0 C library is msvcrt.dll,# the MinGW default.c_runtime_path=''ifc_runtime_pathandos.path.isdir(c_runtime_path):# Override the default msvcrt.dll linkage.os.environ['LIBRARY_PATH']=c_runtime_pathelifnot(c_runtime_pathorglob.glob(os.path.join(self.__sdl_lib_dir,'msvcr*'))):passelse:raiseRuntimeError("The dependencies are linked to"" the wrong C runtime for"" Python %i.%i"%sys.version_info[:2])build_ext.run(self)cmdclass['build_ext']=WinBuildExt# Add the precompiled smooth scale MMX functions to transform.defreplace_scale_mmx():foreinextensions:ife.name=='transform':if'64 bit'insys.version:e.extra_objects.append(os.path.join('obj','win64','scale_mmx.obj'))else:e.extra_objects.append(os.path.join('obj','win32','scale_mmx.obj'))foriinrange(len(e.sources)):ife.sources[i].endswith('scale_mmx.c'):dele.sources[i]returnreplace_scale_mmx()#clean up the list of extensionsforeinextensions[:]:ife.name.startswith('COPYLIB_'):extensions.remove(e)#don't compile the COPYLIBs, just clean themelse:e.name='pygame.'+e.name#prepend package name on modules#data installer with improved intelligence over distutils#data files are copied into the project directory instead#of willy-nillyclasssmart_install_data(install_data):defrun(self):#need to change self.install_dir to the actual library dirinstall_cmd=self.get_finalized_command('install')self.install_dir=getattr(install_cmd,'install_lib')returninstall_data.run(self)cmdclass['install_data']=smart_install_dataif"bdist_msi"insys.argv:# if you are making an msi, we want it to overwrite filesfromdistutils.commandimportbdist_msiimportmsilibclassbdist_msi_overwrite_on_install(bdist_msi.bdist_msi):defrun(self):bdist_msi.bdist_msi.run(self)# Remove obsolete files.comp="pygame1"# Pygame componentprop=comp# Directory propertyrecords=[("surfarray.pyd",comp,"SURFAR~1.PYD|surfarray.pyd",prop,1),("sndarray.pyd",comp,"SNDARRAY.PYD|sndarray.pyd",prop,1),("camera.pyd",comp,"CAMERA.PYD|camera.pyd",prop,1),("color.py",comp,"COLOR.PY|color.py",prop,1),("color.pyc",comp,"COLOR.PYC|color.pyc",prop,1),("color.pyo",comp,"COLOR.PYO|color.pyo",prop,1)]msilib.add_data(self.db,"RemoveFile",records)# Overwrite outdated files.fullname=self.distribution.get_fullname()installer_name=self.get_installer_filename(fullname)print("changing %s to overwrite files on install"%installer_name)msilib.add_data(self.db,"Property",[("REINSTALLMODE","amus")])self.db.Commit()cmdclass['bdist_msi']=bdist_msi_overwrite_on_install# test command. For doing 'python setup.py test'classTestCommand(Command):user_options=[]definitialize_options(self):self._dir=os.getcwd()deffinalize_options(self):passdefrun(self):''' runs the tests with default options. '''importsubprocessreturnsubprocess.call([sys.executable,"run_tests.py"])cmdclass['test']=TestCommand# Prune empty file lists.date_files=[(path,files)forpath,filesindata_filesiffiles]#finally,#call distutils with all needed infoPACKAGEDATA={"cmdclass":cmdclass,"packages":['pygame','pygame.gp2x','pygame.threads','pygame.tests','pygame.tests.test_utils','pygame.tests.run_tests__tests','pygame.tests.run_tests__tests.all_ok','pygame.tests.run_tests__tests.failures1','pygame.tests.run_tests__tests.incomplete','pygame.tests.run_tests__tests.infinite_loop','pygame.tests.run_tests__tests.print_stderr','pygame.tests.run_tests__tests.print_stdout','pygame.tests.run_tests__tests.incomplete_todo','pygame.tests.run_tests__tests.exclude','pygame.tests.run_tests__tests.timeout','pygame.tests.run_tests__tests.everything','pygame.docs','pygame.examples'],"package_dir":{'pygame':'lib','pygame.threads':'lib/threads','pygame.gp2x':'lib/gp2x','pygame.tests':'test','pygame.docs':'docs','pygame.examples':'examples'},"headers":headers,"ext_modules":extensions,"data_files":data_files,}PACKAGEDATA.update(METADATA)PACKAGEDATA.update(EXTRAS)setup(**PACKAGEDATA)defremove_old_files():# try and figure out where we are installed.#pygame could be installed in a weird location because of # setuptools or something else. The only sane way seems to be by trying# first to import it, and see where the imported one is.# # Otherwise we might delete some files from another installation.try:importpygame.baseuse_pygame=1except:use_pygame=0ifuse_pygame:install_path=os.path.split(pygame.base.__file__)[0]extension_ext=os.path.splitext(pygame.base.__file__)[1]else:ifnotos.path.exists(data_path):returninstall_path=data_pathbase_file=glob.glob(os.path.join(data_path,"base*"))ifnotbase_file:returnextension_ext=os.path.splitext(base_file[0])[1]# here are the .so/.pyd files we need to ask to remove.ext_to_remove=["camera"]# here are the .py/.pyo/.pyc files we need to ask to remove.py_to_remove=["color"]os.path.join(data_path,'color.py')ifos.name=="e32":# Don't warn on Symbian. The color.py is used as a wrapper.py_to_remove=[]# See if any of the files are there.extension_files=["%s%s"%(x,extension_ext)forxinext_to_remove]py_files=["%s%s"%(x,py_ext)forpy_extin[".py",".pyc",".pyo"]forxinpy_to_remove]files=py_files+extension_filesunwanted_files=[]forfinfiles:unwanted_files.append(os.path.join(install_path,f))ask_remove=[]forfinunwanted_files:ifos.path.exists(f):ask_remove.append(f)forfinask_remove:try:print("trying to remove old file :%s: ..."%f)os.remove(f)print("Successfully removed :%s:."%f)except:print("FAILED to remove old file :%s:"%f)if"install"insys.argv:# remove some old files.# only call after a successful install. Should only reach here if there is# a successful install... otherwise setup() raises an error.try:remove_old_files()except:pass