Example #1
0
def main():

    app = QApplication(sys.argv)
    app.setStyle(QtWidgets.QStyleFactory.create("Fusion"))
    p = app.palette()
    p.setColor(QPalette.Base, QColor(40, 40, 40))
    p.setColor(QPalette.Window, QColor(55, 55, 55))
    p.setColor(QPalette.Button, QColor(49, 49, 49))
    p.setColor(QPalette.Highlight, QColor(135, 135, 135))
    p.setColor(QPalette.ButtonText, QColor(155, 155, 155))
    p.setColor(QPalette.WindowText, QColor(155, 155, 155))
    p.setColor(QPalette.Text, QColor(155, 155, 155))
    p.setColor(QPalette.Disabled, QPalette.Base, QColor(49, 49, 49))
    p.setColor(QPalette.Disabled, QPalette.Text, QColor(90, 90, 90))
    p.setColor(QPalette.Disabled, QPalette.Button, QColor(42, 42, 42))
    p.setColor(QPalette.Disabled, QPalette.ButtonText, QColor(90, 90, 90))
    p.setColor(QPalette.Disabled, QPalette.Window, QColor(49, 49, 49))
    p.setColor(QPalette.Disabled, QPalette.WindowText, QColor(90, 90, 90))
    app.setPalette(p)
    QApplication.addLibraryPath(QApplication.applicationDirPath() + "/../PlugIns")
    main = Window()
    main.setWindowTitle('Detection')
    main.setWindowIcon(QtGui.QIcon('assets/icon.png'))
    main.show()
    try:
        sys.exit(app.exec_())
    except KeyboardInterrupt:
        pass
Example #2
0
def main():

    app = QApplication(sys.argv)
    app.setStyle(QtWidgets.QStyleFactory.create("Fusion"))
    p = app.palette()
    p.setColor(QPalette.Base, QColor(40, 40, 40))
    p.setColor(QPalette.Window, QColor(55, 55, 55))
    p.setColor(QPalette.Button, QColor(49, 49, 49))
    p.setColor(QPalette.Highlight, QColor(135, 135, 135))
    p.setColor(QPalette.ButtonText, QColor(155, 155, 155))
    p.setColor(QPalette.WindowText, QColor(155, 155, 155))
    p.setColor(QPalette.Text, QColor(155, 155, 155))
    p.setColor(QPalette.Disabled, QPalette.Base, QColor(49, 49, 49))
    p.setColor(QPalette.Disabled, QPalette.Text, QColor(90, 90, 90))
    p.setColor(QPalette.Disabled, QPalette.Button, QColor(42, 42, 42))
    p.setColor(QPalette.Disabled, QPalette.ButtonText, QColor(90, 90, 90))
    p.setColor(QPalette.Disabled, QPalette.Window, QColor(49, 49, 49))
    p.setColor(QPalette.Disabled, QPalette.WindowText, QColor(90, 90, 90))
    app.setPalette(p)
    QApplication.addLibraryPath(QApplication.applicationDirPath() +
                                "/../PlugIns")
    main = Window()
    main.setWindowTitle('Detection')
    main.setWindowIcon(QtGui.QIcon('assets/icon.png'))
    main.show()
    try:
        sys.exit(app.exec_())
    except KeyboardInterrupt:
        pass
Example #3
0
    def InitWindow(self):
        path = QApplication.applicationDirPath()
        self.setWindowIcon(QtGui.QIcon('main_icon.jpeg'))
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        self.create_button()
        self.create_label()
Example #4
0
def main():
    # make the Python warnings go to Friture logger
    logging.captureWarnings(True)

    logFormat = "%(asctime)s %(levelname)s %(name)s: %(message)s"
    formatter = logging.Formatter(logFormat)

    logFileName = "friture.log.txt"
    dirs = appdirs.AppDirs("Friture", "")
    logDir = dirs.user_data_dir
    try:
        os.makedirs(logDir)
    except OSError as e:
        if e.errno != errno.EEXIST:
            raise
    logFilePath = os.path.join(logDir, logFileName)

    # log to file
    fileHandler = logging.handlers.RotatingFileHandler(logFilePath,
                                                       maxBytes=100000,
                                                       backupCount=5)
    fileHandler.setLevel(logging.DEBUG)
    fileHandler.setFormatter(formatter)

    rootLogger = logging.getLogger()
    rootLogger.setLevel(logging.DEBUG)
    rootLogger.addHandler(fileHandler)

    if hasattr(sys, "frozen"):
        # redirect stdout and stderr to the logger if this is a pyinstaller bundle
        sys.stdout = StreamToLogger(logging.getLogger('STDOUT'), logging.INFO)
        sys.stderr = StreamToLogger(logging.getLogger('STDERR'), logging.ERROR)
    else:
        # log to console if this is not a pyinstaller bundle
        console = logging.StreamHandler()
        console.setLevel(logging.DEBUG)
        console.setFormatter(formatter)
        rootLogger.addHandler(console)

    # make Qt logs go to Friture logger
    QtCore.qInstallMessageHandler(qt_message_handler)

    logger = logging.getLogger(__name__)

    logger.info("Friture %s starting on %s (%s)", friture.__version__,
                platform.system(), sys.platform)

    # make sure Qt loads the desktop OpenGL stack, rather than OpenGL ES or a software OpenGL
    # only the former option is compatible with the use of PyOpenGL
    QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_UseDesktopOpenGL)

    if platform.system() == "Windows":
        logger.info("Applying Windows-specific setup")

        # enable automatic scaling for high-DPI screens
        os.environ["QT_AUTO_SCREEN_SCALE_FACTOR"] = "1"

        # set the App ID for Windows 7 to properly display the icon in the
        # taskbar.
        import ctypes
        myappid = 'Friture.Friture.Friture.current'  # arbitrary string
        try:
            ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(
                myappid)
        except:
            logger.error(
                "Could not set the app model ID. If the plaftorm is older than Windows 7, this is normal."
            )

    app = QApplication(sys.argv)

    if platform.system() == "Darwin":
        logger.info("Applying Mac OS-specific setup")
        # help the packaged application find the Qt plugins (imageformats and platforms)
        pluginsPath = os.path.normpath(
            os.path.join(QApplication.applicationDirPath(), os.path.pardir,
                         'PlugIns'))
        logger.info("Adding the following to the Library paths: %s",
                    pluginsPath)
        QApplication.addLibraryPath(pluginsPath)

        # on macOS, OpenGL 2.1 does not work well
        # request a 3.2 Core context instead
        format = QSurfaceFormat()
        format.setDepthBufferSize(24)
        format.setStencilBufferSize(8)
        format.setVersion(3, 2)
        format.setProfile(QSurfaceFormat.CoreProfile)
        QSurfaceFormat.setDefaultFormat(format)

    # Splash screen
    #pixmap = QPixmap(":/images/splash.png")
    #splash = QSplashScreen(pixmap)
    #splash.show()
    #splash.showMessage("Initializing the audio subsystem")
    app.processEvents()

    window = Friture()
    window.show()
    #splash.finish(window)

    profile = "no"  # "python" or "kcachegrind" or anything else to disable

    if len(sys.argv) > 1:
        if sys.argv[1] == "--python":
            profile = "python"
        elif sys.argv[1] == "--kcachegrind":
            profile = "kcachegrind"
        elif sys.argv[1] == "--no":
            profile = "no"
        else:
            logger.info("command-line arguments (%s) not recognized",
                        sys.argv[1:])

    return_code = 0
    if profile == "python":
        import cProfile
        import pstats

        # friture.cprof can be visualized with SnakeViz
        # http://jiffyclub.github.io/snakeviz/
        # snakeviz friture.cprof
        cProfile.runctx('app.exec_()',
                        globals(),
                        locals(),
                        filename="friture.cprof")

        logger.info("Profile saved to '%s'", "friture.cprof")

        stats = pstats.Stats("friture.cprof")
        stats.strip_dirs().sort_stats('time').print_stats(20)
        stats.strip_dirs().sort_stats('cumulative').print_stats(20)
    elif profile == "kcachegrind":
        import cProfile
        import lsprofcalltree

        p = cProfile.Profile()
        p.run('app.exec_()')

        k = lsprofcalltree.KCacheGrind(p)
        with open('cachegrind.out.00000', 'wb') as data:
            k.output(data)
    else:
        return_code = app.exec_()

    # explicitly delete the main windows instead of waiting for the interpreter shutdown
    # tentative to prevent errors on exit on macos
    del window

    sys.exit(return_code)
Example #5
0
def main():
    print("Platform is %s (%s)" %(platform.system(), sys.platform))

    if platform.system() == "Windows":
        print("Applying Windows-specific setup")
        # On Windows, redirect stderr to a file
        import imp
        import ctypes
        if (hasattr(sys, "frozen") or  # new py2exe
                hasattr(sys, "importers") or  # old py2exe
                imp.is_frozen("__main__")):  # tools/freeze
            sys.stderr = open(os.path.expanduser("~/friture.exe.log"), "w")
        # set the App ID for Windows 7 to properly display the icon in the
        # taskbar.
        myappid = 'Friture.Friture.Friture.current'  # arbitrary string
        try:
            ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(myappid)
        except:
            print("Could not set the app model ID. If the plaftorm is older than Windows 7, this is normal.")

    app = QApplication(sys.argv)

    if platform.system() == "Darwin":
        if hasattr(sys, "frozen"): #py2app
            sys.stdout = open(os.path.expanduser("~/friture.out.txt"), "w")
            sys.stderr = open(os.path.expanduser("~/friture.err.txt"), "w")

        print("Applying Mac OS-specific setup")
        # help the py2app-packaged application find the Qt plugins (imageformats and platforms)
        pluginsPath = os.path.normpath(os.path.join(QApplication.applicationDirPath(), os.path.pardir, 'PlugIns'))
        print("Adding the following to the Library paths: " + pluginsPath)
        QApplication.addLibraryPath(pluginsPath)

    # Splash screen
    pixmap = QPixmap(":/images/splash.png")
    splash = QSplashScreen(pixmap)
    splash.show()
    splash.showMessage("Initializing the audio subsystem")
    app.processEvents()

    # Logger class
    logger = Logger()

    window = Friture(logger)
    window.show()
    splash.finish(window)

    profile = "no"  # "python" or "kcachegrind" or anything else to disable

    if len(sys.argv) > 1:
        if sys.argv[1] == "--python":
            profile = "python"
        elif sys.argv[1] == "--kcachegrind":
            profile = "kcachegrind"
        elif sys.argv[1] == "--no":
            profile = "no"
        else:
            print("command-line arguments (%s) not recognized" % sys.argv[1:])

    if profile == "python":
        import cProfile
        import pstats

        cProfile.runctx('app.exec_()', globals(), locals(), filename="friture.cprof")

        stats = pstats.Stats("friture.cprof")
        stats.strip_dirs().sort_stats('time').print_stats(20)
        stats.strip_dirs().sort_stats('cumulative').print_stats(20)

        sys.exit(0)
    elif profile == "kcachegrind":
        import cProfile
        import lsprofcalltree

        p = cProfile.Profile()
        p.run('app.exec_()')

        k = lsprofcalltree.KCacheGrind(p)
        with open('cachegrind.out.00000', 'wb') as data:
            k.output(data)

        sys.exit(0)
    else:
        sys.exit(app.exec_())
Example #6
0
def main():
    print("Platform is %s (%s)" % (platform.system(), sys.platform))

    if platform.system() == "Windows":
        print("Applying Windows-specific setup")
        # On Windows, redirect stderr to a file
        import imp
        import ctypes
        if (hasattr(sys, "frozen") or  # new py2exe
                hasattr(sys, "importers") or  # old py2exe
                imp.is_frozen("__main__")):  # tools/freeze
            sys.stderr = open(os.path.expanduser("~/friture.exe.log"), "w")
        # set the App ID for Windows 7 to properly display the icon in the
        # taskbar.
        myappid = 'Friture.Friture.Friture.current'  # arbitrary string
        try:
            ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(
                myappid)
        except:
            print(
                "Could not set the app model ID. If the plaftorm is older than Windows 7, this is normal."
            )

    app = QApplication(sys.argv)

    if platform.system() == "Darwin":
        if hasattr(sys, "frozen"):  #py2app
            sys.stdout = open(os.path.expanduser("~/friture.out.txt"), "w")
            sys.stderr = open(os.path.expanduser("~/friture.err.txt"), "w")

        print("Applying Mac OS-specific setup")
        # help the py2app-packaged application find the Qt plugins (imageformats and platforms)
        pluginsPath = os.path.normpath(
            os.path.join(QApplication.applicationDirPath(), os.path.pardir,
                         'PlugIns'))
        print("Adding the following to the Library paths: " + pluginsPath)
        QApplication.addLibraryPath(pluginsPath)

    # Splash screen
    pixmap = QPixmap(":/images/splash.png")
    splash = QSplashScreen(pixmap)
    splash.show()
    splash.showMessage("Initializing the audio subsystem")
    app.processEvents()

    # Logger class
    logger = Logger()

    window = Friture(logger)
    window.show()
    splash.finish(window)

    profile = "no"  # "python" or "kcachegrind" or anything else to disable

    if len(sys.argv) > 1:
        if sys.argv[1] == "--python":
            profile = "python"
        elif sys.argv[1] == "--kcachegrind":
            profile = "kcachegrind"
        elif sys.argv[1] == "--no":
            profile = "no"
        else:
            print("command-line arguments (%s) not recognized" % sys.argv[1:])

    if profile == "python":
        import cProfile
        import pstats

        cProfile.runctx('app.exec_()',
                        globals(),
                        locals(),
                        filename="friture.cprof")

        stats = pstats.Stats("friture.cprof")
        stats.strip_dirs().sort_stats('time').print_stats(20)
        stats.strip_dirs().sort_stats('cumulative').print_stats(20)

        sys.exit(0)
    elif profile == "kcachegrind":
        import cProfile
        import lsprofcalltree

        p = cProfile.Profile()
        p.run('app.exec_()')

        k = lsprofcalltree.KCacheGrind(p)
        with open('cachegrind.out.00000', 'wb') as data:
            k.output(data)

        sys.exit(0)
    else:
        sys.exit(app.exec_())
Example #7
0
File: app.py Project: yhnu/mmgui
class App(Context):
    def __init__(self,
                 headless: bool = False,
                 icon_file=None,
                 splash_file=None,
                 splash_text=None,
                 configs_file=None,
                 log_file=None):
        self._headless = headless
        self._configs_file = configs_file
        self._icon_file = icon_file
        self._splash_file = splash_file
        self._splash_text = splash_text
        self._log_file = log_file
        self._settings: QSettings = None
        self._qt_application = None
        self._events_callback = {"create": [], "destroy": []}

    def on(self, event: str, callback: Callable[[Context], None]) -> NoReturn:
        if event not in self._events_callback:
            raise Exception("unsupported event %s" % event)
        self._events_callback[event].append(callback)

    def _notify_callback(self, event: str) -> NoReturn:
        if event not in self._events_callback:
            raise Exception("unsupported event %s" % event)
        for callback in self._events_callback[event]:
            callback(self)

    def on_create(self) -> NoReturn:
        self._notify_callback("create")

    def on_destroy(self) -> NoReturn:
        self._notify_callback("destroy")

    def run(self) -> int:
        setup_stdio()
        setup_console()
        run_as_job()

        argv = sys.argv[:]
        if self._headless:
            self._qt_application = QCoreApplication(argv)  # Non-GUI
            signal.signal(signal.SIGINT,
                          lambda *a: self._qt_application.quit())
        else:
            self._qt_application = QApplication(argv)

        # icon
        if self._icon_file:
            self._window_icon = QtGui.QIcon(self._icon_file)
            self._qt_application.setWindowIcon(self._window_icon)

        # splash
        if self._splash_file:
            pixmap = QtGui.QPixmap(self._splash_file)
            self._splash = QSplashScreen(pixmap)
            if self._splash_text:
                self._set_splash_text(self._splash_text, "#ffffff")
            self._splash.show()

        # asyncqt
        asyncqt_ui_thread_loop.start_loop()

        # configs
        if self._configs_file:
            self._settings = QSettings(self._configs_file, QSettings.IniFormat)
            self._settings.sync()

        # log
        if self._log_file:
            logfp = open(self._log_file, 'w')
            STDERR_STREAMS.add(logfp)
            STDOUT_STREAMS.add(logfp)

        self._qt_application.aboutToQuit.connect(self._on_quit)
        self.on_create()  # -> create and show the WebView window
        exit_code = self._qt_application.exec_()
        self._qt_application.deleteLater()
        return exit_code
        #sys.exit(exit_code)

    def _set_splash_text(self, text, color):
        self._splash.showMessage(text,
                                 alignment=QtCore.Qt.AlignHCenter
                                 | QtCore.Qt.AlignBottom,
                                 color=QtGui.QColor(color))

    def set_main_window(self, window):
        if window:
            self._splash.finish(window)
            window.setWindowIcon(self._window_icon)

    def get_config(self, key, def_val=None):
        if self._settings:
            return self._settings.value(key, def_val)
        return def_val

    def _on_quit(self):
        self.on_destroy()

    def exit(self) -> NoReturn:
        self._qt_application.quit()

    def get_application_dir_path(self):
        return self._qt_application.applicationDirPath()