Merge big changes (mostly Controllable) from trunk
[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 if conf.CheckCHeader('jack/midiport.h'):
494     libraries['sysmidi'] = LibraryInfo (LIBS='jack')
495     env['SYSMIDI'] = 'JACK MIDI'
496     subst_dict['%MIDITAG%'] = "control"
497     subst_dict['%MIDITYPE%'] = "jack"
498     print "Using JACK MIDI"
499 elif conf.CheckCHeader('alsa/asoundlib.h'):
500     libraries['sysmidi'] = LibraryInfo (LIBS='asound')
501     env['SYSMIDI'] = 'ALSA Sequencer'
502     subst_dict['%MIDITAG%'] = "seq"
503     subst_dict['%MIDITYPE%'] = "alsa/sequencer"
504     print "Using ALSA MIDI"
505 elif conf.CheckCHeader('/System/Library/Frameworks/CoreMIDI.framework/Headers/CoreMIDI.h'):
506     # this line is needed because scons can't handle -framework in ParseConfig() yet.
507     libraries['sysmidi'] = LibraryInfo (LINKFLAGS= '-framework CoreMIDI -framework CoreFoundation -framework CoreAudio -framework CoreServices -framework AudioUnit -framework AudioToolbox -bind_at_load')
508     env['SYSMIDI'] = 'CoreMIDI'
509     subst_dict['%MIDITAG%'] = "ardour"
510     subst_dict['%MIDITYPE%'] = "coremidi"
511     print "Using CoreMIDI"
512 else:
513     print "It appears you don't have the required MIDI libraries installed."
514     sys.exit (1)
515
516 env = conf.Finish()
517
518 if env['SYSLIBS']:
519     
520     libraries['sigc2'] = LibraryInfo()
521     libraries['sigc2'].ParseConfig('pkg-config --cflags --libs sigc++-2.0')
522     libraries['glibmm2'] = LibraryInfo()
523     libraries['glibmm2'].ParseConfig('pkg-config --cflags --libs glibmm-2.4')
524     libraries['gdkmm2'] = LibraryInfo()
525     libraries['gdkmm2'].ParseConfig ('pkg-config --cflags --libs gdkmm-2.4')
526     libraries['gtkmm2'] = LibraryInfo()
527     libraries['gtkmm2'].ParseConfig ('pkg-config --cflags --libs gtkmm-2.4')
528     libraries['atkmm'] = LibraryInfo()
529     libraries['atkmm'].ParseConfig ('pkg-config --cflags --libs atkmm-1.6')
530     libraries['pangomm'] = LibraryInfo()
531     libraries['pangomm'].ParseConfig ('pkg-config --cflags --libs pangomm-1.4')
532     libraries['libgnomecanvasmm'] = LibraryInfo()
533     libraries['libgnomecanvasmm'].ParseConfig ('pkg-config --cflags --libs libgnomecanvasmm-2.6')
534
535 #
536 # cannot use system one for the time being
537 #
538     
539     libraries['sndfile'] = LibraryInfo(LIBS='libsndfile',
540                                     LIBPATH='#libs/libsndfile',
541                                     CPPPATH=['#libs/libsndfile', '#libs/libsndfile/src'])
542
543 #    libraries['libglademm'] = LibraryInfo()
544 #    libraries['libglademm'].ParseConfig ('pkg-config --cflags --libs libglademm-2.4')
545
546 #    libraries['flowcanvas'] = LibraryInfo(LIBS='flowcanvas', LIBPATH='#/libs/flowcanvas', CPPPATH='#libs/flowcanvas')
547     libraries['soundtouch'] = LibraryInfo()
548     libraries['soundtouch'].ParseConfig ('pkg-config --cflags --libs libSoundTouch')
549     
550     coredirs = [
551         'templates'
552     ]
553     
554     subdirs = [
555         'libs/libsndfile',
556         'libs/pbd',
557         'libs/midi++2',
558         'libs/ardour'
559         ]
560     
561     if env['VST']:
562         subdirs = ['libs/fst'] + subdirs + ['vst']
563     
564     gtk_subdirs = [
565 #        'libs/flowcanvas',
566         'libs/gtkmm2ext',
567         'gtk2_ardour'
568         ]
569
570 else:
571     libraries['sigc2'] = LibraryInfo(LIBS='sigc++2',
572                                     LIBPATH='#libs/sigc++2',
573                                     CPPPATH='#libs/sigc++2')
574     libraries['glibmm2'] = LibraryInfo(LIBS='glibmm2',
575                                     LIBPATH='#libs/glibmm2',
576                                     CPPPATH='#libs/glibmm2')
577     libraries['pangomm'] = LibraryInfo(LIBS='pangomm',
578                                     LIBPATH='#libs/gtkmm2/pango',
579                                     CPPPATH='#libs/gtkmm2/pango')
580     libraries['atkmm'] = LibraryInfo(LIBS='atkmm',
581                                      LIBPATH='#libs/gtkmm2/atk',
582                                      CPPPATH='#libs/gtkmm2/atk')
583     libraries['gdkmm2'] = LibraryInfo(LIBS='gdkmm2',
584                                       LIBPATH='#libs/gtkmm2/gdk',
585                                       CPPPATH='#libs/gtkmm2/gdk')
586     libraries['gtkmm2'] = LibraryInfo(LIBS='gtkmm2',
587                                      LIBPATH="#libs/gtkmm2/gtk",
588                                      CPPPATH='#libs/gtkmm2/gtk/')
589     libraries['libgnomecanvasmm'] = LibraryInfo(LIBS='libgnomecanvasmm',
590                                                 LIBPATH='#libs/libgnomecanvasmm',
591                                                 CPPPATH='#libs/libgnomecanvasmm')
592     
593     libraries['soundtouch'] = LibraryInfo(LIBS='soundtouch',
594                                           LIBPATH='#libs/soundtouch',
595                                           CPPPATH=['#libs', '#libs/soundtouch'])
596     libraries['sndfile'] = LibraryInfo(LIBS='libsndfile',
597                                     LIBPATH='#libs/libsndfile',
598                                     CPPPATH=['#libs/libsndfile', '#libs/libsndfile/src'])
599 #    libraries['libglademm'] = LibraryInfo(LIBS='libglademm',
600 #                                          LIBPATH='#libs/libglademm',
601 #                                          CPPPATH='#libs/libglademm')
602     
603     coredirs = [
604         'libs/soundtouch',
605         'templates'
606     ]
607     
608     subdirs = [
609         'libs/sigc++2',
610         'libs/libsndfile',
611         'libs/pbd',
612         'libs/midi++2',
613         'libs/ardour'
614         ]
615     
616     if env['VST']:
617         subdirs = ['libs/fst'] + subdirs + ['vst']
618     
619     gtk_subdirs = [
620         'libs/glibmm2',
621         'libs/gtkmm2/pango',
622         'libs/gtkmm2/atk',
623         'libs/gtkmm2/gdk',
624         'libs/gtkmm2/gtk',
625         'libs/libgnomecanvasmm',
626 #       'libs/flowcanvas',
627     'libs/gtkmm2ext',
628     'gtk2_ardour'
629         ]
630
631 #
632 # always build the LGPL control protocol lib, since we link against it ourselves
633 # ditto for generic MIDI
634 #
635
636 surface_subdirs = [ 'libs/surfaces/control_protocol', 'libs/surfaces/generic_midi' ]
637
638 if env['SURFACES']:
639     if have_libusb:
640         surface_subdirs += [ 'libs/surfaces/tranzport' ]
641     if os.access ('libs/surfaces/sony9pin', os.F_OK):
642         surface_subdirs += [ 'libs/surfaces/sony9pin' ]
643
644 opts.Save('scache.conf', env)
645 Help(opts.GenerateHelpText(env))
646
647 if os.environ.has_key('PATH'):
648     env.Append(PATH = os.environ['PATH'])
649
650 if os.environ.has_key('PKG_CONFIG_PATH'):
651     env.Append(PKG_CONFIG_PATH = os.environ['PKG_CONFIG_PATH'])
652
653 if os.environ.has_key('CC'):
654     env['CC'] = os.environ['CC']
655
656 if os.environ.has_key('CXX'):
657     env['CXX'] = os.environ['CXX']
658
659 if os.environ.has_key('DISTCC_HOSTS'):
660     env['ENV']['DISTCC_HOSTS'] = os.environ['DISTCC_HOSTS']
661     env['ENV']['HOME'] = os.environ['HOME']
662
663 final_prefix = '$PREFIX'
664 install_prefix = '$DESTDIR/$PREFIX'
665
666 subst_dict['INSTALL_PREFIX'] = install_prefix;
667
668 if env['PREFIX'] == '/usr':
669     final_config_prefix = '/etc'
670 else:
671     final_config_prefix = env['PREFIX'] + '/etc'
672
673 config_prefix = '$DESTDIR' + final_config_prefix
674
675 # For colorgcc ( so says the wiki, but it's still not working :/  anyone? )
676 if os.environ.has_key('PATH'):
677         env['PATH'] = os.environ['PATH']
678 if os.environ.has_key('TERM'):
679         env['TERM'] = os.environ['TERM']
680 if os.environ.has_key('HOME'):
681         env['HOME'] = os.environ['HOME']
682
683
684 # SCons should really do this for us
685
686 conf = Configure (env)
687
688 have_cxx = conf.TryAction (Action (env['CXX'] + ' --version'))
689 if have_cxx[0] != 1:
690     print "This system has no functional C++ compiler. You cannot build Ardour from source without one."
691     exit (1)
692 else:
693     print "Congratulations, you have a functioning C++ compiler."
694
695 env = conf.Finish()
696
697 #
698 # Compiler flags and other system-dependent stuff
699 #
700
701 opt_flags = []
702 debug_flags = [ '-g' ]
703
704 # guess at the platform, used to define compiler flags
705
706 config_guess = os.popen("tools/config.guess").read()[:-1]
707
708 config_cpu = 0
709 config_arch = 1
710 config_kernel = 2
711 config_os = 3
712 config = config_guess.split ("-")
713
714 print "system triple: " + config_guess
715
716 # Autodetect
717 if env['DIST_TARGET'] == 'auto':
718     if config[config_arch] == 'apple':
719         # The [.] matches to the dot after the major version, "." would match any character
720         if re.search ("darwin[0-7][.]", config[config_kernel]) != None:
721             env['DIST_TARGET'] = 'panther'
722         else:
723             env['DIST_TARGET'] = 'tiger'
724     else:
725         if re.search ("x86_64", config[config_cpu]) != None:
726             env['DIST_TARGET'] = 'x86_64'
727         elif re.search("i[0-5]86", config[config_cpu]) != None:
728             env['DIST_TARGET'] = 'i386'
729         elif re.search("powerpc", config[config_cpu]) != None:
730             env['DIST_TARGET'] = 'powerpc'
731         else:
732             env['DIST_TARGET'] = 'i686'
733     print "\n*******************************"
734     print "detected DIST_TARGET = " + env['DIST_TARGET']
735     print "*******************************\n"
736
737
738 if config[config_cpu] == 'powerpc' and env['DIST_TARGET'] != 'none':
739     #
740     # Apple/PowerPC optimization options
741     #
742     # -mcpu=7450 does not reliably work with gcc 3.*
743     #
744     if env['DIST_TARGET'] == 'panther' or env['DIST_TARGET'] == 'tiger':
745         if config[config_arch] == 'apple':
746             opt_flags.extend ([ "-mcpu=7450", "-faltivec"])
747         else:
748             opt_flags.extend ([ "-mcpu=7400", "-maltivec", "-mabi=altivec"])
749     else:
750         opt_flags.extend([ "-mcpu=750", "-mmultiple" ])
751     opt_flags.extend (["-mhard-float", "-mpowerpc-gfxopt"])
752
753 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':
754     
755     build_host_supports_sse = 0
756     
757     debug_flags.append ("-DARCH_X86")
758     opt_flags.append ("-DARCH_X86")
759     
760     if config[config_kernel] == 'linux' :
761         
762         if env['DIST_TARGET'] != 'i386':
763             
764             flag_line = os.popen ("cat /proc/cpuinfo | grep '^flags'").read()[:-1]
765             x86_flags = flag_line.split (": ")[1:][0].split (' ')
766             
767             if "mmx" in x86_flags:
768                 opt_flags.append ("-mmmx")
769             if "sse" in x86_flags:
770                 build_host_supports_sse = 1
771             if "3dnow" in x86_flags:
772                 opt_flags.append ("-m3dnow")
773             
774             if config[config_cpu] == "i586":
775                 opt_flags.append ("-march=i586")
776             elif config[config_cpu] == "i686":
777                 opt_flags.append ("-march=i686")
778     
779     if ((env['DIST_TARGET'] == 'i686') or (env['DIST_TARGET'] == 'x86_64')) and build_host_supports_sse:
780         opt_flags.extend (["-msse", "-mfpmath=sse"])
781         debug_flags.extend (["-msse", "-mfpmath=sse"])
782 # end of processor-specific section
783
784 # optimization section
785 if env['FPU_OPTIMIZATION']:
786     if env['DIST_TARGET'] == 'tiger':
787         opt_flags.append ("-DBUILD_VECLIB_OPTIMIZATIONS")
788         debug_flags.append ("-DBUILD_VECLIB_OPTIMIZATIONS")
789         libraries['core'].Append(LINKFLAGS= '-framework Accelerate')
790     elif env['DIST_TARGET'] == 'i686' or env['DIST_TARGET'] == 'x86_64':
791         opt_flags.append ("-DBUILD_SSE_OPTIMIZATIONS")
792         debug_flags.append ("-DBUILD_SSE_OPTIMIZATIONS")
793         if env['DIST_TARGET'] == 'x86_64':
794             opt_flags.append ("-DUSE_X86_64_ASM")
795             debug_flags.append ("-DUSE_X86_64_ASM")
796         if build_host_supports_sse != 1:
797             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)"
798 # end optimization section
799
800 #
801 # save off guessed arch element in an env
802 #
803 env.Append(CONFIG_ARCH=config[config_arch])
804
805
806 #
807 # ARCH="..." overrides all
808 #
809
810 if env['ARCH'] != '':
811     opt_flags = env['ARCH'].split()
812
813 #
814 # prepend boiler plate optimization flags
815 #
816
817 opt_flags[:0] = [
818     "-O3",
819     "-fomit-frame-pointer",
820     "-ffast-math",
821     "-fstrength-reduce"
822     ]
823
824 if env['DEBUG'] == 1:
825     env.Append(CCFLAGS=" ".join (debug_flags))
826 else:
827     env.Append(CCFLAGS=" ".join (opt_flags))
828
829 #
830 # warnings flags
831 #
832
833 env.Append(CCFLAGS="-Wall")
834 env.Append(CXXFLAGS="-Woverloaded-virtual")
835
836 if env['LIBLO']:
837     env.Append(CCFLAGS="-DHAVE_LIBLO")
838
839 #
840 # everybody needs this
841 #
842
843 env.Merge ([ libraries['core'] ])
844
845 #
846 # fix scons nitpickiness on APPLE
847 #
848
849 if env['DIST_TARGET'] == 'panther' or env['DIST_TARGET'] == 'tiger':
850     env.Append(CCFLAGS="-I/opt/local/include", LINKFLAGS="-L/opt/local/lib")
851
852 #
853 # i18n support
854 #
855
856 conf = Configure (env)
857 if env['NLS']:
858     nls_error = 'This system is not configured for internationalized applications.  An english-only version will be built:'
859     print 'Checking for internationalization support ...'
860     have_gettext = conf.TryAction(Action('xgettext --version'))
861     if have_gettext[0] != 1:
862         nls_error += ' No xgettext command.'
863         env['NLS'] = 0
864     else:
865         print "Found xgettext"
866     
867     have_msgmerge = conf.TryAction(Action('msgmerge --version'))
868     if have_msgmerge[0] != 1:
869         nls_error += ' No msgmerge command.'
870         env['NLS'] = 0
871     else:
872         print "Found msgmerge"
873     
874     if not conf.CheckCHeader('libintl.h'):
875         nls_error += ' No libintl.h.'
876         env['NLS'] = 0
877         
878     if env['NLS'] == 0:
879         print nls_error
880     else:
881         print "International version will be built."
882 env = conf.Finish()
883
884 if env['NLS'] == 1:
885     env.Append(CCFLAGS="-DENABLE_NLS")
886
887 Export('env install_prefix final_prefix config_prefix final_config_prefix libraries i18n version subst_dict')
888
889 #
890 # the configuration file may be system dependent
891 #
892
893 conf = env.Configure ()
894
895 if conf.CheckCHeader('/System/Library/Frameworks/CoreAudio.framework/Versions/A/Headers/CoreAudio.h'):
896     subst_dict['%JACK_INPUT%'] = "coreaudio:Built-in Audio:in"
897     subst_dict['%JACK_OUTPUT%'] = "coreaudio:Built-in Audio:out"
898 else:
899     subst_dict['%JACK_INPUT%'] = "alsa_pcm:playback_"
900     subst_dict['%JACK_OUTPUT%'] = "alsa_pcm:capture_"
901
902 # posix_memalign available
903 if not conf.CheckFunc('posix_memalign'):
904     print 'Did not find posix_memalign(), using malloc'
905     env.Append(CCFLAGS='-DNO_POSIX_MEMALIGN')
906
907
908 env = conf.Finish()
909
910 rcbuild = env.SubstInFile ('ardour.rc','ardour.rc.in', SUBST_DICT = subst_dict)
911
912 env.Alias('install', env.Install(os.path.join(config_prefix, 'ardour2'), 'ardour_system.rc'))
913 env.Alias('install', env.Install(os.path.join(config_prefix, 'ardour2'), 'ardour.rc'))
914
915 Default (rcbuild)
916
917 # source tarball
918
919 Precious (env['DISTTREE'])
920
921 #
922 # note the special "cleanfirst" source name. this triggers removal
923 # of the existing disttree
924 #
925
926 env.Distribute (env['DISTTREE'],
927                 [ 'SConstruct',
928                   'COPYING', 'PACKAGER_README', 'README',
929                   'ardour.rc.in',
930                   'ardour_system.rc',
931                   'tools/config.guess'
932                   ] +
933                 glob.glob ('DOCUMENTATION/AUTHORS*') +
934                 glob.glob ('DOCUMENTATION/CONTRIBUTORS*') +
935                 glob.glob ('DOCUMENTATION/TRANSLATORS*') +
936                 glob.glob ('DOCUMENTATION/BUILD*') +
937                 glob.glob ('DOCUMENTATION/FAQ*') +
938                 glob.glob ('DOCUMENTATION/README*')
939                 )
940
941 srcdist = env.Tarball(env['TARBALL'], env['DISTTREE'])
942 env.Alias ('srctar', srcdist)
943 #
944 # don't leave the distree around
945 #
946 env.AddPreAction (env['DISTTREE'], Action ('rm -rf ' + str (File (env['DISTTREE']))))
947 env.AddPostAction (srcdist, Action ('rm -rf ' + str (File (env['DISTTREE']))))
948
949 #
950 # the subdirs
951 #
952
953 for subdir in coredirs:
954     SConscript (subdir + '/SConscript')
955
956 for sublistdir in [ subdirs, gtk_subdirs, surface_subdirs ]:
957     for subdir in sublistdir:
958         SConscript (subdir + '/SConscript')
959
960 # cleanup
961 env.Clean ('scrub', [ 'scache.conf', '.sconf_temp', '.sconsign.dblite', 'config.log'])
962