# Copyright (c) 2011-2014, B.I.Stepanov Institute of Physics, National Academy
# of Sciences of Belarus.
#
# This program 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 2 of the License, or (at your option) any later
# version.
#
# This program 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
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

"""Common startup code for GUI applications.

Import this module at the beginning of the top-level application script, then
create the main application widget, call 'runApplication' and do nothing
more."""

import StringIO
import sys
import traceback

from PyQt4.QtCore import *
from PyQt4.QtGui import *

# **** Private functions ******************************************************
def _excepthook(type, value, tracebackObj):
    """Exception handler that displays a message box showing the traceback."""

    # Still print the traceback to stderr.
    traceback.print_exception(type, value, tracebackObj, file = sys.stderr)
    # Display the same string in a message box.
    errorText = StringIO.StringIO()
    traceback.print_exception(type, value, tracebackObj, file = errorText)
    QMessageBox.critical(None, 'Unhandled exception', errorText.getvalue())

# **** Startup code ***********************************************************
# Replace the standard exception handler to make sure that exceptions won't
# slip away. Normally, exceptions do not cause PyQt applications to halt, being
# silently printed to the output window (which, moreover, may be hidden).
sys.excepthook = _excepthook

# Instantiate the application object.
_app = QApplication(sys.argv)

# Show the splash screen while the main application widget is initialized.
_splashScreen = QSplashScreen(
    QPixmap('code/media/images/institute-of-physics-splash.png'))
_splashScreen.showMessage('  Loading...',
    Qt.AlignHCenter | Qt.AlignBottom, Qt.white)
_splashScreen.show()

# **** Public functions *******************************************************
def runApplication(mainWidget):
    """Show 'mainWidget', close the splash screen and run the application event
    loop."""

    mainWidget.show()
    _splashScreen.finish(mainWidget)

    _app.exec_()
