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

# Copyright (c) 2002, 2003 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 QApplication, QTranslator, QTextCodec, QPixmap, QPoint, \
    QLabel, Qt, QFrame, QRect, QPainter, QFont, SIGNAL, SLOT

from UI.Info import Program, Version
import Preferences

def showSplash():
    """
    Global function to show a nice splash screen.
    """
    screen = QApplication.desktop().screenGeometry()
    ericPic = QPixmap(os.path.join(ericDir, 'pixmaps', 'eric.png'))
    eric = QLabel(None, "splash", 
        Qt.WDestructiveClose | Qt.WStyle_Customize | Qt.WStyle_NoBorder |\
        Qt.WX11BypassWM | Qt.WStyle_StaysOnTop)
    eric.setFrameStyle(QFrame.WinPanel | QFrame.Raised)
    eric.setPixmap(ericPic)
    eric.adjustSize()
    eric.setCaption(Program)
    eric.move(QPoint(screen.center().x() - eric.width()/2, 
                     screen.center().y() - eric.height()/2))
    eric.show()
    eric.repaint(0)
    QApplication.flush()

    return eric

def loadTranslator(dirs, tn):
    """
    Global function to find and load a specific translation.

    Arguments
    
        dirs -- searchpath for the translations (list of strings)
        
        tn -- the translation to be loaded (string)
        
    Returns
    
        tuple of a status flag and the loaded translator (int, QTranslator)
    """
    trans = QTranslator(None)
    for dir in dirs:
        loaded = trans.load(tn, dir)
        if loaded:
            return (trans, 1)
            
    print "eric: no translation file '" + tn + "'found."
    print "Using default."
    return (None, 0)

if __name__ == '__main__':
    ericDir = os.path.dirname(sys.argv[0])
    if ericDir == '':
        ericDir = '.'
    app = QApplication(sys.argv)

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

    # 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:]
    
    # We can only import these after creating the QApplication because they
    # make Qt calls that need the QApplication to exist.
    from UI.UserInterface import UserInterface

    # 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
    
    # Load translation files and install them
    loaded = 0
    loc = Preferences.getUILanguage()
    if loc is not None:
        if loc == "System":
            loc = str(QTextCodec.locale())
        
        if loc != "C":
            # setup the searchpath for qt and qscintilla
            dirs = [ericDir, "."]
            if qtdir is not None:
                dirs.insert(-1, os.path.join(qtdir, "translations"))
                
            # 1) load translations for qt
            qtTrans, ok = loadTranslator(dirs, "qt_" + loc)
            if ok:
                app.installTranslator(qtTrans)
                
            # 2) load translations for qscintilla
            scintillaTrans, ok = loadTranslator(dirs, "qscintilla_" + loc)
            if ok:
                app.installTranslator(scintillaTrans)
                
            # 3) load translations for eric
            dirs = [".", ericDir]
            ericTrans, ok = loadTranslator(dirs, "eric3_" + loc)
            if ok:
                app.installTranslator(ericTrans)
            else:
                print "Please report to <eric-bugs@die-offenbachs.de>."
        else:
            loc = None
        
    mw = UserInterface(loc)
    app.setMainWidget(mw)
    app.connect(app, SIGNAL("lastWindowClosed()"), app, SLOT("quit()"))
    mw.show()

    if splash:
        del splash
        
    mw.processArgs(args)
    
    app.exec_loop()
    sys.exit(0)
