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