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