Large nasty commit in the form of a 5000 line patch chock-full of completely
[ardour.git] / SConstruct
1 # -*- python -*-
2
3 import os
4 import sys
5 import re
6 import shutil
7 import glob
8 import errno
9 import time
10 import platform
11 import string
12 from sets import Set
13 import SCons.Node.FS
14
15 SConsignFile()
16 EnsureSConsVersion(0, 96)
17
18 version = '2.0beta2'
19
20 subst_dict = { }
21
22 #
23 # Command-line options
24 #
25
26 opts = Options('scache.conf')
27 opts.AddOptions(
28   ('ARCH', 'Set architecture-specific compilation flags by hand (all flags as 1 argument)',''),
29     BoolOption('COREAUDIO', 'Compile with Apple\'s CoreAudio library', 0),
30     BoolOption('DEBUG', 'Set to build with debugging information and no optimizations', 0),
31     PathOption('DESTDIR', 'Set the intermediate install "prefix"', '/'),
32     EnumOption('DIST_TARGET', 'Build target for cross compiling packagers', 'auto', allowed_values=('auto', 'i386', 'i686', 'x86_64', 'powerpc', 'tiger', 'panther', 'none' ), ignorecase=2),
33     BoolOption('DMALLOC', 'Compile and link using the dmalloc library', 0),
34     BoolOption('FFT_ANALYSIS', 'Include FFT analysis window', 0),
35     BoolOption('FPU_OPTIMIZATION', 'Build runtime checked assembler code', 1),
36     BoolOption('LIBLO', 'Compile with support for liblo library', 1),
37     BoolOption('NLS', 'Set to turn on i18n support', 1),
38     PathOption('PREFIX', 'Set the install "prefix"', '/usr/local'),
39     BoolOption('SURFACES', 'Build support for control surfaces', 0),
40     BoolOption('SYSLIBS', 'USE AT YOUR OWN RISK: CANCELS ALL SUPPORT FROM ARDOUR AUTHORS: Use existing system versions of various libraries instead of internal ones', 0),
41     BoolOption('VERSIONED', 'Add version information to ardour/gtk executable name inside the build directory', 0),
42     BoolOption('VST', 'Compile with support for VST', 0)
43 )
44
45 #----------------------------------------------------------------------
46 # a handy helper that provides a way to merge compile/link information
47 # from multiple different "environments"
48 #----------------------------------------------------------------------
49 #
50 class LibraryInfo(Environment):
51     def __init__(self,*args,**kw):
52         Environment.__init__ (self,*args,**kw)
53         
54     def Merge (self,others):
55         for other in others:
56             self.Append (LIBS = other.get ('LIBS',[]))
57             self.Append (LIBPATH = other.get ('LIBPATH', []))   
58             self.Append (CPPPATH = other.get('CPPPATH', []))
59             self.Append (LINKFLAGS = other.get('LINKFLAGS', []))
60         self.Replace(LIBPATH = list(Set(self.get('LIBPATH', []))))
61         self.Replace(CPPPATH = list(Set(self.get('CPPPATH',[]))))
62         #doing LINKFLAGS breaks -framework
63         #doing LIBS break link order dependency
64
65
66 env = LibraryInfo (options = opts,
67                    CPPPATH = [ '.' ],
68                    VERSION = version,
69                    TARBALL='ardour-' + version + '.tar.bz2',
70                    DISTFILES = [ ],
71                    DISTTREE  = '#ardour-' + version,
72                    DISTCHECKDIR = '#ardour-' + version + '/check'
73                    )
74
75
76 #----------------------------------------------------------------------
77 # Builders
78 #----------------------------------------------------------------------
79
80 # Handy subst-in-file builder
81
82
83 def do_subst_in_file(targetfile, sourcefile, dict):
84         """Replace all instances of the keys of dict with their values.
85         For example, if dict is {'%VERSION%': '1.2345', '%BASE%': 'MyProg'},
86         then all instances of %VERSION% in the file will be replaced with 1.2345 etc.
87         """
88         try:
89             f = open(sourcefile, 'rb')
90             contents = f.read()
91             f.close()
92         except:
93             raise SCons.Errors.UserError, "Can't read source file %s"%sourcefile
94         for (k,v) in dict.items():
95             contents = re.sub(k, v, contents)
96         try:
97             f = open(targetfile, 'wb')
98             f.write(contents)
99             f.close()
100         except:
101             raise SCons.Errors.UserError, "Can't write target file %s"%targetfile
102         return 0 # success
103  
104 def subst_in_file(target, source, env):
105         if not env.has_key('SUBST_DICT'):
106             raise SCons.Errors.UserError, "SubstInFile requires SUBST_DICT to be set."
107         d = dict(env['SUBST_DICT']) # copy it
108         for (k,v) in d.items():
109             if callable(v):
110                 d[k] = env.subst(v())
111             elif SCons.Util.is_String(v):
112                 d[k]=env.subst(v)
113             else:
114                 raise SCons.Errors.UserError, "SubstInFile: key %s: %s must be a string or callable"%(k, repr(v))
115         for (t,s) in zip(target, source):
116             return do_subst_in_file(str(t), str(s), d)
117  
118 def subst_in_file_string(target, source, env):
119         """This is what gets printed on the console."""
120         return '\n'.join(['Substituting vars from %s into %s'%(str(s), str(t))
121                           for (t,s) in zip(target, source)])
122  
123 def subst_emitter(target, source, env):
124         """Add dependency from substituted SUBST_DICT to target.
125         Returns original target, source tuple unchanged.
126         """
127         d = env['SUBST_DICT'].copy() # copy it
128         for (k,v) in d.items():
129             if callable(v):
130                 d[k] = env.subst(v())
131             elif SCons.Util.is_String(v):
132                 d[k]=env.subst(v)
133         Depends(target, SCons.Node.Python.Value(d))
134         # Depends(target, source) # this doesn't help the install-sapphire-linux.sh problem
135         return target, source
136  
137 subst_action = Action (subst_in_file, subst_in_file_string)
138 env['BUILDERS']['SubstInFile'] = Builder(action=subst_action, emitter=subst_emitter)
139
140 #
141 # internationalization
142 #
143
144 # po_helper
145 #
146 # this is not a builder. we can't list the .po files as a target,
147 # because then scons -c will remove them (even Precious doesn't alter
148 # this). this function is called whenever a .mo file is being
149 # built, and will conditionally update the .po file if necessary.
150 #
151
152 def po_helper(po,pot):
153     args = [ 'msgmerge',
154              '--update',
155              po,
156              pot,
157              ]
158     print 'Updating ' + po
159     return os.spawnvp (os.P_WAIT, 'msgmerge', args)
160
161 # mo_builder: builder function for (binary) message catalogs (.mo)
162 #
163 # first source:  .po file
164 # second source: .pot file
165 #
166
167 def mo_builder(target,source,env):
168     po_helper (source[0].get_path(), source[1].get_path())
169     args = [ 'msgfmt',
170              '-c',
171              '-o',
172              target[0].get_path(),
173              source[0].get_path()
174              ]
175     return os.spawnvp (os.P_WAIT, 'msgfmt', args)
176
177 mo_bld = Builder (action = mo_builder)
178 env.Append(BUILDERS = {'MoBuild' : mo_bld})
179
180 # pot_builder: builder function for message templates (.pot)
181 #
182 # source: list of C/C++ etc. files to extract messages from
183 #
184
185 def pot_builder(target,source,env):
186     args = [ 'xgettext', 
187              '--keyword=_',
188              '--keyword=N_',
189              '--from-code=UTF-8',
190              '-o', target[0].get_path(), 
191              "--default-domain=" + env['PACKAGE'],
192              '--copyright-holder="Paul Davis"' ]
193     args += [ src.get_path() for src in source ]
194
195     return os.spawnvp (os.P_WAIT, 'xgettext', args)
196
197 pot_bld = Builder (action = pot_builder)
198 env.Append(BUILDERS = {'PotBuild' : pot_bld})
199
200 #
201 # utility function, not a builder
202 #
203
204 def i18n (buildenv, sources, installenv):
205     domain = buildenv['PACKAGE']
206     potfile = buildenv['POTFILE']
207
208     installenv.Alias ('potupdate', buildenv.PotBuild (potfile, sources))
209
210     p_oze = [ os.path.basename (po) for po in glob.glob ('po/*.po') ]
211     languages = [ po.replace ('.po', '') for po in p_oze ]
212     m_oze = [ po.replace (".po", ".mo") for po in p_oze ]
213     
214     for mo in m_oze[:]:
215         po = 'po/' + mo.replace (".mo", ".po")
216         installenv.Alias ('install', buildenv.MoBuild (mo, [ po, potfile ]))
217         
218     for lang in languages[:]:
219         modir = (os.path.join (install_prefix, 'share/locale/' + lang + '/LC_MESSAGES/'))
220         moname = domain + '.mo'
221         installenv.Alias('install', installenv.InstallAs (os.path.join (modir, moname), lang + '.mo'))
222
223 #
224 # A generic builder for version.cc files
225
226 # note: requires that DOMAIN, MAJOR, MINOR, MICRO are set in the construction environment
227 # note: assumes one source files, the header that declares the version variables
228
229 def version_builder (target, source, env):
230    text  = "int " + env['DOMAIN'] + "_major_version = " + str (env['MAJOR']) + ";\n"
231    text += "int " + env['DOMAIN'] + "_minor_version = " + str (env['MINOR']) + ";\n"
232    text += "int " + env['DOMAIN'] + "_micro_version = " + str (env['MICRO']) + ";\n"
233
234    try:
235       o = file (target[0].get_path(), 'w')
236       o.write (text)
237       o.close ()
238    except IOError:
239       print "Could not open", target[0].get_path(), " for writing\n"
240       sys.exit (-1)
241
242    text  = "#ifndef __" + env['DOMAIN'] + "_version_h__\n"
243    text += "#define __" + env['DOMAIN'] + "_version_h__\n"
244    text += "extern int " + env['DOMAIN'] + "_major_version;\n"
245    text += "extern int " + env['DOMAIN'] + "_minor_version;\n"
246    text += "extern int " + env['DOMAIN'] + "_micro_version;\n"
247    text += "#endif /* __" + env['DOMAIN'] + "_version_h__ */\n"
248
249    try:
250       o = file (target[1].get_path(), 'w')
251       o.write (text)
252       o.close ();
253    except IOError:
254       print "Could not open", target[1].get_path(), " for writing\n"
255       sys.exit (-1)
256   
257    return None
258
259 version_bld = Builder (action = version_builder)
260 env.Append (BUILDERS = {'VersionBuild' : version_bld})
261
262 #
263 # a builder that makes a hard link from the 'source' executable to a name with
264 # a "build ID" based on the most recent CVS activity that might be reasonably
265 # related to version activity. this relies on the idea that the SConscript
266 # file that builds the executable is updated with new version info and committed
267 # to the source code repository whenever things change.
268 #
269
270 def versioned_builder(target,source,env):
271     # build ID is composed of a representation of the date of the last CVS transaction
272     # for this (SConscript) file
273     
274     try:
275         o = file (source[0].get_dir().get_path() +  '/CVS/Entries', "r")
276     except IOError:
277         print "Could not CVS/Entries for reading"
278         return -1
279
280     last_date = ""        
281     lines = o.readlines()
282     for line in lines:
283         if line[0:12] == '/SConscript/':
284             parts = line.split ("/")
285             last_date = parts[3]
286             break
287     o.close ()
288
289     if last_date == "":
290         print "No SConscript CVS update info found - versioned executable cannot be built"
291         return -1
292
293     tag = time.strftime ('%Y%M%d%H%m', time.strptime (last_date))
294     print "The current build ID is " + tag
295
296     tagged_executable = source[0].get_path() + '-' + tag
297
298     if os.path.exists (tagged_executable):
299         print "Replacing existing executable with the same build tag."
300         os.unlink (tagged_executable)
301
302     return os.link (source[0].get_path(), tagged_executable)
303
304 verbuild = Builder (action = versioned_builder)
305 env.Append (BUILDERS = {'VersionedExecutable' : verbuild})
306
307 #
308 # source tar file builder
309 #
310
311 def distcopy (target, source, env):
312     treedir = str (target[0])
313
314     try:
315         os.mkdir (treedir)
316     except OSError, (errnum, strerror):
317         if errnum != errno.EEXIST:
318             print 'mkdir ', treedir, ':', strerror
319
320     cmd = 'tar cf - '
321     #
322     # we don't know what characters might be in the file names
323     # so quote them all before passing them to the shell
324     #
325     all_files = ([ str(s) for s in source ])
326     cmd += " ".join ([ "'%s'" % quoted for quoted in all_files])
327     cmd += ' | (cd ' + treedir + ' && tar xf -)'
328     p = os.popen (cmd)
329     return p.close ()
330
331 def tarballer (target, source, env):            
332     cmd = 'tar -jcf ' + str (target[0]) +  ' ' + str(source[0]) + "  --exclude '*~'"
333     print 'running ', cmd, ' ... '
334     p = os.popen (cmd)
335     return p.close ()
336
337 dist_bld = Builder (action = distcopy,
338                     target_factory = SCons.Node.FS.default_fs.Entry,
339                     source_factory = SCons.Node.FS.default_fs.Entry,
340                     multi = 1)
341
342 tarball_bld = Builder (action = tarballer,
343                        target_factory = SCons.Node.FS.default_fs.Entry,
344                        source_factory = SCons.Node.FS.default_fs.Entry)
345
346 env.Append (BUILDERS = {'Distribute' : dist_bld})
347 env.Append (BUILDERS = {'Tarball' : tarball_bld})
348
349 #
350 # Make sure they know what they are doing
351 #
352
353 if env['VST']:
354     sys.stdout.write ("Are you building Ardour for personal use (rather than distributiont to others)? [no]: ")
355     answer = sys.stdin.readline ()
356     answer = answer.rstrip().strip()
357     if answer != "yes" and answer != "y":
358         print 'You cannot build Ardour with VST support for distribution to others.\nIt is a violation of several different licenses. VST support disabled.'
359         env['VST'] = 0;
360     else:
361         print "OK, VST support will be enabled"
362         
363
364 # ----------------------------------------------------------------------
365 # Construction environment setup
366 # ----------------------------------------------------------------------
367
368 libraries = { }
369
370 libraries['core'] = LibraryInfo (CCFLAGS = '-Ilibs')
371
372 #libraries['sndfile'] = LibraryInfo()
373 #libraries['sndfile'].ParseConfig('pkg-config --cflags --libs sndfile')
374
375 libraries['lrdf'] = LibraryInfo()
376 libraries['lrdf'].ParseConfig('pkg-config --cflags --libs lrdf')
377
378 libraries['raptor'] = LibraryInfo()
379 libraries['raptor'].ParseConfig('pkg-config --cflags --libs raptor')
380
381 libraries['samplerate'] = LibraryInfo()
382 libraries['samplerate'].ParseConfig('pkg-config --cflags --libs samplerate')
383
384 if env['FFT_ANALYSIS']: 
385         libraries['fftw3f'] = LibraryInfo()
386         libraries['fftw3f'].ParseConfig('pkg-config --cflags --libs fftw3f')
387
388 libraries['jack'] = LibraryInfo()
389 libraries['jack'].ParseConfig('pkg-config --cflags --libs jack')
390
391 libraries['xml'] = LibraryInfo()
392 libraries['xml'].ParseConfig('pkg-config --cflags --libs libxml-2.0')
393
394 libraries['xslt'] = LibraryInfo()
395 libraries['xslt'].ParseConfig('pkg-config --cflags --libs libxslt')
396
397 libraries['glib2'] = LibraryInfo()
398 libraries['glib2'].ParseConfig ('pkg-config --cflags --libs glib-2.0')
399 libraries['glib2'].ParseConfig ('pkg-config --cflags --libs gobject-2.0')
400 libraries['glib2'].ParseConfig ('pkg-config --cflags --libs gmodule-2.0')
401 libraries['glib2'].ParseConfig ('pkg-config --cflags --libs gthread-2.0')
402
403 libraries['gtk2'] = LibraryInfo()
404 libraries['gtk2'].ParseConfig ('pkg-config --cflags --libs gtk+-2.0')
405
406 libraries['pango'] = LibraryInfo()
407 libraries['pango'].ParseConfig ('pkg-config --cflags --libs pango')
408
409 libraries['libgnomecanvas2'] = LibraryInfo()
410 libraries['libgnomecanvas2'].ParseConfig ('pkg-config --cflags --libs libgnomecanvas-2.0')
411
412 #libraries['flowcanvas'] = LibraryInfo(LIBS='flowcanvas', LIBPATH='#/libs/flowcanvas', CPPPATH='#libs/flowcanvas')
413
414 # The Ardour Control Protocol Library
415
416 libraries['ardour_cp'] = LibraryInfo (LIBS='ardour_cp', LIBPATH='#libs/surfaces/control_protocol',
417                                       CPPPATH='#libs/surfaces/control_protocol')
418
419 # The Ardour backend/engine
420
421 libraries['ardour'] = LibraryInfo (LIBS='ardour', LIBPATH='#libs/ardour', CPPPATH='#libs/ardour')
422 libraries['midi++2'] = LibraryInfo (LIBS='midi++', LIBPATH='#libs/midi++2', CPPPATH='#libs/midi++2')
423 libraries['pbd3']    = LibraryInfo (LIBS='pbd', LIBPATH='#libs/pbd3', CPPPATH='#libs/pbd3')
424 libraries['gtkmm2ext'] = LibraryInfo (LIBS='gtkmm2ext', LIBPATH='#libs/gtkmm2ext', CPPPATH='#libs/gtkmm2ext')
425 #libraries['cassowary'] = LibraryInfo(LIBS='cassowary', LIBPATH='#libs/cassowary', CPPPATH='#libs/cassowary')
426
427 #
428 # Check for libusb
429
430 libraries['usb'] = LibraryInfo ()
431
432 conf = Configure (libraries['usb'])
433 if conf.CheckLib ('usb', 'usb_interrupt_write'):
434     have_libusb = True
435 else:
436     have_libusb = False
437     
438 libraries['usb'] = conf.Finish ()
439
440 #
441 # Check for FLAC
442
443 libraries['flac'] = LibraryInfo ()
444
445 conf = Configure (libraries['flac'])
446 conf.CheckLib ('FLAC', 'FLAC__stream_decoder_new')
447 libraries['flac'] = conf.Finish ()
448
449 #
450 # Check for liblo
451
452 if env['LIBLO']:
453     libraries['lo'] = LibraryInfo ()
454
455     conf = Configure (libraries['lo'])
456     if conf.CheckLib ('lo', 'lo_server_new') == False:
457         print "liblo does not appear to be installed."
458         sys.exit (1)
459     
460     libraries['lo'] = conf.Finish ()
461
462 #
463 # Check for dmalloc
464
465 libraries['dmalloc'] = LibraryInfo ()
466
467 #
468 # look for the threaded version
469 #
470
471 conf = Configure (libraries['dmalloc'])
472 if conf.CheckLib ('dmallocth', 'dmalloc_shutdown'):
473     have_libdmalloc = True
474 else:
475     have_libdmalloc = False
476     
477 libraries['dmalloc'] = conf.Finish ()
478
479 #
480
481 #
482 # Audio/MIDI library (needed for MIDI, since audio is all handled via JACK)
483
484
485 conf = Configure(env)
486 if conf.CheckCHeader('jack/midiport.h'):
487     libraries['sysmidi'] = LibraryInfo (LIBS='jack')
488     env['SYSMIDI'] = 'JACK MIDI'
489     subst_dict['%MIDITAG%'] = "control"
490     subst_dict['%MIDITYPE%'] = "jack"
491     print "Using JACK MIDI"
492 elif conf.CheckCHeader('alsa/asoundlib.h'):
493     libraries['sysmidi'] = LibraryInfo (LIBS='asound')
494     env['SYSMIDI'] = 'ALSA Sequencer'
495     subst_dict['%MIDITAG%'] = "seq"
496     subst_dict['%MIDITYPE%'] = "alsa/sequencer"
497     print "Using ALSA MIDI"
498 elif conf.CheckCHeader('/System/Library/Frameworks/CoreMIDI.framework/Headers/CoreMIDI.h'):
499     # this line is needed because scons can't handle -framework in ParseConfig() yet.
500     libraries['sysmidi'] = LibraryInfo (LINKFLAGS= '-framework CoreMIDI -framework CoreFoundation -framework CoreAudio -framework CoreServices -framework AudioUnit -framework AudioToolbox -bind_at_load')
501     env['SYSMIDI'] = 'CoreMIDI'
502     subst_dict['%MIDITAG%'] = "ardour"
503     subst_dict['%MIDITYPE%'] = "coremidi"
504     print "Using CoreMIDI"
505 else:
506     print "It appears you don't have the required MIDI libraries installed."
507     sys.exit (1)
508         
509 env = conf.Finish()
510
511 if env['SYSLIBS']:
512
513     libraries['sigc2'] = LibraryInfo()
514     libraries['sigc2'].ParseConfig('pkg-config --cflags --libs sigc++-2.0')
515     libraries['glibmm2'] = LibraryInfo()
516     libraries['glibmm2'].ParseConfig('pkg-config --cflags --libs glibmm-2.4')
517     libraries['gdkmm2'] = LibraryInfo()
518     libraries['gdkmm2'].ParseConfig ('pkg-config --cflags --libs gdkmm-2.4')
519     libraries['gtkmm2'] = LibraryInfo()
520     libraries['gtkmm2'].ParseConfig ('pkg-config --cflags --libs gtkmm-2.4')
521     libraries['atkmm'] = LibraryInfo()
522     libraries['atkmm'].ParseConfig ('pkg-config --cflags --libs atkmm-1.6')
523     libraries['pangomm'] = LibraryInfo()
524     libraries['pangomm'].ParseConfig ('pkg-config --cflags --libs pangomm-1.4')
525     libraries['libgnomecanvasmm'] = LibraryInfo()
526     libraries['libgnomecanvasmm'].ParseConfig ('pkg-config --cflags --libs libgnomecanvasmm-2.6')
527
528 #
529 # cannot use system one for the time being
530 #
531
532     libraries['sndfile'] = LibraryInfo(LIBS='libsndfile',
533                                     LIBPATH='#libs/libsndfile',
534                                     CPPPATH=['#libs/libsndfile', '#libs/libsndfile/src'])
535
536 #    libraries['libglademm'] = LibraryInfo()
537 #    libraries['libglademm'].ParseConfig ('pkg-config --cflags --libs libglademm-2.4')
538
539 #    libraries['flowcanvas'] = LibraryInfo(LIBS='flowcanvas', LIBPATH='#/libs/flowcanvas', CPPPATH='#libs/flowcanvas')
540     libraries['soundtouch'] = LibraryInfo()
541     libraries['soundtouch'].ParseConfig ('pkg-config --cflags --libs libSoundTouch')
542
543     coredirs = [
544         'templates'
545     ]
546
547     subdirs = [
548         'libs/libsndfile',
549         'libs/pbd3',
550         'libs/midi++2',
551         'libs/ardour'
552         ]
553
554     if env['VST']:
555         subdirs = ['libs/fst'] + subdirs + ['vst']
556
557     gtk_subdirs = [
558 #        'libs/flowcanvas',
559         'libs/gtkmm2ext',
560         'gtk2_ardour'
561         ]
562
563 else:
564     libraries['sigc2'] = LibraryInfo(LIBS='sigc++2',
565                                     LIBPATH='#libs/sigc++2',
566                                     CPPPATH='#libs/sigc++2')
567     libraries['glibmm2'] = LibraryInfo(LIBS='glibmm2',
568                                     LIBPATH='#libs/glibmm2',
569                                     CPPPATH='#libs/glibmm2')
570     libraries['pangomm'] = LibraryInfo(LIBS='pangomm',
571                                     LIBPATH='#libs/gtkmm2/pango',
572                                     CPPPATH='#libs/gtkmm2/pango')
573     libraries['atkmm'] = LibraryInfo(LIBS='atkmm',
574                                      LIBPATH='#libs/gtkmm2/atk',
575                                      CPPPATH='#libs/gtkmm2/atk')
576     libraries['gdkmm2'] = LibraryInfo(LIBS='gdkmm2',
577                                       LIBPATH='#libs/gtkmm2/gdk',
578                                       CPPPATH='#libs/gtkmm2/gdk')
579     libraries['gtkmm2'] = LibraryInfo(LIBS='gtkmm2',
580                                      LIBPATH="#libs/gtkmm2/gtk",
581                                      CPPPATH='#libs/gtkmm2/gtk/')
582     libraries['libgnomecanvasmm'] = LibraryInfo(LIBS='libgnomecanvasmm',
583                                                 LIBPATH='#libs/libgnomecanvasmm',
584                                                 CPPPATH='#libs/libgnomecanvasmm')
585
586     libraries['soundtouch'] = LibraryInfo(LIBS='soundtouch',
587                                           LIBPATH='#libs/soundtouch',
588                                           CPPPATH=['#libs', '#libs/soundtouch'])
589     libraries['sndfile'] = LibraryInfo(LIBS='libsndfile',
590                                     LIBPATH='#libs/libsndfile',
591                                     CPPPATH=['#libs/libsndfile', '#libs/libsndfile/src'])
592 #    libraries['libglademm'] = LibraryInfo(LIBS='libglademm',
593 #                                          LIBPATH='#libs/libglademm',
594 #                                          CPPPATH='#libs/libglademm')
595
596     coredirs = [
597         'libs/soundtouch',
598         'templates'
599     ]
600
601     subdirs = [
602 #           'libs/cassowary',
603         'libs/sigc++2',
604         'libs/libsndfile',
605         'libs/pbd3',
606         'libs/midi++2',
607         'libs/ardour'
608         ]
609
610     if env['VST']:
611         subdirs = ['libs/fst'] + subdirs + ['vst']
612
613     gtk_subdirs = [
614         'libs/glibmm2',
615         'libs/gtkmm2/pango',
616         'libs/gtkmm2/atk',
617         'libs/gtkmm2/gdk',
618         'libs/gtkmm2/gtk',
619         'libs/libgnomecanvasmm',
620 #       'libs/flowcanvas',
621     'libs/gtkmm2ext',
622     'gtk2_ardour'
623         ]
624
625 #
626 # always build the LGPL control protocol lib, since we link against it ourselves
627 # ditto for generic MIDI
628 #
629
630 surface_subdirs = [ 'libs/surfaces/control_protocol', 'libs/surfaces/generic_midi' ]
631
632 if env['SURFACES']:
633     if have_libusb:
634         surface_subdirs += [ 'libs/surfaces/tranzport' ]
635     if os.access ('libs/surfaces/sony9pin', os.F_OK):
636         surface_subdirs += [ 'libs/surfaces/sony9pin' ]
637     
638 opts.Save('scache.conf', env)
639 Help(opts.GenerateHelpText(env))
640
641 if os.environ.has_key('PATH'):
642     env.Append(PATH = os.environ['PATH'])
643
644 if os.environ.has_key('PKG_CONFIG_PATH'):
645     env.Append(PKG_CONFIG_PATH = os.environ['PKG_CONFIG_PATH'])
646
647 if os.environ.has_key('CC'):
648     env['CC'] = os.environ['CC']
649
650 if os.environ.has_key('CXX'):
651     env['CXX'] = os.environ['CXX']
652
653 if os.environ.has_key('DISTCC_HOSTS'):
654     env['ENV']['DISTCC_HOSTS'] = os.environ['DISTCC_HOSTS']
655     env['ENV']['HOME'] = os.environ['HOME']
656     
657 final_prefix = '$PREFIX'
658 install_prefix = '$DESTDIR/$PREFIX'
659
660 subst_dict['INSTALL_PREFIX'] = install_prefix;
661
662 if env['PREFIX'] == '/usr':
663     final_config_prefix = '/etc'
664 else:
665     final_config_prefix = env['PREFIX'] + '/etc'
666
667 config_prefix = '$DESTDIR' + final_config_prefix
668
669 # For colorgcc ( so says the wiki, but it's still not working :/  anyone? )
670 if os.environ.has_key('PATH'):
671         env['PATH'] = os.environ['PATH']
672 if os.environ.has_key('TERM'):
673         env['TERM'] = os.environ['TERM']
674 if os.environ.has_key('HOME'):
675         env['HOME'] = os.environ['HOME']
676
677
678 # SCons should really do this for us
679
680 conf = Configure (env)
681
682 have_cxx = conf.TryAction (Action (env['CXX'] + ' --version'))
683 if have_cxx[0] != 1:
684     print "This system has no functional C++ compiler. You cannot build Ardour from source without one."
685     exit (1)
686 else:
687     print "Congratulations, you have a functioning C++ compiler."
688     
689 env = conf.Finish()
690
691 #
692 # Compiler flags and other system-dependent stuff
693 #
694
695 opt_flags = []
696 debug_flags = [ '-g' ]
697
698 # guess at the platform, used to define compiler flags
699
700 config_guess = os.popen("tools/config.guess").read()[:-1]
701
702 config_cpu = 0
703 config_arch = 1
704 config_kernel = 2
705 config_os = 3
706 config = config_guess.split ("-")
707
708 print "system triple: " + config_guess
709
710 # Autodetect
711 if env['DIST_TARGET'] == 'auto':
712     if config[config_arch] == 'apple':
713         # The [.] matches to the dot after the major version, "." would match any character
714         if re.search ("darwin[0-7][.]", config[config_kernel]) != None:
715             env['DIST_TARGET'] = 'panther'
716         else:
717             env['DIST_TARGET'] = 'tiger'
718     else:
719         if re.search ("x86_64", config[config_cpu]) != None:
720             env['DIST_TARGET'] = 'x86_64'
721         elif re.search("i[0-5]86", config[config_cpu]) != None:
722             env['DIST_TARGET'] = 'i386'
723         elif re.search("powerpc", config[config_cpu]) != None:
724             env['DIST_TARGET'] = 'powerpc'
725         else:
726             env['DIST_TARGET'] = 'i686'
727     print "\n*******************************"
728     print "detected DIST_TARGET = " + env['DIST_TARGET']
729     print "*******************************\n"
730
731
732 if config[config_cpu] == 'powerpc' and env['DIST_TARGET'] != 'none':
733     #
734     # Apple/PowerPC optimization options
735     #
736     # -mcpu=7450 does not reliably work with gcc 3.*
737     #
738     if env['DIST_TARGET'] == 'panther' or env['DIST_TARGET'] == 'tiger':
739         if config[config_arch] == 'apple':
740             opt_flags.extend ([ "-mcpu=7450", "-faltivec"])
741         else:
742             opt_flags.extend ([ "-mcpu=7400", "-maltivec", "-mabi=altivec"]) 
743     else:
744         opt_flags.extend([ "-mcpu=750", "-mmultiple" ])
745     opt_flags.extend (["-mhard-float", "-mpowerpc-gfxopt"])
746
747 elif ((re.search ("i[0-9]86", config[config_cpu]) != None) or (re.search ("x86_64", config[config_cpu]) != None)) and env['DIST_TARGET'] != 'none':
748
749     build_host_supports_sse = 0
750     
751     debug_flags.append ("-DARCH_X86")
752     opt_flags.append ("-DARCH_X86")
753
754     if config[config_kernel] == 'linux' :
755
756         if env['DIST_TARGET'] != 'i386': 
757
758             flag_line = os.popen ("cat /proc/cpuinfo | grep '^flags'").read()[:-1]
759             x86_flags = flag_line.split (": ")[1:][0].split (' ')
760
761             if "mmx" in x86_flags:
762                 opt_flags.append ("-mmmx")
763             if "sse" in x86_flags:
764                 build_host_supports_sse = 1
765             if "3dnow" in x86_flags:
766                 opt_flags.append ("-m3dnow")
767
768             if config[config_cpu] == "i586":
769                 opt_flags.append ("-march=i586")
770             elif config[config_cpu] == "i686":
771                 opt_flags.append ("-march=i686")
772
773     if ((env['DIST_TARGET'] == 'i686') or (env['DIST_TARGET'] == 'x86_64')) and build_host_supports_sse:
774         opt_flags.extend (["-msse", "-mfpmath=sse"])
775         debug_flags.extend (["-msse", "-mfpmath=sse"])
776 # end of processor-specific section
777
778 # optimization section
779 if env['FPU_OPTIMIZATION']:
780     if env['DIST_TARGET'] == 'tiger':
781         opt_flags.append ("-DBUILD_VECLIB_OPTIMIZATIONS")
782         debug_flags.append ("-DBUILD_VECLIB_OPTIMIZATIONS")
783         libraries['core'].Append(LINKFLAGS= '-framework Accelerate')
784     elif env['DIST_TARGET'] == 'i686' or env['DIST_TARGET'] == 'x86_64':
785         opt_flags.append ("-DBUILD_SSE_OPTIMIZATIONS")
786         debug_flags.append ("-DBUILD_SSE_OPTIMIZATIONS")
787         if env['DIST_TARGET'] == 'x86_64':
788             opt_flags.append ("-DUSE_X86_64_ASM")
789             debug_flags.append ("-DUSE_X86_64_ASM")
790         if build_host_supports_sse != 1:
791             print "\nWarning: you are building Ardour with SSE support even though your system does not support these instructions. (This may not be an error, especially if you are a package maintainer)"
792 # end optimization section
793
794 #
795 # save off guessed arch element in an env
796 #
797 env.Append(CONFIG_ARCH=config[config_arch])
798
799
800 #
801 # ARCH="..." overrides all 
802 #
803
804 if env['ARCH'] != '':
805     opt_flags = env['ARCH'].split()
806
807 #
808 # prepend boiler plate optimization flags
809 #
810
811 opt_flags[:0] = [
812     "-O3",
813     "-fomit-frame-pointer",
814     "-ffast-math",
815     "-fstrength-reduce"
816     ]
817
818 if env['DEBUG'] == 1:
819     env.Append(CCFLAGS=" ".join (debug_flags))
820 else:
821     env.Append(CCFLAGS=" ".join (opt_flags))
822
823 #
824 # warnings flags
825 #
826
827 env.Append(CCFLAGS="-Wall")
828 env.Append(CXXFLAGS="-Woverloaded-virtual")
829
830 if env['LIBLO']:
831     env.Append(CCFLAGS="-DHAVE_LIBLO")
832
833 #
834 # everybody needs this
835 #
836
837 env.Merge ([ libraries['core'] ])
838
839 #
840 # i18n support 
841 #
842
843 conf = Configure (env)
844
845 if env['NLS']:
846     print 'Checking for internationalization support ...'
847     have_gettext = conf.TryAction(Action('xgettext --version'))
848     if have_gettext[0] != 1:
849         print 'This system is not configured for internationalized applications (no xgettext command). An english-only version will be built\n'
850         env['NLS'] = 0
851         
852     if conf.CheckCHeader('libintl.h') == None:
853         print 'This system is not configured for internationalized applications (no libintl.h). An english-only version will be built\n'
854         env['NLS'] = 0
855
856
857 env = conf.Finish()
858
859 if env['NLS'] == 1:
860     env.Append(CCFLAGS="-DENABLE_NLS")
861
862
863 Export('env install_prefix final_prefix config_prefix final_config_prefix libraries i18n version subst_dict')
864
865 #
866 # the configuration file may be system dependent
867 #
868
869 conf = env.Configure ()
870
871 if conf.CheckCHeader('/System/Library/Frameworks/CoreAudio.framework/Versions/A/Headers/CoreAudio.h'):
872     subst_dict['%JACK_INPUT%'] = "coreaudio:Built-in Audio:in"
873     subst_dict['%JACK_OUTPUT%'] = "coreaudio:Built-in Audio:out"
874 else:
875     subst_dict['%JACK_INPUT%'] = "alsa_pcm:playback_"
876     subst_dict['%JACK_OUTPUT%'] = "alsa_pcm:capture_"
877
878 # posix_memalign available
879 if not conf.CheckFunc('posix_memalign'):
880     print 'Did not find posix_memalign(), using malloc'
881     env.Append(CCFLAGS='-DNO_POSIX_MEMALIGN')
882
883
884 env = conf.Finish()
885
886 rcbuild = env.SubstInFile ('ardour.rc','ardour.rc.in', SUBST_DICT = subst_dict)
887
888 env.Alias('install', env.Install(os.path.join(config_prefix, 'ardour2'), 'ardour_system.rc'))
889 env.Alias('install', env.Install(os.path.join(config_prefix, 'ardour2'), 'ardour.rc'))
890
891 Default (rcbuild)
892
893 # source tarball
894
895 Precious (env['DISTTREE'])
896
897 #
898 # note the special "cleanfirst" source name. this triggers removal
899 # of the existing disttree
900 #
901
902 env.Distribute (env['DISTTREE'],
903                 [ 'SConstruct',
904                   'COPYING', 'PACKAGER_README', 'README',
905                   'ardour.rc.in',
906                   'ardour_system.rc',
907                   'tools/config.guess'
908                   ] +
909                 glob.glob ('DOCUMENTATION/AUTHORS*') +
910                 glob.glob ('DOCUMENTATION/CONTRIBUTORS*') +
911                 glob.glob ('DOCUMENTATION/TRANSLATORS*') +
912                 glob.glob ('DOCUMENTATION/BUILD*') +
913                 glob.glob ('DOCUMENTATION/FAQ*') +
914                 glob.glob ('DOCUMENTATION/README*')
915                 )
916                 
917 srcdist = env.Tarball(env['TARBALL'], env['DISTTREE'])
918 env.Alias ('srctar', srcdist)
919 #
920 # don't leave the distree around 
921 #
922 env.AddPreAction (env['DISTTREE'], Action ('rm -rf ' + str (File (env['DISTTREE']))))
923 env.AddPostAction (srcdist, Action ('rm -rf ' + str (File (env['DISTTREE']))))
924
925 #
926 # the subdirs
927
928
929 for subdir in coredirs:
930     SConscript (subdir + '/SConscript')
931
932 for sublistdir in [ subdirs, gtk_subdirs, surface_subdirs ]:
933     for subdir in sublistdir:
934         SConscript (subdir + '/SConscript')
935             
936 # cleanup
937 env.Clean ('scrub', [ 'scache.conf', '.sconf_temp', '.sconsign.dblite', 'config.log'])
938