Beispiel #1
0
def create_splash_screen():
    """Create splash screen."""
    if not running_under_pytest():
        splash = QSplashScreen(QPixmap(get_image_path('splash')))
        splash_font = splash.font()
        splash_font.setPixelSize(14)
        splash.setFont(splash_font)
    else:
        splash = None

    return splash
Beispiel #2
0
def get_splash():
    from qtpy.QtCore import Qt
    from qtpy.QtWidgets import QApplication, QSplashScreen
    from qtpy.QtGui import QColor, QPixmap
    splash_pix = QPixmap(os.path.join(
        os.path.dirname(__file__), 'images', 'splash.png'))
    splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
    splash.show()
    splash.showMessage("Initializing...", Qt.AlignBottom | Qt.AlignCenter |
                       Qt.AlignAbsolute, QColor(Qt.white))
    QApplication.processEvents()
    return splash
Beispiel #3
0
def main() -> None:
    """Startup function."""
    global _app
    t0 = process_time()
    exit_code = 0
    from sys import argv, exit
    from logging import shutdown
    from platform import system
    from pyslvs_ui.info import ARGUMENTS, logger
    if ARGUMENTS.cmd in {'gui', None}:
        from qtpy.QtCore import Qt, qInstallMessageHandler
        from qtpy.QtWidgets import QApplication, QSplashScreen
        from qtpy.QtGui import QPixmap
        _app = QApplication(argv)
        # Depress Qt warning
        qInstallMessageHandler(lambda _0, _1, _2: None)
        # Load QRC file
        from pyslvs_ui.icons_rc import qInitResources
        qInitResources()
        # Splash
        sp = QSplashScreen(QPixmap(":/icons/splash.png"))
        sp.showMessage(f"{__author__} {__copyright__}",
                       Qt.AlignBottom | Qt.AlignRight)
        sp.show()
        # Force enable fusion style on macOS
        if system() == 'Darwin':
            ARGUMENTS.fusion = True
        if ARGUMENTS.fusion:
            _app.setStyle('fusion')
        # Main window
        from .main_window import MainWindow
        w = MainWindow.new()
        sp.finish(w)
        sp.deleteLater()
        logger.info(f"Startup with: {process_time() - t0:.02f}s")
        if not ARGUMENTS.debug_mode:
            w.console_connect()
        del sp, w
        exit_code = _app.exec_()
    elif ARGUMENTS.cmd == 'test':
        from importlib import import_module
        import_module('pyslvs_ui.main_window')
        logger.info("All module loaded successfully.")
        logger.info(f"Loaded with: {process_time() - t0:.02f}s")
    elif ARGUMENTS.cmd == 'extract':
        logger.info(f"Start CLI: {process_time() - t0:.02f}s")
        # TODO: CLI mode
    else:
        raise ValueError(f"unknown command: {ARGUMENTS.cmd}")
    shutdown()
    exit(exit_code)
Beispiel #4
0
def run(args=[],
        files=[],
        datasets=[],
        flags=(False, False, False, False, False, False, False),
        ppath=None,
        query=None):
    hidecontrol = False
    if flags[4]:
        from CGNS.NAV.wquery import Q7Query
        Q7Query.loadUserQueries()
        Q7Query.fillQueries()
        ql = Q7Query.queriesNamesList()
        print('# CGNS.NAV available queries:')
        for q in ql:
            print(' ', q)
    else:
        app = QApplication(args)
        if not flags[5]:
            pixmap = QPixmap(":/images/splash.png")
            splash = QSplashScreen(pixmap, Qt.WindowStaysOnTopHint)
            splash.show()
            splash.showMessage("Release v%s" % OCTXT._ToolVersion,
                               Qt.AlignHCenter | Qt.AlignBottom)
        app.processEvents()
        t1 = time.time()
        Q7Main.verbose = flags[2]
        wcontrol = Q7Main()
        wcontrol._application = app
        wcontrol.setOptionValue('NAVTrace', flags[2])
        wcontrol.transientRecurse = flags[0]
        wcontrol.transientVTK = flags[3]
        wcontrol.query = query
        wcontrol._T('start')
        wcontrol.setDefaults()
        if flags[1]:
            wcontrol.loadlast()
            hidecontrol = flags[6]
        if files:
            for ff in files:
                wcontrol.loadfile(ff)
            hidecontrol = flags[6]
        if datasets:
            for dd in datasets:
                wcontrol.loadCompleted(dataset_name='FFFF',
                                       dataset_base='BASE',
                                       dataset_tree=dd,
                                       dataset_references=[],
                                       dataset_paths=[])
            hidecontrol = flags[6]
        wcontrol.show()
        if hidecontrol:
            wcontrol.hide()
        if not flags[5]:
            t2 = time.time()
            if t2 - t1 < 2.0:
                time.sleep(2)
            splash.finish(wcontrol)
        app.exec_()
        wcontrol._T('leave')
    sys.exit()
Beispiel #5
0
    def __init__(self):
        super(Restarter, self).__init__()
        self.ellipsis = ['', '.', '..', '...', '..', '.']

        # Widgets
        self.timer_ellipsis = QTimer(self)
        self.splash = QSplashScreen(QPixmap(get_image_path('splash'), 'svg'))

        # Widget setup
        self.setVisible(False)

        font = self.splash.font()
        font.setPixelSize(10)
        self.splash.setFont(font)
        self.splash.show()

        self.timer_ellipsis.timeout.connect(self.animate_ellipsis)
Beispiel #6
0
def main() -> None:
    """Startup function."""
    global _app
    from time import perf_counter
    t0 = perf_counter()

    from sys import argv, exit
    from logging import shutdown
    from platform import system
    from qtpy.QtCore import Qt
    from qtpy.QtWidgets import QApplication, QSplashScreen
    from qtpy.QtGui import QPixmap
    from .core.info import ARGUMENTS, logger
    if ARGUMENTS.test:
        from importlib import import_module
        import_module('pyslvs_ui.core.main_window')
        logger.info("All module loaded successfully.")
        logger.info(f"Loaded with: {perf_counter() - t0:.02f}s")
        shutdown()
        exit(0)

    _app = QApplication(argv)
    splash = QSplashScreen(QPixmap(":/icons/splash.png"))
    splash.showMessage(f"{__author__} {__copyright__}",
                       Qt.AlignBottom | Qt.AlignRight)
    splash.show()

    # Force enable fusion style on macOS
    if system() == 'Darwin':
        ARGUMENTS.fusion = True
    if ARGUMENTS.fusion:
        _app.setStyle('fusion')

    from .core.main_window import MainWindow
    w = MainWindow()
    w.show()
    splash.finish(w)
    splash.deleteLater()
    logger.info(f"Startup with: {perf_counter() - t0:.02f}s")
    if not ARGUMENTS.debug_mode:
        w.console_connect()
    del splash, t0

    qt_exit_code = _app.exec_()
    shutdown()
    exit(qt_exit_code)
Beispiel #7
0
    def __init__(self, version_string="Version string"):
        QSplashScreen.__init__(self)
        self.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.SplashScreen)

        splash_width = 720
        splash_height = 400

        desktop = QApplication.desktop()
        screen = desktop.screenGeometry(desktop.primaryScreen()).size()

        screen_width, screen_height = screen.width(), screen.height()
        x = screen_width // 2 - splash_width // 2
        y = screen_height // 2 - splash_height // 2
        self.setGeometry(x, y, splash_width, splash_height)

        self.ert = "ERT"
        self.ert_title = "Ensemble based Reservoir Tool"
        self.version = version_string
        self.timestamp = "Timestamp string"
Beispiel #8
0
def main() -> None:
    """Startup function."""
    global _app
    t0 = process_time()
    from qtpy.QtCore import Qt, QDir, QLockFile
    from qtpy.QtWidgets import QApplication, QSplashScreen
    from qtpy.QtGui import QPixmap
    from .info import ARGUMENTS, logger
    if ARGUMENTS.test:
        from importlib import import_module
        import_module('pyslvs_ui.main_window')
        logger.info("All module loaded successfully.")
        logger.info(f"Loaded with: {process_time() - t0:.02f}s")
        shutdown()
        exit(0)

    _app = QApplication(argv)
    lf = QLockFile(join(QDir.tempPath(), "pyslvs.lock"))
    if not lf.tryLock(100):
        logger.info("Pyslvs can only start one instance.")
        shutdown()
        exit(0)
    sp = QSplashScreen(QPixmap(":/icons/splash.png"))
    sp.showMessage(f"{__author__} {__copyright__}",
                   Qt.AlignBottom | Qt.AlignRight)
    sp.show()

    # Force enable fusion style on macOS
    if system() == 'Darwin':
        ARGUMENTS.fusion = True
    if ARGUMENTS.fusion:
        _app.setStyle('fusion')

    from .main_window import MainWindow
    sp.finish(MainWindow.new())
    sp.deleteLater()
    del sp
    logger.info(f"Startup with: {process_time() - t0:.02f}s")
    qt_exit_code = _app.exec_()
    del lf
    shutdown()
    exit(qt_exit_code)
Beispiel #9
0
def create_splash_screen():
    """Create splash screen."""
    if not running_under_pytest():
        image = QImage(500, 400, QImage.Format_ARGB32_Premultiplied)
        image.fill(0)
        painter = QPainter(image)
        renderer = QSvgRenderer(get_image_path('splash'))
        renderer.render(painter)
        painter.end()

        pm = QPixmap.fromImage(image)
        pm = pm.copy(0, 0, 500, 400)

        splash = QSplashScreen(pm)
        splash_font = splash.font()
        splash_font.setPixelSize(14)
        splash.setFont(splash_font)
    else:
        splash = None

    return splash
Beispiel #10
0
def gui_qt(*, startup_logo=False):
    """Start a Qt event loop in which to run the application.

    Parameters
    ----------
    startup_logo : bool
        Show a splash screen with the napari logo during startup.

    Notes
    -----
    This context manager is not needed if running napari within an interactive
    IPython session. In this case, use the ``%gui qt`` magic command, or start
    IPython with the Qt GUI event loop enabled by default by using
    ``ipython --gui=qt``.
    """
    splash_widget = None
    app = QApplication.instance()
    if not app:
        # if this is the first time the Qt app is being instantiated, we set
        # the name, so that we know whether to raise_ in Window.show()
        app = QApplication(sys.argv)
        app.setApplicationName('napari')
        if startup_logo:
            logopath = join(dirname(__file__), '..', 'resources', 'logo.png')
            splash_widget = QSplashScreen(QPixmap(logopath).scaled(400, 400))
            splash_widget.show()
    yield app
    # if the application already existed before this function was called,
    # there's no need to start it again.  By avoiding unnecessary calls to
    # ``app.exec_``, we avoid blocking.
    if app.applicationName() == 'napari':
        if splash_widget and startup_logo:
            splash_widget.close()
        app.exec_()
Beispiel #11
0
def gui_qt(*, startup_logo=False, gui_exceptions=False):
    """Start a Qt event loop in which to run the application.

    Parameters
    ----------
    startup_logo : bool, optional
        Show a splash screen with the napari logo during startup.
    gui_exceptions : bool, optional
        Whether to show uncaught exceptions in the GUI, by default they will be
        shown in the console that launched the event loop.

    Notes
    -----
    This context manager is not needed if running napari within an interactive
    IPython session. In this case, use the ``%gui qt`` magic command, or start
    IPython with the Qt GUI event loop enabled by default by using
    ``ipython --gui=qt``.
    """
    splash_widget = None
    app = QApplication.instance()
    if not app:
        # automatically determine monitor DPI.
        # Note: this MUST be set before the QApplication is instantiated
        QApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
        # if this is the first time the Qt app is being instantiated, we set
        # the name, so that we know whether to raise_ in Window.show()
        app = _create_application(sys.argv)
        app.setApplicationName('napari')
        if startup_logo:
            logopath = join(dirname(__file__), '..', 'resources', 'logo.png')
            pm = QPixmap(logopath).scaled(360, 360, Qt.KeepAspectRatio,
                                          Qt.SmoothTransformation)
            splash_widget = QSplashScreen(pm)
            splash_widget.show()
            app._splash_widget = splash_widget
    else:
        app._existed = True

    # instantiate the exception handler
    exception_handler = ExceptionHandler(gui_exceptions=gui_exceptions)
    sys.excepthook = exception_handler.handle

    try:
        yield app
    except Exception:
        exception_handler.handle(*sys.exc_info())

    # if the application already existed before this function was called,
    # there's no need to start it again.  By avoiding unnecessary calls to
    # ``app.exec_``, we avoid blocking.
    # see also https://github.com/napari/napari/pull/2016
    # we add 'magicgui' so that anyone using @magicgui *before* calling gui_qt
    # will also have the application executed. (a bandaid for now?...)
    if app.applicationName() in ('napari', 'magicgui'):
        if splash_widget and startup_logo:
            splash_widget.close()
        app.exec_()
Beispiel #12
0
    def __init__(self):
        super(Restarter, self).__init__()
        self.ellipsis = ['', '.', '..', '...', '..', '.']

        # Widgets
        self.timer_ellipsis = QTimer(self)
        self.splash = QSplashScreen(QPixmap(get_image_path('splash.svg'),
                                    'svg'))

        # Widget setup
        self.setVisible(False)

        font = self.splash.font()
        font.setPixelSize(10)
        self.splash.setFont(font)
        self.splash.show()

        self.timer_ellipsis.timeout.connect(self.animate_ellipsis)
Beispiel #13
0
def get_splash():
    from qtpy.QtCore import Qt
    from qtpy.QtWidgets import QApplication, QSplashScreen
    from qtpy.QtGui import QColor, QPixmap
    splash_pix = QPixmap(
        os.path.join(os.path.dirname(__file__), 'images', 'splash.png'))
    splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
    splash.show()
    splash.showMessage("Initializing...",
                       Qt.AlignBottom | Qt.AlignCenter | Qt.AlignAbsolute,
                       QColor(Qt.white))
    QApplication.processEvents()
    return splash
Beispiel #14
0
def gui_qt(*, startup_logo=False, gui_exceptions=False, force=False):
    """Start a Qt event loop in which to run the application.

    Parameters
    ----------
    startup_logo : bool, optional
        Show a splash screen with the napari logo during startup.
    gui_exceptions : bool, optional
        Whether to show uncaught exceptions in the GUI, by default they will be
        shown in the console that launched the event loop.
    force : bool, optional
        Force the application event_loop to start, even if there are no top
        level widgets to show.

    Notes
    -----
    This context manager is not needed if running napari within an interactive
    IPython session. In this case, use the ``%gui qt`` magic command, or start
    IPython with the Qt GUI event loop enabled by default by using
    ``ipython --gui=qt``.
    """
    splash_widget = None

    app = get_app()
    if startup_logo and app.applicationName() == 'napari':
        pm = QPixmap(NAPARI_ICON_PATH).scaled(360, 360, Qt.KeepAspectRatio,
                                              Qt.SmoothTransformation)
        splash_widget = QSplashScreen(pm)
        splash_widget.show()
        app._splash_widget = splash_widget

    # instantiate the exception handler
    exception_handler = ExceptionHandler(gui_exceptions=gui_exceptions)
    sys.excepthook = exception_handler.handle

    try:
        yield app
    except Exception:
        exception_handler.handle(*sys.exc_info())

    # if the application already existed before this function was called,
    # there's no need to start it again.  By avoiding unnecessary calls to
    # ``app.exec_``, we avoid blocking.
    # we add 'magicgui' so that anyone using @magicgui *before* calling gui_qt
    # will also have the application executed. (a bandaid for now?...)
    # see https://github.com/napari/napari/pull/2016
    if app.applicationName() in ('napari', 'magicgui'):
        if splash_widget and startup_logo:
            splash_widget.close()
        run(force=force, _func_name='gui_qt')
Beispiel #15
0
def gui_qt(*, startup_logo=False):
    """Start a Qt event loop in which to run the application.

    Parameters
    ----------
    startup_logo : bool
        Show a splash screen with the napari logo during startup.

    Notes
    -----
    This context manager is not needed if running napari within an interactive
    IPython session. In this case, use the ``%gui qt`` magic command, or start
    IPython with the Qt GUI event loop enabled by default by using
    ``ipython --gui=qt``.
    """
    splash_widget = None
    app = QApplication.instance()
    if not app:
        # automatically determine monitor DPI.
        # Note: this MUST be set before the QApplication is instantiated
        QApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
        # if this is the first time the Qt app is being instantiated, we set
        # the name, so that we know whether to raise_ in Window.show()
        app = _create_application(sys.argv)
        app.setApplicationName('napari')
        if startup_logo:
            logopath = join(dirname(__file__), '..', 'resources', 'logo.png')
            pm = QPixmap(logopath).scaled(360, 360, Qt.KeepAspectRatio,
                                          Qt.SmoothTransformation)
            splash_widget = QSplashScreen(pm)
            splash_widget.show()
            app._splash_widget = splash_widget
    else:
        app._existed = True

    # instantiate the exception handler
    exception_handler = ExceptionHandler()
    sys.excepthook = exception_handler.handle

    yield app
    # if the application already existed before this function was called,
    # there's no need to start it again.  By avoiding unnecessary calls to
    # ``app.exec_``, we avoid blocking.
    if app.applicationName() == 'napari':
        if splash_widget and startup_logo:
            splash_widget.close()
        app.exec_()
Beispiel #16
0
def gui_qt(*, startup_logo=False):
    """Start a Qt event loop in which to run the application.

    Parameters
    ----------
    startup_logo : bool
        Show a splash screen with the napari logo during startup.

    Notes
    -----
    This context manager is not needed if running napari within an interactive
    IPython session. In this case, use the ``%gui qt`` magic command, or start
    IPython with the Qt GUI event loop enabled by default by using
    ``ipython --gui=qt``.
    """
    app = QApplication.instance() or QApplication(sys.argv)
    if startup_logo:
        logopath = join(dirname(__file__), '..', 'resources', 'logo.png')
        splash_widget = QSplashScreen(QPixmap(logopath).scaled(400, 400))
        splash_widget.show()
    yield
    if startup_logo:
        splash_widget.close()
    app.exec_()
Beispiel #17
0
class Restarter(QWidget):
    """Widget in charge of displaying the splash information screen and the
       error messages.
    """
    def __init__(self):
        super(Restarter, self).__init__()
        self.ellipsis = ['', '.', '..', '...', '..', '.']

        # Widgets
        self.timer_ellipsis = QTimer(self)
        self.splash = QSplashScreen(QPixmap(get_image_path('splash.svg'),
                                    'svg'))

        # Widget setup
        self.setVisible(False)

        font = self.splash.font()
        font.setPixelSize(10)
        self.splash.setFont(font)
        self.splash.show()

        self.timer_ellipsis.timeout.connect(self.animate_ellipsis)

    def _show_message(self, text):
        """Show message on splash screen."""
        self.splash.showMessage(text, Qt.AlignBottom | Qt.AlignCenter |
                                Qt.AlignAbsolute, QColor(Qt.white))

    def animate_ellipsis(self):
        """Animate dots at the end of the splash screen message."""
        ellipsis = self.ellipsis.pop(0)
        text = ' '*len(ellipsis) + self.splash_text + ellipsis
        self.ellipsis.append(ellipsis)
        self._show_message(text)

    def set_splash_message(self, text):
        """Sets the text in the bottom of the Splash screen."""
        self.splash_text = text
        self._show_message(text)
        self.timer_ellipsis.start(500)

    def launch_error_message(self, error_type, error=None):
        """Launch a message box with a predefined error message.

        Parameters
        ----------
        error_type : int [CLOSE_ERROR, RESET_ERROR, RESTART_ERROR]
            Possible error codes when restarting/reseting spyder.
        error : Exception
            Actual Python exception error caught.
        """
        messages = {CLOSE_ERROR: _("It was not possible to close the previous "
                                   "Spyder instance.\nRestart aborted."),
                    RESET_ERROR: _("Spyder could not reset to factory "
                                   "defaults.\nRestart aborted."),
                    RESTART_ERROR: _("It was not possible to restart Spyder.\n"
                                     "Operation aborted.")}
        titles = {CLOSE_ERROR: _("Spyder exit error"),
                  RESET_ERROR: _("Spyder reset error"),
                  RESTART_ERROR: _("Spyder restart error")}

        if error:
            e = error.__repr__()
            message = messages[error_type] + "\n\n{0}".format(e)
        else:
            message = messages[error_type]

        title = titles[error_type]
        self.splash.hide()
        QMessageBox.warning(self, title, message, QMessageBox.Ok)
        raise RuntimeError(message)
Beispiel #18
0
class Restarter(QWidget):
    """Widget in charge of displaying the splash information screen and the
       error messages.
    """
    def __init__(self):
        super(Restarter, self).__init__()
        self.ellipsis = ['', '.', '..', '...', '..', '.']

        # Widgets
        self.timer_ellipsis = QTimer(self)
        self.splash = QSplashScreen(
            QPixmap(get_image_path('splash.svg'), 'svg'))

        # Widget setup
        self.setVisible(False)

        font = self.splash.font()
        font.setPixelSize(10)
        self.splash.setFont(font)
        self.splash.show()

        self.timer_ellipsis.timeout.connect(self.animate_ellipsis)

    def _show_message(self, text):
        """Show message on splash screen."""
        self.splash.showMessage(
            text, int(Qt.AlignBottom | Qt.AlignCenter | Qt.AlignAbsolute),
            QColor(Qt.white))

    def animate_ellipsis(self):
        """Animate dots at the end of the splash screen message."""
        ellipsis = self.ellipsis.pop(0)
        text = ' ' * len(ellipsis) + self.splash_text + ellipsis
        self.ellipsis.append(ellipsis)
        self._show_message(text)

    def set_splash_message(self, text):
        """Sets the text in the bottom of the Splash screen."""
        self.splash_text = text
        self._show_message(text)
        self.timer_ellipsis.start(500)

    def launch_error_message(self, error_type, error=None):
        """Launch a message box with a predefined error message.

        Parameters
        ----------
        error_type : int [CLOSE_ERROR, RESET_ERROR, RESTART_ERROR]
            Possible error codes when restarting/reseting spyder.
        error : Exception
            Actual Python exception error caught.
        """
        messages = {
            CLOSE_ERROR:
            _("It was not possible to close the previous "
              "Spyder instance.\nRestart aborted."),
            RESET_ERROR:
            _("Spyder could not reset to factory "
              "defaults.\nRestart aborted."),
            RESTART_ERROR:
            _("It was not possible to restart Spyder.\n"
              "Operation aborted.")
        }
        titles = {
            CLOSE_ERROR: _("Spyder exit error"),
            RESET_ERROR: _("Spyder reset error"),
            RESTART_ERROR: _("Spyder restart error")
        }

        if error:
            e = error.__repr__()
            message = messages[error_type] + "\n\n{0}".format(e)
        else:
            message = messages[error_type]

        title = titles[error_type]
        self.splash.hide()
        QMessageBox.warning(self, title, message, QMessageBox.Ok)
        raise RuntimeError(message)
Beispiel #19
0
# -----------------------------------------------------------------------------

atexit.register(qCleanupResources)


def _get_splash_image_name():
    # gets the width of the screen where the main window was initialised
    width = QGuiApplication.primaryScreen().size().width()

    if width > 2048:
        return ':/images/MantidSplashScreen_4k.jpg'
    else:
        return ':/images/MantidSplashScreen.png'


SPLASH = QSplashScreen(QPixmap(_get_splash_image_name()),
                       Qt.WindowStaysOnTopHint)
SPLASH.show()
SPLASH.showMessage("Starting...", Qt.AlignBottom | Qt.AlignLeft
                   | Qt.AlignAbsolute, QColor(Qt.black))
# The event loop has not started - force event processing
QApplication.processEvents(QEventLoop.AllEvents)

# -----------------------------------------------------------------------------
# MainWindow
# -----------------------------------------------------------------------------


class MainWindow(QMainWindow):
    DOCKOPTIONS = QMainWindow.AllowTabbedDocks | QMainWindow.AllowNestedDocks

    def __init__(self):
Beispiel #20
0
def _init_mne_qtapp(enable_icon=True, pg_app=False, splash=False):
    """Get QApplication-instance for MNE-Python.

    Parameter
    ---------
    enable_icon: bool
        If to set an MNE-icon for the app.
    pg_app: bool
        If to create the QApplication with pyqtgraph. For an until know
        undiscovered reason the pyqtgraph-browser won't show without
        mkQApp from pyqtgraph.
    splash : bool | str
        If not False, display a splash screen. If str, set the message
        to the given string.

    Returns
    -------
    app : ``qtpy.QtWidgets.QApplication``
        Instance of QApplication.
    splash : ``qtpy.QtWidgets.QSplashScreen``
        Instance of QSplashScreen. Only returned if splash is True or a
        string.
    """
    from qtpy.QtCore import Qt
    from qtpy.QtGui import QIcon, QPixmap, QGuiApplication
    from qtpy.QtWidgets import QApplication, QSplashScreen
    app_name = 'MNE-Python'
    organization_name = 'MNE'

    # Fix from cbrnr/mnelab for app name in menu bar
    # This has to come *before* the creation of the QApplication to work.
    # It also only affects the title bar, not the application dock.
    # There seems to be no way to change the application dock from "python"
    # at runtime.
    if sys.platform.startswith("darwin"):
        try:
            # set bundle name on macOS (app name shown in the menu bar)
            from Foundation import NSBundle
            bundle = NSBundle.mainBundle()
            info = bundle.localizedInfoDictionary() or bundle.infoDictionary()
            info["CFBundleName"] = app_name
        except ModuleNotFoundError:
            pass

    if pg_app:
        from pyqtgraph import mkQApp
        app = mkQApp(app_name)
    else:
        app = QApplication.instance() or QApplication(sys.argv or [app_name])
        app.setApplicationName(app_name)
    app.setOrganizationName(organization_name)

    if enable_icon or splash:
        icons_path = _qt_init_icons()

    if enable_icon:
        # Set icon
        kind = 'bigsur_' if platform.mac_ver()[0] >= '10.16' else 'default_'
        app.setWindowIcon(QIcon(f"{icons_path}/mne_{kind}icon.png"))

    out = app
    if splash:
        pixmap = QPixmap(f"{icons_path}/mne_splash.png")
        pixmap.setDevicePixelRatio(
            QGuiApplication.primaryScreen().devicePixelRatio())
        qsplash = QSplashScreen(pixmap, Qt.WindowStaysOnTopHint)
        qsplash.setAttribute(Qt.WA_ShowWithoutActivating, True)
        if isinstance(splash, str):
            alignment = int(Qt.AlignBottom | Qt.AlignHCenter)
            qsplash.showMessage(
                splash, alignment=alignment, color=Qt.white)
        qsplash.show()
        app.processEvents()
        out = (out, qsplash)

    return out
Beispiel #21
0
        # not calling app.setApplicationVersion(mantid.kernel.version_str())
        # because it needs to happen after logging is monkey-patched in
    return app


# Create the application object early
MAIN_APP = qapplication()

# -----------------------------------------------------------------------------
# Splash screen
# -----------------------------------------------------------------------------
# Importing resources loads the data in
from workbench.app.resources import qCleanupResources  # noqa
atexit.register(qCleanupResources)

SPLASH = QSplashScreen(QPixmap(':/images/MantidSplashScreen.png'),
                       Qt.WindowStaysOnTopHint)
SPLASH.show()
SPLASH.showMessage("Starting...",
                   Qt.AlignBottom | Qt.AlignLeft | Qt.AlignAbsolute,
                   QColor(Qt.black))
# The event loop has not started - force event processing
QApplication.processEvents(QEventLoop.AllEvents)

# -----------------------------------------------------------------------------
# Utilities/Widgets
# -----------------------------------------------------------------------------
from mantidqt.utils.qt import add_actions, create_action  # noqa
from mantidqt.widgets.manageuserdirectories import ManageUserDirectories  # noqa

# -----------------------------------------------------------------------------
# MainWindow
Beispiel #22
0
        self.move(0, 0)
        self.setWindowTitle('Hola, QMainWindow')
        ruta_icono = Path('.', 'imgs', 'pybofractal.png')
        self.setWindowIcon(QIcon(str(ruta_icono)))
        self.statusBar().showMessage('Ready')
        self.show()


if __name__ == '__main__':

    app = QApplication(sys.argv)

    # Crea y muestra el splash screen
    path = Path('imgs', 'splashscreen_background.jpg')
    splash_pix = QPixmap(str(path))
    splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
    splash.setEnabled(False)
    splash.show()

    # Esto es un simple contador/temporizador para mostrar en pantalla
    # el splash screen. En el futuro haremos que esto sea más útil.
    for i in range(0, 5):
        msg = ('<h1><font color="yellow">' f'Listo en {5 - i}s' '</font></h1>')
        splash.showMessage(msg,
                           int(Qt.AlignLeft) | int(Qt.AlignBottom), Qt.black)
        time.sleep(1)
        app.processEvents()

    w = MiVentana()
    splash.finish(w)
    sys.exit(app.exec_())
Beispiel #23
0
    if app is None:
        app = QApplication(['Mantid Workbench'])
    return app


# Create the application object early
MAIN_APP = qapplication()

# -----------------------------------------------------------------------------
# Splash screen
# -----------------------------------------------------------------------------
# Importing resources loads the data in
from workbench.app.resources import qCleanupResources  # noqa
atexit.register(qCleanupResources)

SPLASH = QSplashScreen(QPixmap(':/images/MantidSplashScreen.png'),
                       Qt.WindowStaysOnTopHint)
SPLASH.show()
SPLASH.showMessage("Starting...", Qt.AlignBottom | Qt.AlignLeft |
                   Qt.AlignAbsolute, QColor(Qt.black))
# The event loop has not started - force event processing
QApplication.processEvents(QEventLoop.AllEvents)

# -----------------------------------------------------------------------------
# Utilities/Widgets
# -----------------------------------------------------------------------------
from mantidqt.py3compat import qbytearray_to_str  # noqa
from mantidqt.utils.qt import add_actions, create_action  # noqa
from mantidqt.widgets.manageuserdirectories import ManageUserDirectories  # noqa
from workbench.config.main import CONF  # noqa
from workbench.external.mantid import prepare_mantid_env  # noqa