small fixes
[swftools.git] / setup.py
1 #!/usr/bin/env python
2
3 from distutils import ccompiler
4 from distutils.core import CompileError
5
6 try:
7     from setuptools import setup, Extension
8 except ImportError:
9     from distutils.core import setup, Extension
10
11 cc = ccompiler.new_compiler()
12
13 import os
14 import sys
15 import stat
16
17 DATADIR = "/usr/share/swftools/"
18
19 def update_dirs(list1, list2):
20     for v in list2:
21         if v not in list1 and os.path.isdir(v):
22             list1.append(v)
23
24 def update_list(list1, list2):
25     for v in list2:
26         if v not in list1:
27             list1.append(v)
28
29 COMPILER_OPTIONS = ['-fPIC', '-Wparentheses', '-Wimplicit', '-Wreturn-type',
30                     '-O3', '-fomit-frame-pointer', '-Winline', 
31                     '-Wno-unused', '-Wno-strict-prototypes','-DHAVE_CONFIG_H',
32                     '-DSWFTOOLS_DATADIR="'+DATADIR+'"']
33 INCLUDE=['lib/lame/', 'lib/pdf/xpdf', 'lib/pdf']
34
35 if 'library_dirs' in os.environ:
36     update_dirs(cc.library_dirs, [path.strip() for path in os.environ.get('library_dirs').strip().split(":")])
37 else:
38     update_dirs(cc.library_dirs, [os.path.join(sys.prefix, 'lib'), 
39                                   os.path.join(sys.prefix, 'local/lib')])
40     if sys.platform == "darwin":
41         update_list(cc.library_dirs, ["/sw/lib", "/opt/local/lib"])
42
43 if 'include_dirs' in os.environ:
44     update_dirs(cc.include_dirs, [path.strip() for path in os.environ.get('include_dirs').strip().split(":")])
45 else:
46     update_dirs(cc.include_dirs, [os.path.join(sys.prefix, 'include'), 
47                                   os.path.join(sys.prefix, 'include/freetype2'),
48                                   os.path.join(sys.prefix, 'include/fontconfig')])
49     if sys.platform == "darwin":
50         update_dirs(cc.include_dirs, ["/sw/include/freetype2", "/sw/lib/freetype2/include", "/sw/include", "/opt/local/include"])
51
52
53 class ConfigScript:
54     def __init__(self):
55         self.defines = []
56         self.includefiles = []
57         self.libraries = []
58
59     def unlink(self, filename):
60         try:
61             os.unlink(filename)
62         except OSError: 
63             pass
64
65     def test_code(self, head, body, stdh=1):
66         fi = open("setup_test.c", "wb")
67         if stdh:
68             fi.write("#include <stdlib.h>\n")
69             fi.write("#include <stdio.h>\n")
70             for i in self.includefiles:
71                 fi.write("#include <%s>\n" % i)
72         for d in self.defines:
73             fi.write("%s;\n" % d)
74         fi.write(head)
75         fi.write("\nint main()\n")
76         fi.write("{\n")
77         fi.write(body)
78         fi.write("\n}\n")
79         fi.close()
80         #fi = open("setup_test.c", "rb")
81         #print fi.read()
82         #fi.close()
83
84         quiet = 1
85         if quiet:
86             try:
87                 # redirect stderr
88                 sys.stderr.flush()
89                 err = open('/dev/null', 'a+', 0)
90                 olderr = open('/dev/null', 'a+', 0)
91                 os.dup2(2, olderr.fileno())
92                 os.dup2(err.fileno(), 2)
93             except:
94                 pass
95
96         error = 0
97         try:
98             cc.compile(["setup_test.c"], include_dirs=cc.include_dirs)
99         except CompileError:
100             error = 1
101
102         if quiet:
103             try:
104                 # unredirect stderr
105                 sys.stderr.flush()
106                 err = open('/dev/null', 'a+', 0)
107                 os.dup2(olderr.fileno(), 2)
108                 olderr.close()
109                 err.close()
110             except:
111                 pass
112
113         self.unlink("setup_test.o")
114         self.unlink("setup_test.obj")
115         self.unlink("setup_test.c")
116         if error:
117             return None
118         else:
119             return 1
120
121     def system_has_property(self,name):
122         if name.startswith("STD"):
123             return 1
124         elif name.startswith("INTERNAL"):
125             return 1
126         elif "POPPLER" in name:
127             return None
128         elif name.startswith("HAVE_") and name.endswith("_H"):
129             header = name[5:].lower()
130             c = header.rfind("_")
131             if c>=0:
132                 header = header[0:c]+"."+header[c+1]
133             header = header.replace("_","/")
134             ok = 0
135             for dir in cc.include_dirs:
136                 if os.path.isfile(os.path.join(dir,header)):
137                     ok = 1
138                     break
139             if ok and self.test_code("#include <"+header+">", ""):
140                 if header.startswith("sys"):
141                     self.includefiles += [header]
142                 return 1
143         elif name.startswith("HAVE_LIB") \
144           or name.startswith("HAVE_FONTCONFIG") \
145           or name.startswith("HAVE_FREETYPE"):
146             if name.startswith("HAVE_LIB"):
147                 libname = name[8:].lower()
148             else:
149                 libname = name[5:].lower()
150             if cc.find_library_file(cc.library_dirs, libname):
151                 update_list(self.libraries, [libname])
152                 return 1
153         elif name.startswith("HAVE_LAME"):
154             return None
155         elif name.startswith("O_BINARY"):
156             if sys.platform.startswith("win"):
157                 return None
158             else:
159                 return 0
160         elif name == "boolean":
161             if self.test_code("", "boolean b;"):
162                 return None
163             else:
164                 self.defines += ["typedef int boolean"]
165                 return "int"
166         elif name.startswith("SIZEOF_"):
167             t = name[7:].lower().replace("_", " ")
168             if t == "voidp":
169                 t = "void*"
170             for i in [1,2,4,8]:
171                 s = "static int test_array [%d+1-sizeof(%s)*2];\ntest_array [0] = 0;" % (i*2,t)
172                 if self.test_code("", s):
173                     return i
174             return None
175         elif name.startswith("USE_FREEETYPE"):
176             # TODO: run a test here?
177             return 1 
178         elif name.startswith("HAVE_"):
179             function = name[5:].lower()
180             params=""
181             if function=="bcopy":
182                 params = "0,0,0"
183             elif function=="bzero":
184                 params = "0,0"
185             return self.test_code("", "%s(%s);" % (function,params), stdh=0)
186         return None
187
188     def create_config(self):
189         print "Creating config.h..."
190
191         fi = open("config.h.in", "rb")
192         fo = open("config.h", "wb")
193         for line in fi.readlines():
194             if line.startswith("#undef "):
195                 line = line.strip()
196                 name = line[7:]
197                 if " " in name:
198                     name = name.split(" ")[0]
199                 value = self.system_has_property(name)
200                 if value is None:
201                     fo.write("// %s is not set\n" % (name))
202                 else:
203                     fo.write("#define %s %s\n" % (name, value))
204             else:
205                 fo.write(line)
206         fo.write("// python:lib "+(" ".join(self.libraries))+"\n")
207         fo.close()
208         fi.close()
209
210     def load(self):
211         if not os.path.isfile("config.h"):
212             return 0
213         fi = open("config.h", "rb")
214         for line in fi.readlines():
215             if line.startswith("// python: lib "):
216                 self.libraries = line[15:].split(" ")
217         fi.close()
218         return
219
220 config = ConfigScript()
221 # if either setup.py or config.h.in were modfied, rebuild config.h
222 if not config.load() or \
223    os.stat("setup.py")[stat.ST_MTIME] > os.stat("config.h")[stat.ST_MTIME] or \
224    os.stat("config.h.in")[stat.ST_MTIME] > os.stat("config.h")[stat.ST_MTIME]:
225     config.create_config()
226 #print dir(cc)
227 #sys.exit(0)
228
229 if "jpeg" not in config.libraries:
230     print "Error: Couldn't find jpeg library on your system"
231     sys.exit(1)
232
233 if "freetype" not in config.libraries:
234     print "Error: Couldn't find freetype library on your system"
235     sys.exit(1)
236
237 base_sources = [
238 "lib/q.c", "lib/utf8.c", "lib/png.c", "lib/jpeg.c", "lib/wav.c", "lib/mp3.c", "lib/os.c", "lib/bitio.c", "lib/log.c", "lib/mem.c",
239 ]
240 rfxswf_sources = [
241 "lib/modules/swfaction.c", "lib/modules/swfbits.c", "lib/modules/swfbutton.c",
242 "lib/modules/swfcgi.c", "lib/modules/swfdraw.c", "lib/modules/swfdump.c", "lib/modules/swffilter.c",
243 "lib/modules/swffont.c", "lib/modules/swfobject.c", "lib/modules/swfrender.c", "lib/modules/swfshape.c",
244 "lib/modules/swfsound.c", "lib/modules/swftext.c", "lib/modules/swftools.c",
245 "lib/rfxswf.c", "lib/drawer.c", "lib/MD5.c", "lib/h.263/dct.c", "lib/h.263/h263tables.c",
246 "lib/h.263/swfvideo.c", "lib/action/assembler.c", "lib/action/compile.c",
247 "lib/action/lex.swf4.c", "lib/action/lex.swf5.c", "lib/action/libming.c",
248 "lib/action/swf4compiler.tab.c", 
249 "lib/as3/abc.c", "lib/as3/code.c", "lib/as3/pool.c", "lib/as3/files.c", "lib/as3/opcodes.c", 
250 "lib/action/swf5compiler.tab.c", "lib/action/actioncompiler.c"
251 ]
252 libpdf_sources = [
253 "lib/pdf/GFXOutputDev.cc", "lib/pdf/InfoOutputDev.cc", "lib/pdf/BitmapOutputDev.cc",
254 "lib/pdf/FullBitmapOutputDev.cc", "lib/pdf/pdf.cc", "lib/pdf/fonts.c", "lib/pdf/xpdf/GHash.cc",
255 "lib/pdf/xpdf/GList.cc", "lib/pdf/xpdf/GString.cc", "lib/pdf/xpdf/gmem.cc", "lib/pdf/xpdf/gfile.cc",
256 "lib/pdf/xpdf/FoFiTrueType.cc", "lib/pdf/xpdf/FoFiType1.cc", "lib/pdf/xpdf/FoFiType1C.cc",
257 "lib/pdf/xpdf/FoFiBase.cc", "lib/pdf/xpdf/FoFiEncodings.cc", "lib/pdf/xpdf/OutputDev.cc", "lib/pdf/xpdf/PDFDoc.cc",
258 "lib/pdf/xpdf/Error.cc", "lib/pdf/xpdf/Stream.cc", "lib/pdf/xpdf/Object.cc", "lib/pdf/xpdf/Decrypt.cc",
259 "lib/pdf/xpdf/Array.cc", "lib/pdf/xpdf/XRef.cc", "lib/pdf/xpdf/Dict.cc", "lib/pdf/xpdf/Parser.cc",
260 "lib/pdf/xpdf/Lexer.cc", "lib/pdf/xpdf/Outline.cc", "lib/pdf/xpdf/PDFDocEncoding.cc", "lib/pdf/xpdf/Catalog.cc",
261 "lib/pdf/xpdf/Link.cc", "lib/pdf/xpdf/GlobalParams.cc", "lib/pdf/xpdf/JBIG2Stream.cc", "lib/pdf/xpdf/Page.cc",
262 "lib/pdf/xpdf/JPXStream.cc", "lib/pdf/xpdf/JArithmeticDecoder.cc", "lib/pdf/xpdf/Gfx.cc", "lib/pdf/xpdf/GfxFont.cc",
263 "lib/pdf/xpdf/CMap.cc", "lib/pdf/xpdf/CharCodeToUnicode.cc", "lib/pdf/xpdf/PSTokenizer.cc", "lib/pdf/xpdf/FontEncodingTables.cc",
264 "lib/pdf/xpdf/BuiltinFont.cc", "lib/pdf/xpdf/BuiltinFontTables.cc", "lib/pdf/xpdf/GfxState.cc", "lib/pdf/xpdf/Function.cc",
265 "lib/pdf/xpdf/Annot.cc", "lib/pdf/xpdf/NameToCharCode.cc", "lib/pdf/xpdf/UnicodeMap.cc", "lib/pdf/xpdf/SecurityHandler.cc",
266 "lib/pdf/xpdf/SplashOutputDev.cc", "lib/pdf/xpdf/SplashFont.cc", "lib/pdf/xpdf/SplashState.cc", "lib/pdf/xpdf/Splash.cc",
267 "lib/pdf/xpdf/SplashBitmap.cc", "lib/pdf/xpdf/SplashClip.cc", "lib/pdf/xpdf/SplashPattern.cc", "lib/pdf/xpdf/SplashFontEngine.cc",
268 "lib/pdf/xpdf/SplashFontFile.cc", "lib/pdf/xpdf/SplashFontFileID.cc", "lib/pdf/xpdf/SplashScreen.cc", "lib/pdf/xpdf/SplashPath.cc",
269 "lib/pdf/xpdf/SplashXPath.cc", "lib/pdf/xpdf/SplashXPathScanner.cc", "lib/pdf/xpdf/SplashFTFontEngine.cc",
270 "lib/pdf/xpdf/SplashFTFontFile.cc", "lib/pdf/xpdf/SplashFTFont.cc"]
271
272 libgfx_sources = [
273 "lib/gfxtools.c", "lib/gfxfont.c", "lib/gfxpoly.c",
274 "lib/devices/dummy.c", "lib/devices/file.c", "lib/devices/render.c", "lib/devices/text.c", "lib/devices/record.c",
275 "lib/devices/ops.c", "lib/devices/polyops.c", "lib/devices/bbox.c", "lib/devices/rescale.c",
276 "lib/art/art_affine.c", "lib/art/art_alphagamma.c", "lib/art/art_bpath.c", "lib/art/art_gray_svp.c",
277 "lib/art/art_misc.c", "lib/art/art_pixbuf.c", "lib/art/art_rect.c", "lib/art/art_rect_svp.c",
278 "lib/art/art_rect_uta.c", "lib/art/art_render.c", "lib/art/art_render_gradient.c", "lib/art/art_render_mask.c",
279 "lib/art/art_render_svp.c", "lib/art/art_rgb.c", "lib/art/art_rgb_a_affine.c", "lib/art/art_rgb_affine.c",
280 "lib/art/art_rgb_affine_private.c", "lib/art/art_rgb_bitmap_affine.c", "lib/art/art_rgb_pixbuf_affine.c",
281 "lib/art/art_rgb_rgba_affine.c", "lib/art/art_rgb_svp.c", "lib/art/art_rgba.c", "lib/art/art_svp.c",
282 "lib/art/art_svp_intersect.c", "lib/art/art_svp_ops.c", "lib/art/art_svp_point.c",
283 "lib/art/art_svp_render_aa.c", "lib/art/art_svp_vpath.c", "lib/art/art_svp_vpath_stroke.c",
284 "lib/art/art_svp_wind.c", "lib/art/art_uta.c", "lib/art/art_uta_ops.c", "lib/art/art_uta_rect.c",
285 "lib/art/art_uta_svp.c", "lib/art/art_uta_vpath.c", "lib/art/art_vpath.c", "lib/art/art_vpath_bpath.c",
286 "lib/art/art_vpath_dash.c", "lib/art/art_vpath_svp.c", "lib/gocr/box.c", 
287 "lib/gocr/database.c", "lib/gocr/detect.c", "lib/gocr/job.c", "lib/gocr/lines.c", "lib/gocr/list.c", 
288 "lib/gocr/ocr0.c", "lib/gocr/ocr0n.c", "lib/gocr/ocr1.c", "lib/gocr/otsu.c", "lib/gocr/output.c", 
289 "lib/gocr/pgm2asc.c", "lib/gocr/pixel.c", "lib/gocr/progress.c", "lib/gocr/remove.c", "lib/gocr/unicode.c",
290 "lib/devices/ocr.c",
291 ]
292 gfxswf_sources = ["lib/devices/swf.c", "lib/readers/swf.c", "lib/readers/image.c"]
293
294 swf_module = Extension(
295     name='SWF', 
296     include_dirs=cc.include_dirs+INCLUDE,
297     sources=['lib/python/SWF.c', 'lib/python/taglist.c', 'lib/python/tag.c', 'lib/python/image.c', 
298              'lib/python/tags.c', 'lib/python/tagmap.c', 'lib/python/action.c', 'lib/python/primitives.c', 
299              'lib/python/pyutils.c'] + base_sources + rfxswf_sources,
300     library_dirs=cc.library_dirs,
301     libraries=config.libraries,
302     extra_objects=['%s/lib/python%s/site-packages/PIL/_imaging.so' % (sys.prefix, sys.version[:3])],
303     extra_compile_args=COMPILER_OPTIONS,
304     )
305
306 gfx_module = Extension(
307     name='gfx',
308     sources=['lib/python/gfx.c'] + base_sources + libgfx_sources + rfxswf_sources + libpdf_sources + gfxswf_sources,
309     include_dirs=cc.include_dirs+INCLUDE,
310     library_dirs=cc.library_dirs,
311     libraries=config.libraries + ["stdc++"],
312     extra_objects=[],
313     extra_compile_args=COMPILER_OPTIONS,
314     )    
315
316 setup(name='SWFTools',
317       version='0.9dev',
318       description='Python wrapper for SWFTools',
319       author='Matthias Kramm',
320       author_email='kramm@quiss.org',
321       url='http://www.swftools.org/',
322       ext_modules=[swf_module, gfx_module],
323 )