# vim: filetype=python expandtab sw=4 tabstop=4
# Since all frontends require very little code, we don't split this
# SConscript into several.

import os

Import("commonEnvironment", "commandOptions", "util" )
Import("configure")

# Add all the options first
commandOptions.Add('buildCsound5GUI',
    'Build FLTK GUI frontend (requires FLTK 1.1.7 or later).',
    '0')
commandOptions.Add('buildWinsound',
    "Build Winsound frontend. Requires FLTK headers and libs",
    '0')
commandOptions.Add('buildOSXGUI',
    'On OSX, set to 1 to build the basic GUI frontend',
    '0')
commandOptions.Add('buildCSEditor',
    'Set to 1 to build the Csound syntax highlighting text editor. Requires FLTK headers and libs',
    '0')
commandOptions.Add('buildPDClass',
    "build csoundapi~ PD class (needs m_pd.h in the standard places)",
    '0')
commandOptions.Add('buildTclcsound',
    "Build Tclcsound frontend (cstclsh, cswish and tclcsound dynamic module). Requires Tcl/Tk headers and libs",
    '0')

commandOptions.Update(commonEnvironment)

util.fixEnvForOLPC(commonEnvironment)

# First the csound program with no dependencies
programEnvironment = commonEnvironment.Clone()
csoundSources = ['csound/csound_main.c']
if util.platform == 'linux':
    csoundSources += ['csound/sched.c'] 
csoundProgram = programEnvironment.Program('csound/csound', csoundSources)

# FLTK csound5gui


if commonEnvironment['buildCsound5GUI'] != '0':
    util.confDecision("Building FLTK GUI CSOUND5GUI frontend.")
    found117 = configure.CheckHeader("FL/Fl_Spinner.H", language = "C++")
    if not found117:
        util.fatal("You specified buildCsound5GUI, but you don't have FLTK 1.17 installed.")

    csound5GUIEnvironment = programEnvironment.Clone()
    if configure.CheckLibWithHeader("jack", "jack/jack.h", language = "C", autoadd=False):
        csound5GUIEnvironment.Append(LIBS = ['jack'])
        csound5GUIEnvironment.Prepend(CPPFLAGS = ['-DHAVE_JACK'])
    if util.platform == 'linux':
        csound5GUIEnvironment.ParseConfig('fltk-config --use-images --cflags --cxxflags --ldflags')
        csound5GUIEnvironment.Append(LIBS = ['stdc++', 'pthread', 'm'])
    elif util.platform == 'win32':
        if util.compilerGNU():
            csound5GUIEnvironment.Append(LIBS = ['stdc++', 'supc++'])
            csound5GUIEnvironment.Prepend(LINKFLAGS = Split('''
                -mwindows -Wl,--enable-runtime-pseudo-reloc
            '''))
            csound5GUIEnvironment.Append(LIBS = Split('fltk_images fltk_png fltk_z fltk_jpeg fltk'))
        else:
            csound5GUIEnvironment.Append(LIBS = Split('fltkimages fltkpng fltkz fltkjpeg fltk'))
    elif util.platform == 'darwin':
        csound5GUIEnvironment.Prepend(CXXFLAGS = "-fno-rtti")
        csound5GUIEnvironment.Append(LIBS = Split('''
            fltk stdc++ pthread m
        '''))
        csound5GUIEnvironment.Append(LINKFLAGS = Split('''
            -framework Carbon -framework ApplicationServices
        '''))

    csound5GUISources = Split('''
        fltk_gui/ConfigFile.cpp
        fltk_gui/CsoundCopyrightInfo.cpp
        fltk_gui/CsoundGlobalSettings.cpp
        fltk_gui/CsoundGUIConsole.cpp
        fltk_gui/CsoundGUIMain.cpp
        fltk_gui/CsoundPerformance.cpp
        fltk_gui/CsoundPerformanceSettings.cpp
        fltk_gui/CsoundUtility.cpp
        fltk_gui/CsoundEditor.cpp
        fltk_gui/Fl_Native_File_Chooser.cxx
        fltk_gui/main.cpp
    ''')
    csound5GUIFluidSources = Split('''
        CsoundAboutWindow_FLTK
        CsoundGlobalSettingsPanel_FLTK
        CsoundGUIConsole_FLTK
        CsoundGUIMain_FLTK
        CsoundPerformanceSettingsPanel_FLTK
        CsoundUtilitiesWindow_FLTK
    ''')
    csound5GUIObjectFiles = []
    csound5GUIFluidObjectFiles = []
    for i in csound5GUISources:
        csound5GUIObjectFiles += csound5GUIEnvironment.Object(i)
    csound5GUIEnvironment.Append( CPPPATH = '#/interfaces' )
    csound5GUIObjectFiles += csound5GUIEnvironment.Object(
        'fltk_gui/csPerfThread', '#/interfaces/csPerfThread.cpp')
    for i in csound5GUIFluidSources:
        csound5GUIFluidObjectFiles += csound5GUIEnvironment.Object(
            util.fluidTarget(csound5GUIEnvironment, 'fltk_gui', i,
                        csound5GUIObjectFiles, 'frontends'))
    csound5GUIObjectFiles += csound5GUIFluidObjectFiles
    csound5GUI = csound5GUIEnvironment.Program('fltk_gui/csound5gui',
                                  csound5GUIObjectFiles)
    if util.platform == 'darwin':
        appDir = 'fltk_gui/Csound5GUI.app/Contents/MacOS'
        util.addOSXResourceFork(csound5GUIEnvironment, 'csound5gui', '')
        csound5GUIEnvironment.Command(
            '%s/csound5gui' % appDir, 'csound5gui', "cp $SOURCE %s/" % appDir)
        util.addOSXResourceFork(csound5GUIEnvironment, 'csound5gui', appDir)
 
else:
    util.confDecision("Not building FLTK CSOUND5GUI frontend.")

# Winsound
if commonEnvironment['buildWinsound'] == '1':
    fltkfound = configure.CheckLibWithHeader("fltk", "FL/Fl.H",
            language = "C++", autoadd = False)
    util.confDecision("Building Winsound frontend")
    # should these be installed ?
    # headers += glob.glob('frontends/winsound/*.h')
    csWinEnvironment = commonEnvironment.Clone()
    # not used
    # if (commonEnvironment['noFLTKThreads'] == '1'):
    #     csWinEnvironment.Append(CCFLAGS = ['-DNO_FLTK_THREADS'])
    if util.platform == 'linux':
        csWinEnvironment.ParseConfig('fltk-config --use-images --cflags \
                --cxxflags --ldflags')
        csWinEnvironment.Append(LIBS = ['stdc++', 'pthread', 'm'])
    elif util.platform == 'win32':
        if util.compilerGNU():
            csWinEnvironment.Append(LIBS = Split(
                'fltk_images fltk_png fltk_z fltk_jpeg fltk'))
            csWinEnvironment.Append(LIBS = ['stdc++', 'supc++'])
            csWinEnvironment.Prepend(LINKFLAGS = Split('''
                -mwindows -Wl,--enable-runtime-pseudo-reloc
            '''))
        else:
            csWinEnvironment.Append(LIBS = Split('fltkimages fltkpng fltkz fltkjpeg fltk'))
    elif util.platform == 'darwin':
        csWinEnvironment.Append(CXXFLAGS = ['-fno-rtti'])
        csWinEnvironment.Append(LIBS = ['fltk', 'stdc++', 'pthread', 'm'])
        csWinEnvironment.Append(LINKFLAGS = Split('''
            -framework Carbon -framework CoreAudio -framework CoreMidi
            -framework ApplicationServices
        '''))
        appDir = 'frontends/winsound/Winsound.app/Contents/MacOS'
        util.addOSXResourceFork(csWinEnvironment, 'winsound', '')
        csWinEnvironment.Command(
            '%s/winsound' % appDir, 'winsound', "cp $SOURCE %s/" % appDir)
        util.addOSXResourceFork(csWinEnvironment, 'winsound', appDir)
    flSrc = 'winsound/winsound.cpp'
    flHdr = 'winsound/winsound.h'
    fl    = 'winsound/winsound.fl'
    winsoundSrcs = csWinEnvironment.Command([flSrc, flHdr],
            fl, 'fluid -c -o frontends/%s -h frontends/%s frontends/%s' %
            (flSrc, flHdr, fl))
    # winsoundSrcs contains the header and the cpp file
    winsoundSrc = winsoundSrcs[0]
    winsoundMain = csWinEnvironment.Object('winsound/main.cxx')
    Depends(winsoundMain, winsoundSrc)
    winsound5 = csWinEnvironment.Program(
        'winsound/winsound', [winsoundMain, winsoundSrc])
else:
    util.confDecision("Not building Winsound")

# OSX frontend
if (util.platform == 'darwin' and commonEnvironment['buildOSXGUI'] == '1'):
    util.confDecision("Building OSX GUI frontend")
    csOSXGUIEnvironment = commonEnvironment.Clone()
    OSXGUI = csOSXGUIEnvironment.Command(
        '''OSX/build/Csound 5.app/Contents/MacOS/Csound 5''',
        'OSX/main.c',
        "cd frontends/OSX; xcodebuild -buildstyle Deployment")
else:
    util.confDecision("Not building OSX GUI frontend")

# csLadspa
print "CONFIGURATION DEFAULT:  Building csLadspa."
csLadspaEnv = commonEnvironment.Clone()
csLadspaEnv.Append(CPPPATH='#/frontends/csladspa')
if util.platform == "darwin":
    if commonEnvironment['dynamicCsoundLibrary'] != '0':
        csLadspaEnv.Append(LINKFLAGS=Split('''
            -bundle -undefined suppress -flat_namespace
             -framework CsoundLib
        '''))
    else:
        csLadspaEnv.Append(LINKFLAGS="-bundle")
    csladspa = csLadspaEnv.Program('csladspa.so',
         'csladspa/csladspa.cpp' )
else:
    csladspa = csLadspaEnv.SharedLibrary('csladspa/csladspa.cpp')

# Cseditor
if commonEnvironment['buildCSEditor'] == '1':
    fltkfound = configure.CheckLibWithHeader("fltk", "FL/Fl.H",
            language = "C++", autoadd = False)
    if not fltkfound:
        util.Fatal("You specified buildCSeditor, but FLTK was not found")
    util.confDecision('Building Csound Text Editor.')
    csEditorEnvironment = commonEnvironment.Clone()
    if util.platform == 'linux':
        csEditorEnvironment.ParseConfig(
                'fltk-config --use-images --cflags --cxxflags --ldflags')
        csEditorEnvironment.Append(LIBS = ['stdc++', 'pthread', 'm'])
    elif util.platform == 'win32':
        if util.compilerGNU():
            csEditorEnvironment.Append(LIBS = ['stdc++', 'supc++'])
            csEditorEnvironment.Prepend(LINKFLAGS =
                    Split('''-mwindows -Wl,--enable-runtime-pseudo-reloc'''))
            csEditorEnvironment.Append(LIBS = 
                    Split('fltk_images fltk_png fltk_z fltk_jpeg fltk'))
        else:
            csEditorEnvironment.Append(LIBS =
                    Split('fltkimages fltkpng fltkz fltkjpeg fltk'))
    elif util.platform == 'darwin':
        csEditorEnvironment.Prepend(CXXFLAGS = "-fno-rtti")
        csEditorEnvironment.Append(LIBS = Split('fltk stdc++ pthread m'))
        csEditorEnvironment.Append(LINKFLAGS = Split('''
            -framework Carbon -framework ApplicationServices
        '''))
        csEditorEnvironment.ParseConfig(
                "fltk-config --use-images --cflags --cxxflags --ldflags")

    csEditor = csEditorEnvironment.Program( 'cseditor/cseditor',
            'cseditor/cseditor.cxx')
else:
    util.confDecision('Not building Csound Text Editor.')

if commonEnvironment['buildPDClass'] != '0':
    if not configure.CheckHeader('m_pd.h', language = 'C'):
        util.fatal('You specified buildPDClass but PD was not found')
    pdClassEnvironment = commonEnvironment.Clone()
    if util.platform == 'darwin':
        pdClassEnvironment.Append(LINKFLAGS = Split('''
            -bundle -flat_namespace -undefined suppress
            -framework Carbon -framework ApplicationServices
        '''))
        pdClass = pdClassEnvironment.Program(
            'csoundapi_tilde/csoundapi~.pd_darwin',
            'csoundapi_tilde/csoundapi_tilde.c')
    elif util.platform == 'linux':
        pdClass = pdClassEnvironment.SharedLibrary(
            'csoundapi_tilde/csoundapi~.pd_linux',
            'csoundapi_tilde/csoundapi_tilde.c',
            SHLIBPREFIX = '', SHLIBSUFFIX = '')
    elif util.platform == 'win32':
        pdClassEnvironment.Append(LIBS = ['pd'])
        pdClassEnvironment.Append(SHLINKFLAGS = ['-module'])
        pdClassEnvironment['ENV']['PATH'] = os.environ['PATH']
        pdClass = pdClassEnvironment.SharedLibrary(
            'csoundapi_tilde/csoundapi~',
            'csoundapi_tilde/csoundapi_tilde.c')

# Tclcsound
if commonEnvironment['buildTclcsound'] == '1':
    util.confDecision("Building Tclcsound frontend")
    # The header we don't care version
    if util.platform == "linux":
        tclIncludePath = Split('''
            /usr/include/tcl
            /usr/include/tcl8.5
            /usr/include/tcl8.4
            /usr/include/tk
            /usr/include/tk8.5
            /usr/include/tk8.4
        ''')
    elif util.platform == "darwin":
        tclIncludePath = Split('''
            /Library/Frameworks/Tcl.Framework/Headers
            /Library/Frameworks/Tk.Framework/Headers
            /System/Library/Frameworks/Tcl.Framework/Headers
            /System/Library/Frameworks/Tk.Framework/Headers
        ''')
    tclhfound = configure.CheckHeader('tcl.h', language ='C')
    for path in tclIncludePath:
        tclhfound = tclhfound or configure.CheckHeader('%s/tcl.h' % path,
            language ='C')

    if not tclhfound:
        util.fatal("You specified buildTclcsound but tcl.h was not found!")

    csTclEnvironment = commonEnvironment.Clone()
    csTclEnvironment.Append(CPPPATH = tclIncludePath)

    # Look for tcl and tk libs, try 8.5 first and then 8.4
    tcllibfound = False
    tklibfound = False
    if util.platform == "linux" or util.platform == "win32":
        for version in ['8.5', '85', '8.4', '84']:
            tcllibfound = tcllibfound or configure.CheckLib("tcl%s" % version,
                    autoadd=0)
            tklibfound = tklibfound or configure.CheckLib("tk%s" % version,
                    autoadd=0)
            if tcllibfound and tklibfound:
                csTclEnvironment.Append(LIBS =
                        ['tcl%s' % version, 'tk%s' % version])
                break
    elif util.platform == "darwin":
        csTclEnvironment.Append(LINKFLAGS = Split(
            '-framework tk -framework tcl'))

    if util.platform == 'win32':
        csTclEnvironment.Append(SHLINKFLAGS = ['-module'])

    csTclCmdObj     = csTclEnvironment.SharedObject('tclcsound/commands.c')
    csTcl           = csTclEnvironment.Program(
        'tclcsound/cstclsh', ['tclcsound/main_tclsh.c', csTclCmdObj])
    csTk            = csTclEnvironment.Program(
        'tclcsound/cswish', ['tclcsound/main_wish.c', csTclCmdObj])
    Tclcsoundlib    = csTclEnvironment.SharedLibrary(
        'tclcsound/tclcsound', ['tclcsound/tclcsound.c', csTclCmdObj],
        SHLIBPREFIX = '')
    if util.platform == 'darwin':
        tmp = "/Developer/Tools/Rez -i APPL -o cswish frontends/tclcsound/cswish.r"
        csTclEnvironment.Command('cswish_resources', 'cswish', tmp)
        if commonEnvironment['dynamicCsoundLibrary'] == '1':
            tmp  = 'mkdir /Library/Frameworks/CsoundLib.framework/Resources/TclTk'
            tmp += '; cp -R tclcsound.dylib /Library/Frameworks/CsoundLib.framework/Resources/TclTk/'
            csTclEnvironment.Command('tclcsound_install', 'tclcsound.dylib',
                                    tmp)
#    try     : os.mkdir('tclcsound', 0755)
#    except  : pass
#    if util.platform == 'darwin':
#      csTclEnvironment.Command('tclcsound/pkgIndex.tcl', 'tclcsound.dylib','cp tclcsound.dylib tclcsound; tclsh pkgbuild.tcl')
#    elif util.platform == 'linux':
#      csTclEnvironment.Command('tclcsound/pkgIndex.tcl', 'tclcsound.so','cp tclcsound.so tclcsound; tclsh pkgbuild.tcl')
#    elif  util.platform == 'win32':
#      csTclEnvironment.Command('tclcsound/tclcsound.dll', 'tclcsound.dll','cp tclcsound.dll tclcsound')
#      csTclEnvironment.Command('tclcsound/pkgIndex.tcl', 'tclcsound/tclcsound.dll','tclsh84 pkgbuild.tcl')

else:
    util.confDecision("Not building Tclcsound")
