#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Copyright (c) 2002 - 2006 Detlev Offenbach <detlev@die-offenbachs.de>
#

"""
Eric3 Python IDE

This is the main Python script that performs the neccessary initialization
of the IDE and starts the Qt event loop.
"""

import sys
import os
from qt import QTextCodec, SIGNAL, SLOT, qApp

# disable the usage of KDE widgets, if requested
# Note 1: Qt widgets might still be KDE widgets,
#         if Qt was compiled with Qt-KDE-Integration
# Note 2: This is an experimental feature of SUSE 9.3.
#         Disable it by setting the environment
#         variable "QT_NO_KDE_INTEGRATION=1"
if "--nokde" in sys.argv:
    del sys.argv[sys.argv.index("--nokde")]
    os.environ["e3nokde"] = "1"

from KdeQt.KQApplication import KQApplication

from UI.Info import Program, Version
from UI.SplashScreen import SplashScreen, NoneSplashScreen
from UI.E3SingleApplication import E3SingleApplicationClient
from Utilities import Startup
import Preferences


def handleSingleApplication(ddindex):
    """
    Global function to handle the single application mode.
    
    @param ddindex index of a '--' option in the options list
    """
    client = E3SingleApplicationClient()
    res = client.connect()
    if res > 0:
        if "--nosplash" in sys.argv and sys.argv.index("--nosplash") < ddindex:
            del sys.argv[sys.argv.index("--nosplash")]
        if "--nokde" in sys.argv and sys.argv.index("--nokde") < ddindex:
            del sys.argv[sys.argv.index("--nokde")]
        if len(sys.argv) > 1:
            client.processArgs(sys.argv[1:])
        sys.exit(0)
    elif res < 0:
        print "eric3: %s" % client.errstr()
        sys.exit(res)

def main():
    """
    Main entry point into the application.
    """
    options = [\
        ("--nosplash", "don't show the splash screen"),
        ("--nokde" , "don't use KDE widgets"),
        ("--", "indicate that there are options for the program to be debugged"),
        ("", "(everything after that is considered arguments for this program)")
    ]
    kqOptions = [\
        ("nosplash", "don't show the splash screen"),
        ("nokde" , "don't use KDE widgets"),
        ("!+file","")
    ]
    appinfo = Startup.makeAppInfo(sys.argv,
                                  "Eric3",
                                  "[project | files... [--] [debug-options]]",
                                  "A Python IDE",
                                  options)
    ddindex = Startup.handleArgs(sys.argv, appinfo)
    
    if Preferences.getUI("SingleApplicationMode"):
        handleSingleApplication(ddindex)
        
    app = KQApplication(sys.argv, kqOptions, )
    
    # set the searchpath for icons
    Startup.initializeMimeSourceFactory()

    # generate and show a splash window, if not suppressed
    if "--nosplash" in sys.argv and sys.argv.index("--nosplash") < ddindex:
        del sys.argv[sys.argv.index("--nosplash")]
        splash = NoneSplashScreen()
    else:
        splash = SplashScreen()

    # is there a set of filenames or options on the command line,
    # if so, pass them to the UI
    args = None
    if len(sys.argv) > 1:
        args = sys.argv[1:]
    
    # Set the applications string encoding
    try:
        sys.setappdefaultencoding(str(Preferences.getSystem("StringEncoding")))
    except:
        pass
    
    # get the Qt installation directory
    qtdir = Preferences.getQtDir()
    if qtdir is not None:
        if Preferences.getQt("ExportQtDir"):
            os.environ["QTDIR"] = qtdir
    # get the Qt4 installation directory
    qt4dir = Preferences.getQt4Dir()
    if qt4dir is not None:
        if Preferences.getQt("ExportQt4Dir"):
            os.environ["QT4DIR"] = qt4dir
    
    # Load translation files and install them
    loc = Startup.loadTranslators(qtdir, app, ("qscintilla",))
    
    QTextCodec.setCodecForCStrings(QTextCodec.codecForName(str(Preferences.getSystem("StringEncoding"))))
    
    splash.message(qApp.translate("eric3", "Importing packages..."))
    # We can only import these after creating the KQApplication because they
    # make Qt calls that need the KQApplication to exist.
    from UI.UserInterface import UserInterface

    splash.message(qApp.translate("eric3", "Generating Main Window..."))
    mw = UserInterface(loc, splash)
    app.setMainWidget(mw)
    app.connect(app, SIGNAL("lastWindowClosed()"), app, SLOT("quit()"))
    mw.show()
    
    if splash:
        del splash

    mw.processArgs(args)
        
    res = app.exec_loop()
    sys.exit(res)

if __name__ == '__main__':
    main()
