#!/usr/bin/python
###########################################################################
# qtuicompiler - description                                              #
# ------------------------------                                          #
# begin     : Thu Apr 21 2005                                             #
# copyright : (C) 2005 by Simon Edwards                                   #
# email     : simon@simonzone.com                                         #
#                                                                         #
###########################################################################
#                                                                         #
#   This program is free software; you can redistribute it and/or modify  #
#   it under the terms of the GNU Library General Public License as       #
#   published by the Free Software Foundation; either version 2 of the    #
#   License, or (at your option) any later version.                       #
#                                                                         #
###########################################################################

import os
import sys
import pyqtconfig
from distutils.spawn import *
import traceback

pyqt_configuration = pyqtconfig.Configuration()
pyuic_exe = None

############################################################################
def FindPyuic():
    global pyuic_exe
    if pyuic_exe is not None: return pyuic_exe
    
    pyuic_exe = find_executable('pyuic',pyqt_configuration.pyqt_bin_dir)
    if pyuic_exe is None:
        # Search on the $Path.
        pyuic_exe = find_executable('pyuic')

############################################################################
def CompileUI(ui_file_name, py_file_name=None, kde=False):
    pyuic_exe = find_executable('pyuic',pyqt_configuration.default_bin_dir)
    if pyuic_exe is None:
        # Search on the $Path.
        pyuic_exe = find_executable('pyuic')
    if pyuic_exe is None:
        pass  # FIXME raise something!
        
    if py_file_name is None:
        py_file_name = os.path.splitext(os.path.basename(ui_file_name))[0] + '.py'
    
    tmp_file_name = py_file_name + '.bak'
    cmd = [pyuic_exe]
    if kde:
        cmd.append('-tr')
        cmd.append('i18n')
    cmd.append('-o')
    cmd.append(tmp_file_name)
    cmd.append(ui_file_name)
    spawn(cmd)
    
    input = open(tmp_file_name, 'r')
    output = open(py_file_name, 'w')
    for line in input.readlines():
        if kde and string.strip(line) == 'from qt import *':
            output.write(line)
            output.write('from kdecore import *\nfrom kdeui import *\n\n')
        elif kde and string.find(line, " = KDatePicker(") != -1:
            o = string.find(line, ",")
            output.write(line[:o] + ",QDate.currentDate()" + line[o:])
        else:
            output.write (line)

    input.close()
    output.close()

    os.remove(tmp_file_name)

############################################################################
def DynamicImport(importargs,kde=False):
    file_name = importargs[0].replace('.',os.sep)
    file_name_ui = file_name + '.ui'
    if os.path.exists(file_name_ui):
        try:
            UpdateUI(file_name_ui,kde)
        except:
            traceback.print_exc()
            raise ImportError, "Unable to compile Qt designer file %s." % args[0]

############################################################################
def UpdateUI(ui_file,kde=False):
    py_file = ui_file[:-3] + '.py'
    remake = False
    if os.path.exists(py_file):
        remake = os.stat(py_file).st_mtime <= os.stat(ui_file).st_mtime
    else:
        remake = True

    if remake:
        CompileUI(ui_file, py_file, kde)

############################################################################
def main():
    # FIXME parse args and add --kde parameter.
    if len(sys.argv)!=3:
        print """\nUsage:
qtuicompiler filename.ui filename.py\n\n
"""
        return

    CompileUI(sys.argv[1],sys.argv[2])
    
if __name__=='__main__':
    main()
