#!/usr/bin/env python
import autowaf
import os
import glob
import Options
import sys
import TaskGen
import re

# Version of this package (even if built as a child)
MAJOR = '3'
MINOR = '0'
MICRO = '0'
GTK2_ARDOUR_VERSION = "%s.%s.%s" % (MAJOR, MINOR, MICRO)

# Variables for 'waf dist'
APPNAME = 'gtk2_ardour'
VERSION = GTK2_ARDOUR_VERSION

# Mandatory variables
srcdir = '.'
blddir = 'build'

path_prefix = 'gtk2_ardour/'

gtk2_ardour_sources = [
	'about.cc',
	'actions.cc',
	'add_midi_cc_track_dialog.cc',
	'add_route_dialog.cc',
	'analysis_window.cc',
	'ardour_dialog.cc',
	'ardour_ui.cc',
	'ardour_ui2.cc',
	'ardour_ui_dependents.cc',
	'ardour_ui_dialogs.cc',
	'ardour_ui_ed.cc',
	'ardour_ui_mixer.cc',
	'ardour_ui_options.cc',
	'audio_clock.cc',
	'audio_region_editor.cc',
	'audio_region_view.cc',
	'audio_streamview.cc',
	'audio_time_axis.cc',
	'automation_controller.cc',
	'automation_line.cc',
	'automation_region_view.cc',
	'automation_streamview.cc',
	'automation_time_axis.cc',
	'axis_view.cc',
	'bundle_manager.cc',
	'cairo_widget.cc',
	'canvas-flag.cc',
	'canvas-hit.cc',
	'canvas-note-event.cc',
	'canvas-note.cc',
	'canvas-program-change.cc',
	'canvas-simpleline.c',
	'canvas-simplerect.c',
	'canvas-sysex.cc',
	'canvas-waveview.c',
	'configinfo.cc',
	'control_point.cc',
	'control_point_dialog.cc',
	'crossfade_edit.cc',
	'crossfade_view.cc',
	'curvetest.cc',
	'diamond.cc',
	'editing.cc',
	'editor.cc',
	'editor_actions.cc',
	'editor_audio_import.cc',
	'editor_audiotrack.cc',
	'editor_canvas.cc',
	'editor_canvas_events.cc',
	'editor_component.cc',
	'editor_cursors.cc',
	'editor_drag.cc',
	'editor_route_groups.cc',
	'editor_export_audio.cc',
	'editor_group_tabs.cc',
	'editor_keyboard.cc',
	'editor_keys.cc',
	'editor_locations.cc',
	'editor_markers.cc',
	'editor_mixer.cc',
	'editor_mouse.cc',
	'editor_nudge.cc',
	'editor_ops.cc',
	'editor_regions.cc',
	'editor_routes.cc',
	'editor_rulers.cc',
	'editor_scrub.cc',
	'editor_selection.cc',
	'editor_snapshots.cc',
	'editor_summary.cc',
	'editor_tempodisplay.cc',
	'editor_timefx.cc',
	'engine_dialog.cc',
	'enums.cc',
	'export_channel_selector.cc',
	'export_dialog.cc',
	'export_file_notebook.cc',
	'export_filename_selector.cc',
	'export_format_dialog.cc',
	'export_format_selector.cc',
	'export_preset_selector.cc',
	'export_timespan_selector.cc',
	'fft.cc',
	'fft_graph.cc',
	'fft_result.cc',
	'gain_meter.cc',
	'generic_pluginui.cc',
	'ghostregion.cc',
	'global_port_matrix.cc',
	'group_tabs.cc',
	'gtk-custom-hruler.c',
	'gtk-custom-ruler.c',
	'interthread_progress_window.cc',
	'io_selector.cc',
	'keyboard.cc',
	'keyeditor.cc',
	'latency_gui.cc',
        'led.cc',
	'level_meter.cc',
	'lineset.cc',
	'location_ui.cc',
	'main.cc',
	'marker.cc',
	'midi_automation_line.cc',
	'midi_channel_selector.cc',
	'midi_cut_buffer.cc',
	'midi_list_editor.cc',
	'midi_port_dialog.cc',
	'midi_region_view.cc',
	'midi_scroomer.cc',
	'midi_streamview.cc',
	'midi_time_axis.cc',
	'midi_tracer.cc',
	'mixer_group_tabs.cc',
	'mixer_strip.cc',
	'mixer_ui.cc',
        'monitor_section.cc',
	'nag.cc',
	'option_editor.cc',
	'opts.cc',
	'panner.cc',
	'panner2d.cc',
	'panner_ui.cc',
	'piano_roll_header.cc',
	'playlist_selector.cc',
	'plugin_eq_gui.cc',
	'plugin_selector.cc',
	'plugin_ui.cc',
	'port_group.cc',
	'port_matrix.cc',
	'port_matrix_body.cc',
	'port_matrix_column_labels.cc',
	'port_matrix_component.cc',
	'port_matrix_grid.cc',
	'port_matrix_labels.cc',
	'port_matrix_row_labels.cc',
	'processor_box.cc',
	'prompter.cc',
	'public_editor.cc',
	'quantize_dialog.cc',
	'rc_option_editor.cc',
	'region_editor.cc',
	'region_gain_line.cc',
	'region_selection.cc',
	'region_view.cc',
	'return_ui.cc',
	'rhythm_ferret.cc',
	'route_group_dialog.cc',
	'route_group_menu.cc',
	'route_params_ui.cc',
	'route_processor_selection.cc',
	'route_time_axis.cc',
	'route_ui.cc',
	'selection.cc',
	'send_ui.cc',
	'session_import_dialog.cc',
	'session_metadata_dialog.cc',
	'session_option_editor.cc',
	'sfdb_ui.cc',
	'simpleline.cc',
	'simplerect.cc',
	'splash.cc',
	'startup.cc',
	'streamview.cc',
	'strip_silence_dialog.cc',
	'tape_region_view.cc',
	'tempo_dialog.cc',
	'tempo_lines.cc',
	'theme_manager.cc',
	'time_axis_view.cc',
	'time_axis_view_item.cc',
	'time_fx_dialog.cc',
	'time_selection.cc',
	'track_selection.cc',
	'track_view_list.cc',
	'ui_config.cc',
	'utils.cc',
	'version.cc',
        'volume_controller.cc',
	'waveview.cc',
]

def set_options(opt):
	autowaf.set_options(opt)

def configure(conf):
	autowaf.build_version_files(path_prefix+'version.h', path_prefix+'version.cc',
			'gtk2_ardour', MAJOR, MINOR, MICRO)
	autowaf.configure(conf)
	conf.check_tool('compiler_cxx')

	if re.search ("linux", sys.platform) != None:
		autowaf.check_pkg(conf, 'alsa', uselib_store='ALSA')
		#
		#	TODO: Insert a sanity check for on OS X
		#	to ensure that CoreAudio is present....
		#	Really shouldn't these checks be in AutoWaf?
		#
	autowaf.check_pkg(conf, 'flac', uselib_store='FLAC', atleast_version='1.2.1')
	autowaf.check_pkg(conf, 'gthread', uselib_store='GTHREAD', atleast_version='2.10.1')
	autowaf.check_pkg(conf, 'gtk+-2.0', uselib_store='GTK', atleast_version='2.12.1')
	autowaf.check_pkg(conf, 'gtkmm-2.4', uselib_store='GTKMM', atleast_version='2.8')
	autowaf.check_pkg(conf, 'libgnomecanvas-2.0', uselib_store='GNOMECANVAS', atleast_version='2.0')
	autowaf.check_pkg(conf, 'libgnomecanvasmm-2.6', uselib_store='GNOMECANVASMM', atleast_version='2.12.0')
	autowaf.check_pkg(conf, 'ogg', uselib_store='OGG', atleast_version='1.1.2')

	conf.check_tool('misc') # subst tool

	conf.write_config_header('gtk2ardour-config.h')
	
	# Boost headers
	autowaf.check_header(conf, 'boost/shared_ptr.hpp')
	autowaf.check_header(conf, 'boost/weak_ptr.hpp')

# Add a waf `feature' to allow compilation of things using winegcc
from TaskGen import feature
@feature("wine")
def set_winegcc(self):
	self.env.LINK_CXX = self.env.LINK_CC = 'wineg++'
	self.env.CC = 'winegcc'

def build(bld):
	# GTK front-end; if we're using VST we build this as a shared library, otherwise
	# it's a normal executabale
	if bld.env['VST_SUPPORT']:
		obj = bld.new_task_gen(features = 'cxx cc cshlib')
	else:
		obj = bld.new_task_gen(features = 'cxx cc cprogram')

	obj.includes     = ['.']
	obj.source       = gtk2_ardour_sources
	obj.name         = 'gtk2_ardour'
	if bld.env['VST_SUPPORT']:
		obj.target = 'gtk2_ardour'
		obj.includes += ['../libs/fst']
	else:
		obj.target = 'ardour-3.0'
	obj.install_path = os.path.join(bld.env['LIBDIR'], 'ardour3')
	obj.uselib       = 'UUID FLAC GLIBMM GTHREAD GTK GNOMECANVAS OGG ALSA'
	obj.uselib       += ' GTKMM GNOMECANVASMM OSX GTKOSX COREAUDIO'
	obj.uselib_local = '''libpbd libmidipp libtaglib libardour libardour_cp
	                      libgtkmm2ext libtaglib'''
	obj.cflags       = ['-DPACKAGE="gtk2_ardour"']
	obj.cxxflags     = ['-DPACKAGE="gtk2_ardour"']
	obj.cxxflags     += ['-DVERSIONSTRING="' + bld.env['VERSION'] + '"']
	obj.cxxflags     += ['-DDATA_DIR="' + os.path.normpath(bld.env['DATADIR']) + '"']
	obj.cxxflags     += ['-DCONFIG_DIR="' + os.path.normpath(bld.env['CONFIGDIR']) + '"']
	obj.cxxflags     += ['-DMODULE_DIR="' + os.path.normpath(bld.env['LIBDIR']) + '"']
	obj.cxxflags     += ['-DLOCALEDIR="' + os.path.join(
			os.path.normpath(bld.env['DATADIR']), 'locale') + '"']
        obj.cxxflags     += ['-DPROGRAM_NAME="' + bld.env['PROGRAM_NAME'] + '"']

	if bld.env['HAVE_SLV2']:
		obj.source += [ 'lv2_plugin_ui.cc' ]
		obj.uselib += ' SLV2 '

	if bld.env['FREESOUND']:
		obj.source +=  [ 'sfdb_freesound_mootcher.cc' ]

	if bld.env['VST_SUPPORT']:
		obj.source += [ 'vst_pluginui.cc' ]
		obj.cxxflags += [ '-DVST_SUPPORT' ]

	if bld.env['GTKOSX']:
		TaskGen.task_gen.mappings['.mm'] = TaskGen.task_gen.mappings['.cc']
		obj.source += [ 'cocoacarbon.mm' ]

		if bld.env['AUDIOUNITS']:
			obj.source += [ 'au_pluginui.mm' ]
			obj.uselib_local += ' libappleutility '

	else:
		obj.source += [ 'x11.cc' ]

	if bld.env['VST_SUPPORT']:
		# If we require VST support we build a stub main() and the FST library here using
		# winegcc, and link it to the GTK front-end library
		obj = bld.new_task_gen (features = 'cxx cc cprogram wine')
		obj.source = '''
			../libs/fst/fst.c
			../libs/fst/fstinfofile.c
			../libs/fst/vsti.c
			../libs/fst/vstwin.c
			../vst/winmain.c
		'''
		obj.includes = '../libs/fst'
		obj.target = 'ardour-3.0-vst'
		obj.linkflags = ['-mwindows', '-Wl,--export-dynamic']
		obj.defines = ['_POSIX_SOURCE', 'USE_WS_PREFIX']
		obj.uselib = 'ALSA'
		obj.uselib_local = '''libpbd libmidipp libtaglib libardour libardour_cp libgtkmm2ext libtaglib gtk2_ardour'''

	# Wrappers

	wrapper_subst_dict = {
		'INSTALL_PREFIX' : bld.env['PREFIX'],
		'LIBDIR'         : os.path.normpath(bld.env['LIBDIRNAME']),
		'LIBS'           : 'build/default/libs',
		'VERSION'        : '3.0',
		'EXECUTABLE'     : 'build/default/gtk2_ardour/ardour-3.0'
	}

	obj              = bld.new_task_gen('subst')
	obj.source       = 'ardev_common.sh.in'
	obj.target       = 'ardev_common_waf.sh'
	obj.chmod        = 0755
	obj.dict         = wrapper_subst_dict

	obj              = bld.new_task_gen('subst')
	obj.source       = 'ardour.sh.in'
	obj.target       = 'ardour3'
	obj.chmod        = 0755
	obj.dict         = wrapper_subst_dict
	obj.install_path = bld.env['BINDIR']

	# Font configuration

	font_subst_dict = {}
	font_sizes      = {}
	base_font       = ""

	# Set up font sizes
	if bld.env['IS_OSX']: # OS X fonts
		basefont = "Lucida Grande"
		font_sizes = {
			'TINY' : '7',
			'SMALLER' : '9',
			'SMALL' : '10',
			'NORMAL' : '11',
			'BIG' : '12',
			'BIGGER' : '14',
			'LARGE' : '18',
			'LARGER' : '28',
			'HUGER' : '36',
			'MASSIVE' : '60'
		}
	else: # Linux/X11 fonts
		basefont = "sans"
		font_sizes = {
			'TINY' : '6',
			'SMALLER' : '8',
			'SMALL' : '9',
			'NORMAL' : '10',
			'BIG' : '14',
			'BIGGER' : '16',
			'LARGE' : '18',
			'LARGER' : '24',
			'HUGER' : '34',
			'MASSIVE' : '60'
		}

 	# Set up font substitution dictionary
	for style in ['', 'BOLD', 'ITALIC']:
		for sizename,points in font_sizes.iteritems():
			if (len (style)):
				key = "_".join (['FONT',style,sizename])
				fontstyle = " ".join ([basefont,style.lower(),points])
			else:
				key = "_".join (['FONT',sizename])
				fontstyle = " ".join ([basefont,points])
				
			font_subst_dict[key] = fontstyle

	# add normal monospace to font dict
	font_subst_dict['FONT_MONOSPACE_NORMAL'] = 'monospace 10'

	# RC files
	obj              = bld.new_task_gen('subst')
	obj.source       = 'ardour3_ui_dark.rc.in'
	obj.target       = 'ardour3_ui_dark.rc'
	obj.dict         = font_subst_dict
	obj.install_path = os.path.join(bld.env['CONFIGDIR'], 'ardour3')

	obj              = bld.new_task_gen('subst')
	obj.source       = 'ardour3_ui_light.rc.in'
	obj.target       = 'ardour3_ui_light.rc'
	obj.dict         = font_subst_dict
	obj.install_path = os.path.join(bld.env['CONFIGDIR'], 'ardour3')

	obj              = bld.new_task_gen('subst')
	obj.source       = 'ardour3_ui_dark_sae.rc.in'
	obj.target       = 'ardour3_ui_dark_sae.rc'
	obj.dict         = font_subst_dict
	obj.install_path = os.path.join(bld.env['CONFIGDIR'], 'ardour3')

	obj              = bld.new_task_gen('subst')
	obj.source       = 'ardour3_ui_light_sae.rc.in'
	obj.target       = 'ardour3_ui_light_sae.rc'
	obj.dict         = font_subst_dict
	obj.install_path = os.path.join(bld.env['CONFIGDIR'], 'ardour3')

	# Menus
	menus_argv = []
	if bld.env['GTKOSX']:
		menus_argv = [ '-E', '-P', '-DGTKOSX' ]
	else:
		menus_argv = [ '-E', '-P' ]
	obj = bld.new_task_gen('command-output')
	obj.command = 'cpp'
	obj.command_is_external = True
	obj.no_inputs = True
	obj.argv = menus_argv
	obj.stdin = 'ardour.menus.in'
	obj.stdout = 'ardour.menus'
	bld.install_files(os.path.join(bld.env['CONFIGDIR'], 'ardour3'), 'ardour.menus')

	# Keybindings

        # 'SAE-de-keypad', 'SAE-de-nokeypad', 'SAE-us-keypad', 'SAE-us-nokeypad', 'ergonomic-us'

	for b in [ 'mnemonic-us' ] :
		obj = bld.new_task_gen (
			target = b + '.bindings',
			source = b + '.bindings.in',
			rule = '../tools/fmt-bindings --winkey=%s --accelmap <${SRC} >${TGT}' % bld.env['windows_key']
			)
		obj.install_path = os.path.join(bld.env['CONFIGDIR'], 'ardour3')

	# Icons/Images
	bld.install_files('${DATADIR}/ardour3/icons', 'icons/*.png')
	bld.install_files('${DATADIR}/ardour3/pixmaps', 'pixmaps/*.xpm')
	bld.install_files('${DATADIR}/ardour3', 'splash.png')

	# Default UI configuration
	bld.install_files('${CONFIGDIR}/ardour3', 'ardour3_ui_default.conf')

	# i18n
	if bld.env['ENABLE_NLS']:
		mo_files = glob.glob (os.path.join (bld.get_curdir(), 'po/*.mo'))
		for mo in mo_files:
			lang = os.path.basename (mo).replace ('.mo', '')
			bld.install_as (os.path.join (bld.env['PREFIX'], 'share', 'locale', lang, 'LC_MESSAGES', APPNAME + '.mo'), mo)

def i18n(bld):
	autowaf.build_i18n (bld, 'gtk2_ardour', APPNAME, gtk2_ardour_sources)

