Exemple #1
0
def init():
    """Initialize logging for the tests."""
    logging.basicConfig(format='\nLOG %(levelname)s %(name)s '
                        '%(module)s:%(funcName)s:%(lineno)d %(message)s',
                        level=logging.WARNING)
    logging.captureWarnings(True)
    qInstallMessageHandler(qt_message_handler)
    def exception_hook(self, exctype, excvalue, tb):
        """Handle uncaught python exceptions.

        It'll try very hard to write all open tabs to a file, and then exit
        gracefully.
        """
        exc = (exctype, excvalue, tb)

        if not self._quitter.quit_status['crash']:
            log.misc.error("ARGH, there was an exception while the crash "
                           "dialog is already shown:", exc_info=exc)
            return

        log.misc.error("Uncaught exception", exc_info=exc)

        is_ignored_exception = (exctype is bdb.BdbQuit or
                                not issubclass(exctype, Exception))

        if 'pdb-postmortem' in self._args.debug_flags:
            pdb.post_mortem(tb)

        if is_ignored_exception or 'pdb-postmortem' in self._args.debug_flags:
            # pdb exit, KeyboardInterrupt, ...
            sys.exit(usertypes.Exit.exception)

        self._quitter.quit_status['crash'] = False
        info = self._get_exception_info()

        try:
            ipc.server.ignored = True
        except Exception:
            log.destroy.exception("Error while ignoring ipc")

        try:
            self._app.lastWindowClosed.disconnect(
                self._quitter.on_last_window_closed)
        except TypeError:
            log.destroy.exception("Error while preventing shutdown")

        global is_crashing
        is_crashing = True

        self._app.closeAllWindows()
        if self._args.no_err_windows:
            crashdialog.dump_exception_info(exc, info.pages, info.cmd_history,
                                            info.objects)
        else:
            self._crash_dialog = crashdialog.ExceptionCrashDialog(
                self._args.debug, info.pages, info.cmd_history, exc,
                info.objects)
            ret = self._crash_dialog.exec_()
            if ret == crashdialog.Result.restore:
                self._quitter.restart(info.pages)

        # We might risk a segfault here, but that's better than continuing to
        # run in some undefined state, so we only do the most needed shutdown
        # here.
        qInstallMessageHandler(None)
        self.destroy_crashlogfile()
        sys.exit(usertypes.Exit.exception)
Exemple #3
0
def start(mode):
    # Install message handler for Qt messages
    qInstallMessageHandler(gui_msg_handler)

    # Start the Qt main object
    app = QApplication([])

    # Start the bluesky network client
    client = GuiClient()

    # Enable HiDPI support (Qt5 only)
    if QT_VERSION >= 0x050000:
        app.setAttribute(Qt.AA_UseHighDpiPixmaps)

    splash = Splash()

    # Register our custom pan/zoom event
    for etype in range(1000, 1000 + NUMCUSTOMEVENTS):
        reg_etype = QEvent.registerEventType(etype)
        if reg_etype != etype:
            print(('Warning: Registered event type differs from requested type id (%d != %d)' % (reg_etype, etype)))

    splash.show()

    # Install error message handler
    handler = QErrorMessage.qtHandler()
    handler.setWindowFlags(Qt.WindowStaysOnTopHint)

    # Check and set OpenGL capabilities
    if not QGLFormat.hasOpenGL():
        raise RuntimeError('No OpenGL support detected for this system!')
    else:
        f = QGLFormat()
        f.setVersion(3, 3)
        f.setProfile(QGLFormat.CoreProfile)
        f.setDoubleBuffer(True)
        QGLFormat.setDefaultFormat(f)
        print(('QGLWidget initialized for OpenGL version %d.%d' % (f.majorVersion(), f.minorVersion())))

    splash.showMessage('Constructing main window')
    app.processEvents()
    win = MainWindow(mode)
    win.show()
    splash.showMessage('Done!')
    app.processEvents()
    splash.finish(win)
    # If this instance of the gui is started in client-only mode, show
    # server selection dialog
    if mode == 'client':
        dialog = DiscoveryDialog(win)
        dialog.show()
        bs.net.start_discovery()

    else:
        client.connect(event_port=bs.settings.event_port,
                       stream_port=bs.settings.stream_port)

    # Start the Qt main loop
    app.exec_()
Exemple #4
0
 def _shutdown(self, status, restart):  # noqa
     """Second stage of shutdown."""
     log.destroy.debug("Stage 2 of shutting down...")
     if qApp is None:
         # No QApplication exists yet, so quit hard.
         sys.exit(status)
     # Remove eventfilter
     try:
         log.destroy.debug("Removing eventfilter...")
         event_filter = objreg.get('event-filter', None)
         if event_filter is not None:
             qApp.removeEventFilter(event_filter)
     except AttributeError:
         pass
     # Close all windows
     QApplication.closeAllWindows()
     # Shut down IPC
     try:
         objreg.get('ipc-server').shutdown()
     except KeyError:
         pass
     # Save everything
     try:
         save_manager = objreg.get('save-manager')
     except KeyError:
         log.destroy.debug("Save manager not initialized yet, so not "
                           "saving anything.")
     else:
         for key in save_manager.saveables:
             try:
                 save_manager.save(key, is_exit=True)
             except OSError as e:
                 error.handle_fatal_exc(
                     e, self._args, "Error while saving!",
                     pre_text="Error while saving {}".format(key))
     # Disable storage so removing tempdir will work
     websettings.shutdown()
     # Re-enable faulthandler to stdout, then remove crash log
     log.destroy.debug("Deactivating crash log...")
     objreg.get('crash-handler').destroy_crashlogfile()
     # Delete temp basedir
     if ((self._args.temp_basedir or self._args.temp_basedir_restarted) and
             not restart):
         atexit.register(shutil.rmtree, self._args.basedir,
                         ignore_errors=True)
     # Delete temp download dir
     downloads.temp_download_manager.cleanup()
     # If we don't kill our custom handler here we might get segfaults
     log.destroy.debug("Deactivating message handler...")
     qInstallMessageHandler(None)
     # Now we can hopefully quit without segfaults
     log.destroy.debug("Deferring QApplication::exit...")
     objreg.get('signal-handler').deactivate()
     session_manager = objreg.get('session-manager', None)
     if session_manager is not None:
         session_manager.delete_autosave()
     # We use a singleshot timer to exit here to minimize the likelihood of
     # segfaults.
     QTimer.singleShot(0, functools.partial(qApp.exit, status))
Exemple #5
0
    def _exception_hook(self, exctype, excvalue, tb):
        """Handle uncaught python exceptions.

        It'll try very hard to write all open tabs to a file, and then exit
        gracefully.
        """
        # pylint: disable=broad-except

        if exctype is bdb.BdbQuit or not issubclass(exctype, Exception):
            # pdb exit, KeyboardInterrupt, ...
            try:
                self.shutdown()
                return
            except Exception:
                log.init.exception("Error while shutting down")
                self.quit()
                return

        exc = (exctype, excvalue, tb)
        sys.__excepthook__(*exc)

        self._quit_status['crash'] = False

        try:
            pages = self._recover_pages()
        except Exception:
            log.destroy.exception("Error while recovering pages")
            pages = []

        try:
            history = objreg.get('status-command').history[-5:]
        except Exception:
            log.destroy.exception("Error while getting history: {}")
            history = []

        try:
            objects = self.get_all_objects()
        except Exception:
            log.destroy.exception("Error while getting objects")
            objects = ""

        try:
            self.lastWindowClosed.disconnect(self.shutdown)
        except TypeError:
            log.destroy.exception("Error while preventing shutdown")
        QApplication.closeAllWindows()
        self._crashdlg = crash.ExceptionCrashDialog(pages, history, exc,
                                                    objects)
        ret = self._crashdlg.exec_()
        if ret == QDialog.Accepted:  # restore
            self.restart(shutdown=False, pages=pages)
        # We might risk a segfault here, but that's better than continuing to
        # run in some undefined state, so we only do the most needed shutdown
        # here.
        qInstallMessageHandler(None)
        self._destroy_crashlogfile()
        sys.exit(1)
Exemple #6
0
 def _shutdown(self, status):
     """Second stage of shutdown."""
     log.destroy.debug("Stage 2 of shutting down...")
     if qApp is None:
         # No QApplication exists yet, so quit hard.
         sys.exit(status)
     # Remove eventfilter
     try:
         log.destroy.debug("Removing eventfilter...")
         qApp.removeEventFilter(objreg.get("event-filter"))
     except AttributeError:
         pass
     # Close all windows
     QApplication.closeAllWindows()
     # Shut down IPC
     try:
         objreg.get("ipc-server").shutdown()
     except KeyError:
         pass
     # Save everything
     try:
         save_manager = objreg.get("save-manager")
     except KeyError:
         log.destroy.debug("Save manager not initialized yet, so not " "saving anything.")
     else:
         for key in save_manager.saveables:
             try:
                 save_manager.save(key, is_exit=True)
             except OSError as e:
                 error.handle_fatal_exc(
                     e, self._args, "Error while saving!", pre_text="Error while saving {}".format(key)
                 )
     # Disable storage so removing tempdir will work
     QWebSettings.setIconDatabasePath("")
     QWebSettings.setOfflineWebApplicationCachePath("")
     QWebSettings.globalSettings().setLocalStoragePath("")
     # Re-enable faulthandler to stdout, then remove crash log
     log.destroy.debug("Deactivating crash log...")
     objreg.get("crash-handler").destroy_crashlogfile()
     # Delete temp basedir
     if self._args.temp_basedir:
         atexit.register(shutil.rmtree, self._args.basedir, ignore_errors=True)
     # If we don't kill our custom handler here we might get segfaults
     log.destroy.debug("Deactivating message handler...")
     qInstallMessageHandler(None)
     # Now we can hopefully quit without segfaults
     log.destroy.debug("Deferring QApplication::exit...")
     objreg.get("signal-handler").deactivate()
     # We use a singleshot timer to exit here to minimize the likelihood of
     # segfaults.
     QTimer.singleShot(0, functools.partial(qApp.exit, status))
Exemple #7
0
 def _shutdown(self, status):  # noqa
     """Second stage of shutdown."""
     log.destroy.debug("Stage 2 of shutting down...")
     if qApp is None:
         # No QApplication exists yet, so quit hard.
         sys.exit(status)
     # Remove eventfilter
     try:
         log.destroy.debug("Removing eventfilter...")
         qApp.removeEventFilter(objreg.get('event-filter'))
     except AttributeError:
         pass
     # Close all windows
     QApplication.closeAllWindows()
     # Shut down IPC
     try:
         objreg.get('ipc-server').shutdown()
     except KeyError:
         pass
     # Save everything
     try:
         save_manager = objreg.get('save-manager')
     except KeyError:
         log.destroy.debug("Save manager not initialized yet, so not "
                           "saving anything.")
     else:
         for key in save_manager.saveables:
             try:
                 save_manager.save(key, is_exit=True)
             except OSError as e:
                 msgbox = QMessageBox(
                     QMessageBox.Critical, "Error while saving!",
                     "Error while saving {}: {}".format(key, e))
                 msgbox.exec_()
     # Re-enable faulthandler to stdout, then remove crash log
     log.destroy.debug("Deactivating crash log...")
     objreg.get('crash-handler').destroy_crashlogfile()
     # If we don't kill our custom handler here we might get segfaults
     log.destroy.debug("Deactiving message handler...")
     qInstallMessageHandler(None)
     # Now we can hopefully quit without segfaults
     log.destroy.debug("Deferring QApplication::exit...")
     objreg.get('signal-handler').deactivate()
     # We use a singleshot timer to exit here to minimize the likelihood of
     # segfaults.
     QTimer.singleShot(0, functools.partial(qApp.exit, status))
Exemple #8
0
def init_log(args):
    """Init loggers based on the argparse namespace passed."""
    level = 'VDEBUG' if args.debug else args.loglevel.upper()
    try:
        numeric_level = getattr(logging, level)
    except AttributeError:
        raise ValueError("Invalid log level: {}".format(args.loglevel))

    console, ram = _init_handlers(numeric_level, args.color, args.loglines)
    root = logging.getLogger()
    if console is not None:
        if args.logfilter is not None:
            console.addFilter(LogFilter(args.logfilter.split(',')))
        root.addHandler(console)
    if ram is not None:
        root.addHandler(ram)
    root.setLevel(logging.NOTSET)
    logging.captureWarnings(True)
    qInstallMessageHandler(qt_message_handler)
Exemple #9
0
def qtHandler():
    """
    Module function to install an E5ErrorMessage dialog as the global
    message handler.
    
    @return reference to the message handler dialog (E5ErrorMessage)
    """
    global __msgHandlerDialog, __origMsgHandler
    
    if __msgHandlerDialog is None:
        # Install an E5ErrorMessage dialog as the global message handler.
        __msgHandlerDialog = E5ErrorMessage()
        __origMsgHandler = qInstallMessageHandler(messageHandler)
    
    return __msgHandlerDialog
Exemple #10
0
    def _exception_hook(self, exctype, excvalue, tb):  # noqa
        """Handle uncaught python exceptions.

        It'll try very hard to write all open tabs to a file, and then exit
        gracefully.
        """
        # pylint: disable=broad-except

        exc = (exctype, excvalue, tb)

        if not self._quit_status['crash']:
            log.misc.error(
                "ARGH, there was an exception while the crash "
                "dialog is already shown:",
                exc_info=exc)
            return

        log.misc.error("Uncaught exception", exc_info=exc)

        is_ignored_exception = (exctype is bdb.BdbQuit
                                or not issubclass(exctype, Exception))

        if is_ignored_exception or self._args.no_crash_dialog:
            # pdb exit, KeyboardInterrupt, ...
            status = 0 if is_ignored_exception else 2
            try:
                self.shutdown(status)
                return
            except Exception:
                log.init.exception("Error while shutting down")
                self.quit()
                return

        self._quit_status['crash'] = False

        try:
            pages = self._recover_pages(forgiving=True)
        except Exception:
            log.destroy.exception("Error while recovering pages")
            pages = []

        try:
            history = objreg.get('command-history')[-5:]
        except Exception:
            log.destroy.exception("Error while getting history: {}")
            history = []

        try:
            objects = self.get_all_objects()
        except Exception:
            log.destroy.exception("Error while getting objects")
            objects = ""

        try:
            objreg.get('ipc-server').ignored = True
        except Exception:
            log.destroy.exception("Error while ignoring ipc")

        try:
            self.lastWindowClosed.disconnect(self.shutdown)
        except TypeError:
            log.destroy.exception("Error while preventing shutdown")
        QApplication.closeAllWindows()
        self._crashdlg = crashdialog.ExceptionCrashDialog(
            self._args.debug, pages, history, exc, objects)
        ret = self._crashdlg.exec_()
        if ret == QDialog.Accepted:  # restore
            self.restart(shutdown=False, pages=pages)
        # We might risk a segfault here, but that's better than continuing to
        # run in some undefined state, so we only do the most needed shutdown
        # here.
        qInstallMessageHandler(None)
        self._destroy_crashlogfile()
        sys.exit(1)
Exemple #11
0
def run(cmdConfig=[], type='gui', exitPoint=None):
    """This is the entry point of Maestro. With the default arguments Maestro will start the GUI. Use init
    if you only want to initialize the framework without starting the GUI.
    
    *cmdConfig* is a list of options given on the command line that will
    overwrite the corresponding option from the file or the default. Each list item has to be a string like
    ``database.type=sqlite``.
    
    *type* is determines how the application should be initialized and run: "gui" will start the usual
    application, "console" will initialize the framework without starting the the GUI. "test" is similar
    to "console" but will connect to an in-memory SQLite-database instead of the usual database. All tables
    will be created and empty in this database.
    
    Using the optional argument *exitPoint* you may also initialize only part of the framework. Allowed
    values are (in this order):
    
        - 'config':    Initialize only config
        - 'database':  Stop after database connection has been established
        - 'tags':      Stop after tags module has been initialized (this needs a db connection)
        - 'noplugins': Stop before plugins would be loaded
        - 'nogui':     Stop right before the GUI would be created (plugins are enabled at this point)
        
    If *exitPoint* is not None, this method returns the created QApplication-instance.
    """
    handleCommandLineOptions(cmdConfig)
    
    # Some Qt-classes need a running QApplication before they can be created
    app = QtWidgets.QApplication(sys.argv)
    app.setApplicationName("Maestro")
    app.setApplicationVersion(VERSION)
    from PyQt5.QtCore import qInstallMessageHandler
    qInstallMessageHandler(qtMsgHandler)

    from maestro import resources
    if type == "gui":
        splash = Splash("Loading Maestro")
        splash.show()
        app.processEvents()
        
    # Initialize config and logging
    config.init(cmdConfig, testMode=(type == 'test'))
    
    # Initialize logging as early as possible -- but after the config variables have been read.
    logging.init()
    global logger
    logger = logging.getLogger(__name__)

    logger.debug("START")

    if exitPoint == 'config':
        return app
    
    # Lock the lockfile to prevent a second Maestro-instance from starting.
    if type == 'gui':
        lock()
    
    if type == 'gui':
        splash.showMessage("Loading translations")
    loadTranslators(app, logger)
    translate = QtCore.QCoreApplication.translate
        
    # Initialize database
    if type == 'test':
        config.options.database.type = 'sqlite'
        config.options.database.prefix = 'test'
        config.options.database.sqlite_path = ':memory:'
    from . import database
    try:
        if type == 'gui':
            splash.showMessage(translate('Splash', 'Connecting to database'))
        database.init()
    except database.DBException as e:
        logger.error('I cannot connect to the database. Did you provide the correct information in the'
                     ' config file? SQL error: {}'.format(e.message))
        if type == 'gui':
            runInstaller()
            
    if type == 'test':
        database.createTables()
            
    if exitPoint == 'database':
        return app
    # Initialize undo/redo and event handling
    from . import stack
    stack.init()
    global dispatcher
    dispatcher = ChangeEventDispatcher()
    
    # Initialize core
    from .core import domains, tags, flags
    try:
        domains.init()
        tags.init()
    except RuntimeError:
        if type == 'gui':
            runInstaller()
        else:
            sys.exit(1)
                       
    if type == 'gui':
        # Do not start without a domain
        if len(domains.domains) == 0:
            logger.error("No domain defined.")
            runInstaller() 
            
        # Weird things might happen if these tagtypes are external
        if not tags.get(config.options.tags.title_tag).isInDb():
            logger.error("Title tag '{}' is missing in tagids table.".format(config.options.tags.title_tag))
            runInstaller()
        if not tags.get(config.options.tags.album_tag).isInDb():
            logger.error("Album tag '{}' is missing in tagids table.".format(config.options.tags.album_tag))
            runInstaller()
            
        # In most test scripts these caches would only be overhead.
        database.tags.cacheValues()
        
    flags.init()
    
    if exitPoint == 'tags':
        return app
    
    # Load and initialize remaining modules
    from maestro.core import levels
    levels.init()
    from maestro.core import covers
    covers.init()

    global network
    network = QtNetwork.QNetworkAccessManager()
    
    if type == 'test' or exitPoint == 'noplugins':
        return app

    import maestro.gui.delegates
    maestro.gui.delegates.init()
    import maestro.player
    maestro.player.init()
    import maestro.gui.preferences
    maestro.gui.preferences.init()

    # Load Plugins
    if type == 'gui':
        splash.showMessage(translate('Splash', 'Loading plugins'))
    from maestro import plugins
    plugins.init()
    for pluginName in plugins.enablePlugins(True):
        if type == 'gui':
            splash.showMessage(translate('Splash', 'Enabling plugin »{}«').format(pluginName))
    
    if type != 'gui':
        return app

    from . import filesystem
    filesystem.enable()

    # Create GUI
    splash.showMessage(translate('Splash', 'Loading GUI classes'))
    from maestro.gui import mainwindow
    # First import all modules that want to register WidgetClass-instances
    import maestro.filesystem
    from maestro.gui import treeactions
    import maestro.widgets.playlist.gui
    import maestro.widgets.editor.gui
    global mainWindow
    mainwindow.init()
    treeactions.init()
    maestro.widgets.init()
    maestro.filesystem.init()
    splash.showMessage(translate('Splash', 'Creating main window'))
    mainWindow = mainwindow.MainWindow()
    plugins.mainWindowInit()
    
    # Launch application
    logger.debug('showing mainwindow')
    mainWindow.show()
    splash.finish(mainWindow)
    logger.debug('entering event loop')
    returnValue = app.exec_()
    
    # Close operations
    logger.debug('main application quit')
    filesystem.disable()
    mainWindow.close()
    plugins.shutdown()
    covers.shutdown()
    import maestro.profiles
    maestro.profiles.save()
    database.tags.deleteSuperfluousValues()
    database.shutdown()
    config.shutdown()
    logging.shutdown()
    sys.exit(returnValue)
Exemple #12
0
 def _shutdown(self, status, restart):  # noqa
     """Second stage of shutdown."""
     log.destroy.debug("Stage 2 of shutting down...")
     if qApp is None:
         # No QApplication exists yet, so quit hard.
         sys.exit(status)
     # Remove eventfilter
     try:
         log.destroy.debug("Removing eventfilter...")
         event_filter = objreg.get('event-filter', None)
         if event_filter is not None:
             qApp.removeEventFilter(event_filter)
     except AttributeError:
         pass
     # Close all windows
     QApplication.closeAllWindows()
     # Shut down IPC
     try:
         ipc.server.shutdown()
     except KeyError:
         pass
     # Save everything
     try:
         save_manager = objreg.get('save-manager')
     except KeyError:
         log.destroy.debug("Save manager not initialized yet, so not "
                           "saving anything.")
     else:
         for key in save_manager.saveables:
             try:
                 save_manager.save(key, is_exit=True)
             except OSError as e:
                 error.handle_fatal_exc(
                     e, self._args, "Error while saving!",
                     pre_text="Error while saving {}".format(key))
     # Disable storage so removing tempdir will work
     websettings.shutdown()
     # Disable application proxy factory to fix segfaults with Qt 5.10.1
     proxy.shutdown()
     # Re-enable faulthandler to stdout, then remove crash log
     log.destroy.debug("Deactivating crash log...")
     objreg.get('crash-handler').destroy_crashlogfile()
     # Delete temp basedir
     if ((self._args.temp_basedir or self._args.temp_basedir_restarted) and
             not restart):
         atexit.register(shutil.rmtree, self._args.basedir,
                         ignore_errors=True)
     # Delete temp download dir
     downloads.temp_download_manager.cleanup()
     # If we don't kill our custom handler here we might get segfaults
     log.destroy.debug("Deactivating message handler...")
     qInstallMessageHandler(None)
     # Now we can hopefully quit without segfaults
     log.destroy.debug("Deferring QApplication::exit...")
     objreg.get('signal-handler').deactivate()
     session_manager = objreg.get('session-manager', None)
     if session_manager is not None:
         session_manager.delete_autosave()
     # We use a singleshot timer to exit here to minimize the likelihood of
     # segfaults.
     QTimer.singleShot(0, functools.partial(qApp.exit, status))
Exemple #13
0
    def __init__(self):

        logging.info(f"Trawl Analyzer starting at: {arrow.now().format('MM/DD/YYYY HH:mm:ss')}")

        qInstallMessageHandler(FramUtil.qt_msg_handler)

        app_guid = str(uuid1())
        logging.info(f"uuid={app_guid}")

        self.app = QtSingleApplication(app_guid, sys.argv)
        if self.app.isRunning():
            sys.exit(0)

        self.app.unhandledExceptionCaught.connect(self.exception_caught)
        # self.app.aboutToQuit.connect(self.about_to_quit_callback)

        self.engine = QQmlApplicationEngine()
        self.context = self.engine.rootContext()

        qmlRegisterType(FramTreeItem, 'FramTreeItem', 1, 0, 'FramTreeItem')
        qmlRegisterType(SortFilterProxyModel, "SortFilterProxyModel", 0, 1, "SortFilterProxyModel")
        # qmlRegisterType(MatplotlibFigure, "MatplotlibFigure", 1, 0, "MatplotlibFigure")

        qmlRegisterType(FigureCanvasQTAgg, "MplBackend", 1, 0, "MplFigureCanvas")

        # Set Contexts
        # wfs = WindowFrameSize()
        # self.context.setContextProperty('wfs', wfs)

        self.settings = Settings(app=self)
        self.context.setContextProperty("settings", self.settings)

        fl = FramLog()
        self.context.setContextProperty('framLog', fl)

        self.db = TrawlAnalyzerDB()
        self.context.setContextProperty('db', self.db)

        self.common_functions = CommonFunctions(app=self)
        self.context.setContextProperty('commonFunctions', self.common_functions)

        self.file_management = FileManagement(app=self, db=self.db)
        self.context.setContextProperty("fileManagement", self.file_management)

        self.data_completeness = DataCompleteness(app=self, db=self.db)
        self.context.setContextProperty("dataCompleteness", self.data_completeness)

        self.time_series = TimeSeries(app=self, db=self.db)
        self.context.setContextProperty("timeSeries", self.time_series)

        self.engine.load(QUrl('qrc:/qml/trawl_analyzer/main_trawl_analyzer.qml'))

        """
        Used to access QML objects from Python.  References:
        https://forum.qt.io/topic/62966/parent-in-pyqt5-with-qml
        http://stackoverflow.com/questions/24111717/how-to-bind-buttons-in-qt-quick-to-python-pyqt-5
        """
        self.win = self.engine.rootObjects()[0]
        self.qml_item = self.win.findChild(QObject, "mplFigure")
        self.time_series.set_qml_item(self.qml_item)

        self.msg_box = self.win.findChild(QObject, "dlgUnhandledException")


        self.tracklines_item = self.win.findChild(QObject, "mplTracklines")
        self.time_series._mpl_map.set_qml_item(self.tracklines_item)

        self.engine.quit.connect(self.app.quit)
        sys.exit(self.app.exec_())
Exemple #14
0
def disable_qt_msghandler():
    """Contextmanager which temporarily disables the Qt message handler."""
    old_handler = qInstallMessageHandler(None)
    yield
    qInstallMessageHandler(old_handler)
Exemple #15
0
 def _shutdown(self, status):  # noqa
     """Second stage of shutdown."""
     # pylint: disable=too-many-branches, too-many-statements
     # FIXME refactor this
     # https://github.com/The-Compiler/qutebrowser/issues/113
     log.destroy.debug("Stage 2 of shutting down...")
     # Remove eventfilter
     try:
         log.destroy.debug("Removing eventfilter...")
         self.removeEventFilter(self._event_filter)
     except AttributeError:
         pass
     # Close all windows
     QApplication.closeAllWindows()
     # Shut down IPC
     try:
         objreg.get('ipc-server').shutdown()
     except KeyError:
         pass
     # Save everything
     try:
         config_obj = objreg.get('config')
     except KeyError:
         log.destroy.debug("Config not initialized yet, so not saving "
                           "anything.")
     else:
         to_save = []
         if config.get('general', 'auto-save-config'):
             to_save.append(("config", config_obj.save))
             try:
                 key_config = objreg.get('key-config')
             except KeyError:
                 pass
             else:
                 to_save.append(("keyconfig", key_config.save))
         to_save += [("window geometry", self._save_geometry)]
         to_save += [("version", self._save_version)]
         try:
             command_history = objreg.get('command-history')
         except KeyError:
             pass
         else:
             to_save.append(("command history", command_history.save))
         try:
             quickmark_manager = objreg.get('quickmark-manager')
         except KeyError:
             pass
         else:
             to_save.append(("command history", quickmark_manager.save))
         try:
             state_config = objreg.get('state-config')
         except KeyError:
             pass
         else:
             to_save.append(("window geometry", state_config.save))
         try:
             cookie_jar = objreg.get('cookie-jar')
         except KeyError:
             pass
         else:
             to_save.append(("cookies", cookie_jar.save))
         for what, handler in to_save:
             log.destroy.debug("Saving {} (handler: {})".format(
                 what, utils.qualname(handler)))
             try:
                 handler()
             except OSError as e:
                 msgbox = QMessageBox(
                     QMessageBox.Critical, "Error while saving!",
                     "Error while saving {}: {}".format(what, e))
                 msgbox.exec_()
             except AttributeError as e:
                 log.destroy.warning("Could not save {}.".format(what))
                 log.destroy.debug(e)
     # Re-enable faulthandler to stdout, then remove crash log
     log.destroy.debug("Deactiving crash log...")
     self._destroy_crashlogfile()
     # If we don't kill our custom handler here we might get segfaults
     log.destroy.debug("Deactiving message handler...")
     qInstallMessageHandler(None)
     # Now we can hopefully quit without segfaults
     log.destroy.debug("Deferring QApplication::exit...")
     # We use a singleshot timer to exit here to minimize the likelyhood of
     # segfaults.
     QTimer.singleShot(0, functools.partial(self.exit, status))
Exemple #16
0
        print("Info: {} ({}:{}, {})".format(msg, context.file, context.line,
                                            context.function))
    elif type == QtWarningMsg:
        print("Warning: {} ({}:{}, {})".format(msg, context.file, context.line,
                                               context.function))
    elif type == QtCriticalMsg:
        print("Critical: {} ({}:{}, {})".format(msg, context.file,
                                                context.line,
                                                context.function))
    elif type == QtFatalMsg:
        print("Fatal: {} ({}:{}, {})".format(msg, context.file, context.line,
                                             context.function))


if __name__ == '__main__':
    QCoreApplication.setAttribute(Qt.AA_UseHighDpiPixmaps)
    QGuiApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
    app = QApplication(sys.argv)
    app.setQuitOnLastWindowClosed(True)

    with open(os.path.join(os.path.dirname(__file__), "app.css"),
              "r") as style_sheet_file:
        app.setStyleSheet(style_sheet_file.read())

    qInstallMessageHandler(my_message_output)
    qDebug("Message handler test")

    mw = MainWindow()
    mw.show()
    app.exec_()
Exemple #17
0
def disable_qt_msghandler():
    """Contextmanager which temporarily disables the Qt message handler."""
    old_handler = qInstallMessageHandler(None)
    yield
    qInstallMessageHandler(old_handler)
Exemple #18
0
    def __init__(self, args, config, daemon):
        super().__init__(args)

        self.logger = get_logger(__name__)

        ElectrumQmlApplication._daemon = daemon

        qmlRegisterType(QEWalletListModel, 'org.electrum', 1, 0,
                        'WalletListModel')
        qmlRegisterType(QEWallet, 'org.electrum', 1, 0, 'Wallet')
        qmlRegisterType(QEWalletDB, 'org.electrum', 1, 0, 'WalletDB')
        qmlRegisterType(QEBitcoin, 'org.electrum', 1, 0, 'Bitcoin')
        qmlRegisterType(QEQRParser, 'org.electrum', 1, 0, 'QRParser')
        qmlRegisterType(QEFX, 'org.electrum', 1, 0, 'FX')
        qmlRegisterType(QETxFinalizer, 'org.electrum', 1, 0, 'TxFinalizer')
        qmlRegisterType(QEInvoice, 'org.electrum', 1, 0, 'Invoice')
        qmlRegisterType(QEInvoiceParser, 'org.electrum', 1, 0, 'InvoiceParser')
        qmlRegisterType(QEUserEnteredPayment, 'org.electrum', 1, 0,
                        'UserEnteredPayment')
        qmlRegisterType(QEAddressDetails, 'org.electrum', 1, 0,
                        'AddressDetails')
        qmlRegisterType(QETxDetails, 'org.electrum', 1, 0, 'TxDetails')
        qmlRegisterType(QEChannelOpener, 'org.electrum', 1, 0, 'ChannelOpener')
        qmlRegisterType(QELnPaymentDetails, 'org.electrum', 1, 0,
                        'LnPaymentDetails')
        qmlRegisterType(QEChannelDetails, 'org.electrum', 1, 0,
                        'ChannelDetails')
        qmlRegisterType(QESwapHelper, 'org.electrum', 1, 0, 'SwapHelper')

        qmlRegisterUncreatableType(QEAmount, 'org.electrum', 1, 0, 'Amount',
                                   'Amount can only be used as property')

        self.engine = QQmlApplicationEngine(parent=self)
        self.engine.addImportPath('./qml')

        screensize = self.primaryScreen().size()

        self.qr_ip = QEQRImageProvider(
            (7 / 8) * min(screensize.width(), screensize.height()))
        self.engine.addImageProvider('qrgen', self.qr_ip)

        # add a monospace font as we can't rely on device having one
        self.fixedFont = 'PT Mono'
        not_loaded = QFontDatabase.addApplicationFont(
            'electrum/gui/qml/fonts/PTMono-Regular.ttf') < 0
        not_loaded = QFontDatabase.addApplicationFont(
            'electrum/gui/qml/fonts/PTMono-Bold.ttf') < 0 and not_loaded
        if not_loaded:
            self.logger.warning('Could not load font PT Mono')
            self.fixedFont = 'Monospace'  # hope for the best

        self.context = self.engine.rootContext()
        self._qeconfig = QEConfig(config)
        self._qenetwork = QENetwork(daemon.network)
        self._qedaemon = QEDaemon(daemon)
        self._appController = QEAppController(self._qedaemon)
        self._maxAmount = QEAmount(is_max=True)
        self.context.setContextProperty('AppController', self._appController)
        self.context.setContextProperty('Config', self._qeconfig)
        self.context.setContextProperty('Network', self._qenetwork)
        self.context.setContextProperty('Daemon', self._qedaemon)
        self.context.setContextProperty('FixedFont', self.fixedFont)
        self.context.setContextProperty('MAX', self._maxAmount)
        self.context.setContextProperty(
            'BUILD', {
                'electrum_version': version.ELECTRUM_VERSION,
                'apk_version': version.APK_VERSION,
                'protocol_version': version.PROTOCOL_VERSION
            })

        qInstallMessageHandler(self.message_handler)

        # get notified whether root QML document loads or not
        self.engine.objectCreated.connect(self.objectCreated)
Exemple #19
0
                self.update_subs(False)
            else:
                # 如果连接对象为删除的订阅地址中的配置,断开连接
                if self.v2rayL.current_status.current in self.v2rayL.subs.saved_conf[
                        "subs"]:
                    self.disconn_start.v2rayL = self.v2rayL
                    self.disconn_start.tableView = self.first_ui.tableWidget
                    self.disconn_start.start()

                self.v2rayL.subs.saved_conf["subs"] = {}
                with open("/etc/v2rayL/ndata", "wb") as jf:
                    # print(self.v2rayL.subs.saved_conf)
                    pickle.dump(self.v2rayL.subs.saved_conf, jf)
                self.v2rayL = V2rayL()
                self.display_all_conf()
                self.config_setting_ui.lineEdit.setText(";".join(
                    [x[1] for x in self.v2rayL.current_status.url]))


if __name__ == "__main__":
    import sys
    QApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
    qInstallMessageHandler(qt_message_handler)
    app = QApplication(sys.argv)
    myWin = MyMainWindow()
    # 显示在屏幕上
    myWin.show()
    # 系统exit()方法确保应用程序干净的退出
    # 的exec_()方法有下划线。因为执行是一个Python关键词。因此,exec_()代替
    sys.exit(app.exec_())
Exemple #20
0
global current_status
current_status = "STOPPED"

global Timer

# Timer = 00:00:00


# This is to ignore some warnings which were thrown when gui exited and python deleted some assests in wrong order
# Nothing critical
def handler(msg_type, msg_log_context, msg_string):
    pass


qInstallMessageHandler(handler)


class client_window(QMainWindow):
    def __init__(self, channel, data_changed_flag2, queue, score):
        super().__init__()
        global current_status
        current_status = "STOPPED"
        global Timer
        # Set app icon
        self.setWindowIcon(QIcon('Elements/logo.png'))
        # Set window title
        self.setWindowTitle('BitsOJ v1.0.1 [ Client ]')

        # self.setFixedSize(1200,700)
        self.resize(1200, 700)
Exemple #21
0
    }[msgType]

    print("Qt[{strType}] {category} {function} in {file}, on line {line}\n"
          "    {msg}".format(strType = strType,
                             category = context.category,
                             function = context.function,
                             file = context.file,
                             line = context.line,
                             msg = msg),
          file = sys.stdout if msgType in (QtDebugMsg, QtWarningMsg) else sys.stderr)


app = None
if __name__ == "__main__":
    doQtIntegrityCheck()
    qInstallMessageHandler(QtMsgHandler)

    from shared.profile import profileBootstrap
    profileBootstrap(constants.PROFILE_DIR)
    app = XwareDesktop(sys.argv)

    def safeExec(app_):
        code = app_.exec()
        if __debug__:
            windows = app_.topLevelWindows()
            if windows:
                raise RuntimeError("Windows left: {}"
                                   .format(list(map(lambda win: win.objectName(),
                                                    windows))))
            widgets = app_.topLevelWidgets()
            if widgets:
Exemple #22
0
    def exception_hook(self, exctype, excvalue, tb):  # noqa
        """Handle uncaught python exceptions.

        It'll try very hard to write all open tabs to a file, and then exit
        gracefully.
        """
        exc = (exctype, excvalue, tb)
        qapp = QApplication.instance()

        if not self._quitter.quit_status['crash']:
            log.misc.error("ARGH, there was an exception while the crash "
                           "dialog is already shown:", exc_info=exc)
            return

        log.misc.error("Uncaught exception", exc_info=exc)

        is_ignored_exception = (exctype is bdb.BdbQuit or
                                not issubclass(exctype, Exception))

        if self._args.pdb_postmortem:
            pdb.post_mortem(tb)

        if (is_ignored_exception or self._args.no_crash_dialog or
                self._args.pdb_postmortem):
            # pdb exit, KeyboardInterrupt, ...
            status = 0 if is_ignored_exception else 2
            try:
                qapp.shutdown(status)
                return
            except Exception:
                log.init.exception("Error while shutting down")
                qapp.quit()
                return

        self._quitter.quit_status['crash'] = False

        try:
            pages = self._recover_pages(forgiving=True)
        except Exception:
            log.destroy.exception("Error while recovering pages")
            pages = []

        try:
            cmd_history = objreg.get('command-history')[-5:]
        except Exception:
            log.destroy.exception("Error while getting history: {}")
            cmd_history = []

        try:
            objects = debug.get_all_objects()
        except Exception:
            log.destroy.exception("Error while getting objects")
            objects = ""

        try:
            objreg.get('ipc-server').ignored = True
        except Exception:
            log.destroy.exception("Error while ignoring ipc")

        try:
            self._app.lastWindowClosed.disconnect(
                self._quitter.on_last_window_closed)
        except TypeError:
            log.destroy.exception("Error while preventing shutdown")
        self._app.closeAllWindows()
        self._crash_dialog = crashdialog.ExceptionCrashDialog(
            self._args.debug, pages, cmd_history, exc, objects)
        ret = self._crash_dialog.exec_()
        if ret == QDialog.Accepted:  # restore
            self._quitter.restart(pages)

        # We might risk a segfault here, but that's better than continuing to
        # run in some undefined state, so we only do the most needed shutdown
        # here.
        qInstallMessageHandler(None)
        self.destroy_crashlogfile()
        sys.exit(1)
Exemple #23
0
    print("Qt[{strType}] {category} {function} in {file}, on line {line}\n"
          "    {msg}".format(strType=strType,
                             category=context.category,
                             function=context.function,
                             file=context.file,
                             line=context.line,
                             msg=msg),
          file=sys.stdout if msgType in (QtDebugMsg,
                                         QtWarningMsg) else sys.stderr)


app = None
if __name__ == "__main__":
    doQtIntegrityCheck()
    qInstallMessageHandler(QtMsgHandler)

    from shared.profile import profileBootstrap
    profileBootstrap(constants.PROFILE_DIR)
    app = XwareDesktop(sys.argv)

    def safeExec(app_):
        code = app_.exec()
        if __debug__:
            windows = app_.topLevelWindows()
            if windows:
                raise RuntimeError("Windows left: {}".format(
                    list(map(lambda win: win.objectName(), windows))))
            widgets = app_.topLevelWidgets()
            if widgets:
                raise RuntimeError("Widgets left: {}".format(
Exemple #24
0
    def __init__(self):

        qInstallMessageHandler(FramUtil.qt_msg_handler)

        self.rpc = RpcClient()

        # self.app = QApplication(sys.argv)

        appGuid = 'F3FF80BA-BA05-4277-8063-82A6DB9245A5'
        self.app = QtSingleApplication(appGuid, sys.argv)
        self.app.setWindowIcon(QtGui.QIcon("resources/ico/cutter.ico"))
        # splash screen to launch before loading, close later
        splash = BackdeckSplash()
        splash.show()
        if self.app.isRunning():
            sys.exit(0)

        self.app.unhandledExceptionCaught.connect(self.exception_caught)

        qmlRegisterType(SortFilterProxyModel, "SortFilterProxyModel", 0, 1,
                        "SortFilterProxyModel")

        self.engine = QQmlApplicationEngine()
        self.context = self.engine.rootContext()

        # qmlRegisterType(FramTreeItem, 'FramTreeItem', 1, 0, 'FramTreeItem')

        # Set Contexts
        # wfs = WindowFrameSize()
        # self.context.setContextProperty('wfs', wfs)

        fl = FramLog()
        self.context.setContextProperty('framLog', fl)

        db = HookAndLineHookCutterDB()
        self.context.setContextProperty('db', db)

        self.state_machine = StateMachine(app=self, db=db)
        self.sound_player = SoundPlayer(app=self, db=db)
        self.serial_port_manager = SerialPortManager(app=self, db=db)

        self.sites = Sites(app=self, db=db)
        self.fish_sampling = FishSampling(app=self, db=db)
        self.label_printer = LabelPrinter(app=self, db=db)
        self.notes = Notes(app=self, db=db)
        # self.qaqc = QAQC(app=self, db=db)
        self.settings = Settings(app=self, db=db)

        self.context.setContextProperty("soundPlayer", self.sound_player)
        self.context.setContextProperty("stateMachine", self.state_machine)
        self.context.setContextProperty("sites", self.sites)
        self.context.setContextProperty("fishSampling", self.fish_sampling)
        self.context.setContextProperty("serialPortManager",
                                        self.serial_port_manager)
        self.context.setContextProperty("labelPrinter", self.label_printer)
        self.context.setContextProperty("notes", self.notes)
        # self.context.setContextProperty("qaqc", self.qaqc)
        self.context.setContextProperty("settings", self.settings)

        # self.setAttribute(QtCore.Qt.WA_DeleteOnClose)

        try:

            self.engine.load(
                QUrl('qrc:/qml/survey_backdeck/main_backdeck.qml'))
            splash.close()
            self.win = self.engine.rootObjects()[0]
            self.msg_box = self.win.findChild(QObject, "dlgUnhandledException")

            self.engine.quit.connect(self.app.quit)
            sys.exit(self.app.exec_())

        except Exception as ex:

            logging.error(f"bad stuff happening: {ex}")
Exemple #25
0
    def exception_hook(self, exctype, excvalue, tb):
        """Handle uncaught python exceptions.

        It'll try very hard to write all open tabs to a file, and then exit
        gracefully.
        """
        exc = (exctype, excvalue, tb)
        qapp = QApplication.instance()

        if not self._quitter.quit_status['crash']:
            log.misc.error(
                "ARGH, there was an exception while the crash "
                "dialog is already shown:",
                exc_info=exc)
            return

        log.misc.error("Uncaught exception", exc_info=exc)

        is_ignored_exception = (exctype is bdb.BdbQuit
                                or not issubclass(exctype, Exception))

        if 'pdb-postmortem' in self._args.debug_flags:
            pdb.post_mortem(tb)

        if is_ignored_exception or 'pdb-postmortem' in self._args.debug_flags:
            # pdb exit, KeyboardInterrupt, ...
            status = 0 if is_ignored_exception else 2
            try:
                self._quitter.shutdown(status)
                return
            except Exception:
                log.init.exception("Error while shutting down")
                qapp.quit()
                return

        self._quitter.quit_status['crash'] = False
        info = self._get_exception_info()

        try:
            ipc.server.ignored = True
        except Exception:
            log.destroy.exception("Error while ignoring ipc")

        try:
            self._app.lastWindowClosed.disconnect(
                self._quitter.on_last_window_closed)
        except TypeError:
            log.destroy.exception("Error while preventing shutdown")

        global is_crashing
        is_crashing = True

        self._app.closeAllWindows()
        if self._args.no_err_windows:
            crashdialog.dump_exception_info(exc, info.pages, info.cmd_history,
                                            info.objects)
        else:
            self._crash_dialog = crashdialog.ExceptionCrashDialog(
                self._args.debug, info.pages, info.cmd_history, exc,
                info.objects)
            ret = self._crash_dialog.exec_()
            if ret == crashdialog.Result.restore:
                self._quitter.restart(info.pages)

        # We might risk a segfault here, but that's better than continuing to
        # run in some undefined state, so we only do the most needed shutdown
        # here.
        qInstallMessageHandler(None)
        self.destroy_crashlogfile()
        sys.exit(usertypes.Exit.exception)
    def __init__(self):

        super().__init__()

        qInstallMessageHandler(FramUtil.qt_msg_handler)

        # self.app = QApplication(sys.argv)

        appGuid = 'F3FF80BA-BA05-4277-8063-82A6DB9245A2'
        self.app = QtSingleApplication(appGuid, sys.argv)
        self.app.setWindowIcon(QtGui.QIcon("resources/ico/hooklogger.ico"))
        if self.app.isRunning():
            sys.exit(0)

        # qmlRegisterType(FramTreeItem, 'FramTreeItem', 1, 0, 'FramTreeItem')

        self.engine = QQmlApplicationEngine()

        qmlRegisterType(TextFieldDoubleValidator, "FRAM", 1, 0,
                        "TextFieldDoubleValidator")

        self.context = self.engine.rootContext()

        fl = FramLog()
        self.context.setContextProperty('framLog', fl)

        db = HookandlineFpcDB()
        self.context.setContextProperty('db', db)

        # self.textfield_double_validator = TextFieldDoubleValidator()
        # self.context.setContextProperty('TextFieldDoubleValidator', self.textfield_double_validator)

        # PyQt5 Threading approach
        self._rpc_thread = QThread()
        self._rpc_worker = RpcServer()
        self._rpc_worker.moveToThread(self._rpc_thread)
        self._rpc_worker.speciesChanged.connect(self._species_changed)
        self._rpc_thread.started.connect(self._rpc_worker.run)
        self._rpc_thread.start()

        logging.info(f"\tRPC thread and worker established")

        # Technique that works - traditional python threading, although the queue is not needed anymore
        # self._queue = Queue()
        # self._rpc_server = threading.Thread(target=RpcServer, kwargs={'queue': self._queue})
        # self._rpc_server.setDaemon(True)
        # self._rpc_server.start()

        self.fpc_main = FpcMain(app=self)
        self.settings = Settings(db=db)
        self.serial_port_manager = SerialPortManager(app=self, db=db)
        self.serial_port_simulator = SerialPortSimulator(app=self, db=db)
        self.data_converter = DataConverter(app=self, db=db)
        self.sensor_data_feeds = SensorDataFeeds(app=self, db=db)
        self.species_review = SpeciesReview(app=self, db=db)
        self.end_of_site_validation = EndOfSiteValidation(app=self, db=db)
        logging.info(f"\tComponent classes all initialized")

        self.context.setContextProperty('fpcMain', self.fpc_main)
        self.context.setContextProperty('settings', self.settings)
        self.context.setContextProperty('serialPortManager',
                                        self.serial_port_manager)
        self.context.setContextProperty('serialPortSimulator',
                                        self.serial_port_simulator)
        self.context.setContextProperty('dataConverter', self.data_converter)
        self.context.setContextProperty('sensorDataFeeds',
                                        self.sensor_data_feeds)
        self.context.setContextProperty('speciesReview', self.species_review)
        self.context.setContextProperty('endOfSiteValidation',
                                        self.end_of_site_validation)

        logging.info(f"\tContext Properties all set")

        # self.widget = self.app.instance()
        # self.widget.setAttribute(QtCore.Qt.WA_OpaquePaintEvent)
        # self.widget.setAttribute(QtCore.Qt.WA_NoSystemBackground)

        # self.view = QQuickView()
        # self.view.setSource(QUrl('qrc:/qml/hookandline/main_fpc.qml'))
        # self.view.show()

        try:
            self.engine.load(QUrl('qrc:/qml/hookandline/main_fpc.qml'))

            self.win = self.engine.rootObjects()[0]
            self.msg_box = self.win.findChild(QObject, "dlgUnhandledException")

            logging.info(f"\tmain_fpc.qml loaded")

            self.engine.quit.connect(self.app.quit)
            sys.exit(self.app.exec_())

        except Exception as ex:

            logging.error(f"error loading the application: {ex}")
        
    def run(self):
        super().__init__()
        
        self.pencere2 = QWidget()
        self.pencere2.resize(300, 300)      
        self.pencere2.setWindowIcon(QIcon(os.path.join("kaynaklar", "pencere_firefox_güncelle.png")))
        self.pencere2.setWindowTitle("Firefox Güncelleniyor")
        etk2 = QLabel("<img src='güncelle.png' />Güncelleme dosyası başarıyla indirildi !\nGüncelleme dosyası çalıştırılıyor...", self.pencere2)
        self.pencere2.show()            
""" 

class QEtiket(QLabel):
    def __init__(self, *args, **kwargs):
        super(QLabel, self).__init__(*args, **kwargs)
    
    sn = pyqtSignal(int)
    def mousePressEvent(self, QEvent):
        self.sn.emit(10)
        

def denetle(*args, **kwargs):
    pass

qInstallMessageHandler(denetle)             
uygulama = QApplication(sys.argv)
#QApplication.setStyle(QStyleFactory.create("cleanlooks"))
#uygulama.setStyle(QStyleFactory.create("plastique"))
pencere  = FirefoxGuncelleyici()
pencere.show()
uygulama.exec_()
Exemple #28
0
    run_args = setting_instance.settings.pop('args', None)
    if run_args:
        if 'background' in run_args:
            logging.debug("background run!")
            setting_instance.background_run_param = True
            setting_instance.save_cfg()
    try:
        QCoreApplication.setAttribute(Qt.AA_EnableHighDpiScaling, True)
        # 加载的QML文件
        path = 'qrc:/Main.qml' if not qml_path_load else join(dirname(__file__), 'ui', "Main.qml")
        app = QGuiApplication(sys.argv)
        app.setWindowIcon(
            QIcon(':/img/icon.ico') if not qml_path_load else QIcon(
                join(dirname(__file__), 'ui', "img", "icon.ico")))
        qInstallMessageHandler(qml_log)
        engine = QQmlApplicationEngine()
        context = engine.rootContext()
        context.setContextProperty("mysqlServiceManager", mysql_service_manager_instance)
        context.setContextProperty("mysqlConfiguration", mysql_configuration_instance)
        context.setContextProperty("system", system_instance)
        context.setContextProperty("setting", setting_instance)
        context.setContextProperty("aria2", aria2_instance)
        context.setContextProperty("lanzouParse", lanzou_parse_instance)
        context.setContextProperty("sinaT", sina_t_instance)
        context.setContextProperty("crack", crack_instance)
        context.setContextProperty("keyboardListener", keyboard_listener_instance)
        context.setContextProperty("hostEdit", host_edit_instance)
        context.setContextProperty("V2rayManager", v2ray_instance)
        context.setContextProperty("wechatManager", wechat_instance)
        # context.setContextProperty("uploadHandler", upload_instance)
    log_filename_for_today = ObserverLogUtility.get_log_file_name_for_today()
    log_fmt = ObserverLogUtility.get_log_format()
    date_fmt = ObserverLogUtility.get_date_format()
    log_mode_append = 'a'  # Append mode so that all sessions on one day are logged to same file.
    log_level = logging.INFO if ObserverState.getset_setting('logging_level', 'INFO') == 'INFO' else logging.DEBUG
    logging.basicConfig(level=log_level, filename=log_filename_for_today, format=log_fmt, datefmt=date_fmt,
                        filemode=log_mode_append)

    # Also output to console (stderr)
    console = logging.StreamHandler()
    console.setLevel(log_level)
    formatter = logging.Formatter(log_fmt, date_fmt)
    console.setFormatter(formatter)
    logging.getLogger('').addHandler(console)

    qInstallMessageHandler(FramUtil.qt_msg_handler)

    logging.info("-" * 60)  # Separate each session with a horizontal line.
    logging.info(f'OPTECS v{optecs_version} application launched ' + time.strftime("%m/%d/%Y %H:%M"))

    # Move older log files to a subdirectory, excluding today's
    ObserverLogUtility.archive_log_files(exclude=[log_filename_for_today])

    # perform any migrations required prior to run
    migrator = ObserverDBMigrations()
    migrator.perform_migrations()

    connect_orm()  # ObserverORM

    main_qml = QUrl('qrc:/qml/observer/ObserverLogin.qml')
    appGuid = '8284d07e-d07c-4aad-8874-36720e37ce53'
Exemple #30
0
 def _shutdown(self, status):  # noqa
     """Second stage of shutdown."""
     # pylint: disable=too-many-branches, too-many-statements
     # FIXME refactor this
     # https://github.com/The-Compiler/qutebrowser/issues/113
     log.destroy.debug("Stage 2 of shutting down...")
     # Remove eventfilter
     try:
         log.destroy.debug("Removing eventfilter...")
         self.removeEventFilter(self._event_filter)
     except AttributeError:
         pass
     # Close all windows
     QApplication.closeAllWindows()
     # Shut down IPC
     try:
         objreg.get('ipc-server').shutdown()
     except KeyError:
         pass
     # Save everything
     try:
         config_obj = objreg.get('config')
     except KeyError:
         log.destroy.debug("Config not initialized yet, so not saving "
                           "anything.")
     else:
         to_save = []
         if config.get('general', 'auto-save-config'):
             to_save.append(("config", config_obj.save))
             try:
                 key_config = objreg.get('key-config')
             except KeyError:
                 pass
             else:
                 to_save.append(("keyconfig", key_config.save))
         to_save += [("window geometry", self._save_geometry)]
         try:
             command_history = objreg.get('command-history')
         except KeyError:
             pass
         else:
             to_save.append(("command history", command_history.save))
         try:
             quickmark_manager = objreg.get('quickmark-manager')
         except KeyError:
             pass
         else:
             to_save.append(("command history", quickmark_manager.save))
         try:
             state_config = objreg.get('state-config')
         except KeyError:
             pass
         else:
             to_save.append(("window geometry", state_config.save))
         try:
             cookie_jar = objreg.get('cookie-jar')
         except KeyError:
             pass
         else:
             to_save.append(("cookies", cookie_jar.save))
         for what, handler in to_save:
             log.destroy.debug("Saving {} (handler: {})".format(
                 what, utils.qualname(handler)))
             try:
                 handler()
             except AttributeError as e:
                 log.destroy.warning("Could not save {}.".format(what))
                 log.destroy.debug(e)
     # Re-enable faulthandler to stdout, then remove crash log
     log.destroy.debug("Deactiving crash log...")
     self._destroy_crashlogfile()
     # If we don't kill our custom handler here we might get segfaults
     log.destroy.debug("Deactiving message handler...")
     qInstallMessageHandler(None)
     # Now we can hopefully quit without segfaults
     log.destroy.debug("Deferring QApplication::exit...")
     # We use a singleshot timer to exit here to minimize the likelyhood of
     # segfaults.
     QTimer.singleShot(0, functools.partial(self.exit, status))
Exemple #31
0
def start():
    # Install message handler for Qt messages
    qInstallMessageHandler(gui_msg_handler)

    # Start the Qt main object
    app = QApplication([])

    # Start the bluesky network client
    client = GuiClient()

    # Enable HiDPI support (Qt5 only)
    if QT_VERSION >= 0x050000:
        app.setAttribute(Qt.AA_UseHighDpiPixmaps)

    splash = Splash()

    # Register our custom pan/zoom event
    for etype in range(1000, 1000 + NUMCUSTOMEVENTS):
        reg_etype = QEvent.registerEventType(etype)
        if reg_etype != etype:
            print((
                'Warning: Registered event type differs from requested type id (%d != %d)'
                % (reg_etype, etype)))

    splash.show()

    # Install error message handler
    handler = QErrorMessage.qtHandler()
    handler.setWindowFlags(Qt.WindowStaysOnTopHint)

    # Check and set OpenGL capabilities
    if not QGLFormat.hasOpenGL():
        raise RuntimeError('No OpenGL support detected for this system!')
    else:
        f = QGLFormat()
        f.setVersion(3, 3)
        f.setProfile(QGLFormat.CoreProfile)
        f.setDoubleBuffer(True)
        QGLFormat.setDefaultFormat(f)
        print(('QGLWidget initialized for OpenGL version %d.%d' %
               (f.majorVersion(), f.minorVersion())))

    splash.showMessage('Constructing main window')
    app.processEvents()
    win = MainWindow()
    win.show()
    splash.showMessage('Done!')
    app.processEvents()
    splash.finish(win)
    # If this instance of the gui is started in client-only mode, show
    # server selection dialog
    if bs.settings.is_client:
        dialog = DiscoveryDialog(win)
        dialog.show()
        bs.net.start_discovery()

    else:
        client.connect(event_port=bs.settings.event_port,
                       stream_port=bs.settings.stream_port)

    # Start the Qt main loop
    app.exec_()