# GNU Enterprise Forms - QT UI Driver - User Interface
#
# Copyright 2001-2009 Free Software Foundation
#
# This file is part of GNU Enterprise
#
# GNU Enterprise is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation; either
# version 3, or (at your option) any later version.
#
# GNU Enterprise is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied
# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
# PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public
# License along with program; see the file COPYING. If not,
# write to the Free Software Foundation, Inc., 59 Temple Place
# - Suite 330, Boston, MA 02111-1307, USA.
#
# $Id: UIdriver.py 9956 2009-10-11 18:54:57Z reinhard $
"""
A pyQT based user interface driver for GNUe forms.
"""

import os.path

from gnue.forms.uidrivers._base import Exceptions
from gnue.forms.uidrivers._base.UIdriver import GFUserInterfaceBase

try:
    import qt

except ImportError:
    raise Exceptions.DriverNotSupported, \
            u_("The GNUe-Forms QT3 driver requires PyQT.")

from gnue.common.apps import GConfig
from gnue.forms.uidrivers.qt3.QTApp import *
from gnue.forms.uidrivers.qt3 import dialogs


# =============================================================================
# Splash Screen
# =============================================================================

class UISplashScreen(qt.QMainWindow):
    """
    Splash screen window
    """

    # -------------------------------------------------------------------------
    # Constructor
    # -------------------------------------------------------------------------

    def __init__(self):

        qt.QMainWindow.__init__(self, None, 'GNUeSplash', qt.Qt.WStyle_Splash |
                qt.Qt.WStyle_StaysOnTop)

        idir = GConfig.getInstalledBase('forms_images', 'common_images')
        picture = gConfigForms ('splashScreenPNG')
        if not os.path.isabs(picture):
            picture = os.path.join (idir, picture)

        image = qt.QLabel('', self)
        image.setPixmap(qt.QPixmap(picture))

        self.setCentralWidget(image)
        self.show()
        getQtApp().processEvents()



# =============================================================================
# This class implements the User Interface for QT3
# =============================================================================

class GFUserInterface(GFUserInterfaceBase):

    __rearrange_boxes__ = True

    # -------------------------------------------------------------------------
    # Constructor
    # -------------------------------------------------------------------------

    def __init__(self, eventHandler, name="Undefined", disableSplash=None,
            parentContainer=None, moduleName=None):

        GFUserInterfaceBase.__init__(self, eventHandler, name,
                              disableSplash, parentContainer, moduleName)
        self.__splash = None

        # We don't need these values for this ui driver
        self.textWidth = self.widgetWidth = -1
        self.textHeight = self.widgetHeight = -1

        self.name = "QT3"

        self._qtapp = getQtApp()

        if not self._disableSplash:
            self.__splash = UISplashScreen()
        else:
            self.__splash = None

        self.__cell_size()



    # -------------------------------------------------------------------------
    # Start the application's main loop
    # -------------------------------------------------------------------------

    def mainLoop(self):
        """
        Start the main loop of the current application instance
        """

        assert gEnter(6)

        self._qtapp.start()

        assert gLeave(6)


    # -------------------------------------------------------------------------
    # Hide splash screen
    # -------------------------------------------------------------------------

    def hide_splash(self):
        """
        Hide the splash screen (if available)
        """

        if self.__splash:
            try:
                self.__splash.close()
                self._qtapp.processEvents()
            finally:
                self.__splash = None


    # -------------------------------------------------------------------------
    # Show a simple error message
    # -------------------------------------------------------------------------

    def _ui_show_error_(self, message):

        self.hide_splash()
        qt.QMessageBox.critical(None, "GNU Enterprise", message)


    # -------------------------------------------------------------------------
    # Show Exception dialog
    # -------------------------------------------------------------------------

    def _ui_show_exception_(self, group, name, message, detail):

        self.hide_splash()
        dlg = dialogs.ExceptionDialog(group, name, message, detail)
        dlg.exec_loop()

    # -------------------------------------------------------------------------
    # Create and run an input dialog
    # -------------------------------------------------------------------------

    def _getInput(self, title, fields, cancel=True):

        dlg = dialogs.InputDialog(title, fields, cancel)
        dlg.exec_loop()
        return dlg.inputData


    # -------------------------------------------------------------------------
    # Exit the application
    # -------------------------------------------------------------------------

    def _ui_exit_(self):

        assert gEnter(6)

        for child in self._children:
            child.main_window._closing_ = True
            child.main_window.close()

        assert gLeave(6)


    # -------------------------------------------------------------------------
    # Get the cell size for positioned layout
    # -------------------------------------------------------------------------

    def __cell_size(self):

        frame = qt.QMainWindow()
        result = {}

        lb = qt.QLabel('Sample', frame)
        tx = qt.QLineEdit(frame)
        dr = qt.QComboBox(True, frame)
        result['default'] = (tx.sizeHint().width(), tx.sizeHint().height())
        result['dropdown'] = (dr.sizeHint().width(), dr.sizeHint().height())
        result['label'] = (lb.sizeHint().width(), lb.sizeHint().height())

        text = "".join([chr(i) for i in range(48, 127)])
        self.cell_width = frame.fontMetrics().width(text) / len(text) + 1
        self.cell_height = max([i[1] for i in result.values()])

        bt = qt.QPushButton('Sample', frame)
        mt = qt.QTextEdit(frame)
        result['button'] = (bt.sizeHint().width(), bt.sizeHint().height())
        result['multiline'] = (mt.sizeHint().width(), mt.sizeHint().height())

        self.best_sizes = result
