Example #1
0
def main():
    QApplication.setApplicationName("Blender Version Manager")
    QApplication.setApplicationVersion("1.5.1")

    app = QApplication(sys.argv)

    proc_count = len([
        proc for proc in psutil.process_iter()
        if proc.name() == "Blender Version Manager.exe"
    ])

    if proc_count > 2:
        msg = QMessageBox()
        msg.setIcon(QMessageBox.Warning)
        msg.setWindowIcon(QIcon(":/icons/app.svg"))
        msg.setText(
            "One instance of Blender Version Manager \nis already running!")
        msg.setWindowTitle("Blender Version Manager")
        msg.setStandardButtons(QMessageBox.Ok)
        msg.exec_()
    else:
        window = BVMQMainWindow(app)
        window.setWindowFlags(Qt.FramelessWindowHint)

        if not window.is_run_minimized:
            window.show()

        app.exec_()
Example #2
0
def init_app(argv=None, gui=True):
    """
    Initialize qt runtime, deal with common issues (such as installing an
    exception handler), and return a ``QApplication`` object. If ``gui`` is
    false, return a ``QCoreApplication`` instead.
    """
    warnings.filterwarnings(
        "default", module='(madgui|cpymad|minrpc|pydicti).*')
    set_app_id('hit.madgui')
    init_stdio()
    # QApplication needs a valid argument list:
    if argv is None:
        argv = sys.argv
    if gui:
        from PyQt5.QtWidgets import QApplication
        from madgui.util.qt import load_icon_resource
        from importlib_resources import read_text
        app = QApplication(argv)
        app.setWindowIcon(load_icon_resource('madgui.data', 'icon.xpm'))
        app.setStyleSheet(read_text('madgui.data', 'style.css'))
        # matplotlib must be imported *after* Qt;
        # must be selected before importing matplotlib.backends:
        import matplotlib
        matplotlib.use('Qt5Agg')
    else:
        app = QCoreApplication(argv)
    app.setApplicationName('madgui')
    app.setApplicationVersion(__version__)
    app.setOrganizationName('HIT Betriebs GmbH')
    app.setOrganizationDomain('https://www.klinikum.uni-heidelberg.de/hit')
    # Print uncaught exceptions. This changes the default behaviour on PyQt5,
    # where an uncaught exception would usually cause the program to abort.
    sys.excepthook = traceback.print_exception
    setup_interrupt_handling(app)
    return app
Example #3
0
    def monitor(self):
        """Launch a table view of fields and field statistics."""
        auth = self.get_auth()
        race_id = self.args.race_id

        race_list = get_race_list(auth)
        matching_race_list = list(
            filter(lambda race: fnmatch.fnmatchcase(race['id'], race_id),
                   race_list))
        if len(matching_race_list) > 1:
            sys.stderr.write(
                'Ambiguous race id %s, can match: %s.\n' % (race_id, ', '.join(
                    map(lambda race: race['id'], matching_race_list))))
            sys.exit(-1)
        race = matching_race_list[0]

        QApplication.setOrganizationName(common.ORGANIZATION_NAME)
        QApplication.setOrganizationDomain(common.ORGANIZATION_DOMAIN)
        QApplication.setApplicationName(common.APPLICATION_NAME)
        QApplication.setApplicationVersion(common.VERSION)

        app = QApplication(sys.argv)

        main_window = FieldStatisticsTable(auth, race,
                                           self.args.monitor_interval)
        main_window.show()
        retcode = app.exec_()

        main_window.close()
        sys.exit(retcode)
Example #4
0
def start_gui():
    logger = core.logger.get_logger(__name__)
    logger.info('Qt gui starting, PyQt5 version: {}; sip version: {}'.format(
        PYQT_VERSION_STR, sip.SIP_VERSION_STR))

    sip.setdestroyonexit(False)
    ver = version.get_pyevemon_version()

    # flags are usually set BEFORE app object is created
    QCoreApplication.setAttribute(Qt.AA_EnableHighDpiScaling, True)

    app = QApplication(sys.argv)
    app.setApplicationVersion(ver['version'])
    app.setApplicationName(ver['app_name'])
    app.setApplicationDisplayName(ver['app_displayname'])
    app.setOrganizationDomain(ver['app_domain'])
    app.setOrganizationName(ver['author_name'])

    # print(app.applicationName(), app.applicationDirPath(), app.applicationPid())
    # print(app.applicationDisplayName(), app.applicationVersion())

    # do not forget to start ESI auth callback receiver
    core.esi_handler.esi_handler_start()

    mainwindow = gui_qt.mainwindow.QtEmMainWindow()
    mainwindow.show()

    return app.exec_()
Example #5
0
def main():
    # DBUS MainLoop
    if not dbus.get_default_main_loop():
        from dbus.mainloop.pyqt5 import DBusQtMainLoop
        DBusQtMainLoop(set_as_default=True)

    # Application Stuff
    from libhistorymanager.window import MainManager

    app = QApplication(sys.argv)
    app.setOrganizationName("history-manager")
    app.setApplicationName("history-manager")
    app.setApplicationVersion("0.2.8b")

    locale = QLocale.system().name()
    translator = QTranslator(app)
    translator.load(
        join("/usr/share/history-manager", "languages/{}.qm".format(locale)))
    app.installTranslator(translator)

    # Create Main Widget and make some settings
    mainWindow = MainManager(None, app=app)
    mainWindow.resize(640, 480)
    mainWindow.setWindowIcon(QIcon.fromTheme("view-history"))
    mainWindow.show()

    # Create connection for lastWindowClosed signal to quit app
    app.lastWindowClosed.connect(app.quit)

    # Run the applications
    app.exec_()
Example #6
0
    def initUI(self):
        self.setAttribute(Qt.WA_DeleteOnClose)
        self.spliter = QSplitter(Qt.Vertical)
        self.spliter.addWidget(TestUnitArea())
        self.spliter.addWidget(TestResultArea())
        self.spliter.setHandleWidth(1)
        self.setCentralWidget(self.spliter)

        tool_menu = QMenu('工具', self.menuBar())
        tool_menu.addAction('数据监听', self.onDebugWindow)
        tool_menu.addAction('单步测试', self.onSingleStep)
        tool_menu.addAction('记录查询', self.onViewData)
        tool_menu.addAction('条码打印', self.onPrintBarCode)
        tool_menu.addAction('异常信息', self.onExceptionWindow)

        setting_menu = QMenu('选项', self.menuBar())
        setting_menu.addAction('参数设置', self.onSetting)
        # setting_menu.addAction('软件重启', self.onRestart)

        help_menu = QMenu('帮助', self.menuBar())
        help_menu.addAction('关于', self.onAbout)

        self.menuBar().addMenu(setting_menu)
        self.menuBar().addMenu(tool_menu)
        self.menuBar().addMenu(help_menu)

        QApplication.setWindowIcon(QIcon(Config.LOGO_IMG))
        QApplication.instance().aboutToQuit.connect(self.onApplicationQuit)
        QApplication.setOrganizationName(Config.ORGANIZATION)
        QApplication.setApplicationName(Config.APP_NAME)
        QApplication.setApplicationVersion(Config.APP_VERSION)
        self.restoreQSettings()
        self.createSystemTray()
Example #7
0
def main(argv):
    app = QApplication(argv)
    app.setApplicationName("Githost")
    app.setApplicationVersion(qWebKitVersion())
    win = MainWindow()
    win.show()
    sys.exit(app.exec_())
Example #8
0
def main():
    """The main() function creates the main window and starts the event loop."""
    parser = argparse.ArgumentParser(description=common.APPLICATION_NAME)
    parser.add_argument('--version',
                        action='version',
                        version=common.APPLICATION_NAME + ' v' +
                        common.VERSION)
    parser.add_argument('racefile',
                        nargs='?',
                        help='Optional racefile to load')
    args = parser.parse_args()

    QApplication.setOrganizationName(common.ORGANIZATION_NAME)
    QApplication.setOrganizationDomain(common.ORGANIZATION_DOMAIN)
    QApplication.setApplicationName(common.APPLICATION_NAME)
    QApplication.setApplicationVersion(common.VERSION)

    app = QApplication(sys.argv)

    # Set our current working directory to the documents folder. We need to do this because running
    # a pyinstaller version of this app has the current working directory as "/" (at least, on OS X)
    # which is always wrong. Therefore, always just start it off at somewhere sane and writable.
    os.chdir(common.get_documents_dir())

    main_window = TimingCatMainWindow(filename=args.racefile)
    main_window.show()

    sys.exit(app.exec_())
Example #9
0
def new_qt_application(app_config: dict,
                       logger: Logger,
                       quit_on_last_closed: bool = False,
                       name: str = None) -> QApplication:
    app = QApplication(sys.argv)
    app.setQuitOnLastWindowClosed(
        quit_on_last_closed
    )  # otherwise windows opened through the tray icon kill the application when closed
    app.setApplicationName(name if name else __app_name__)
    app.setApplicationVersion(__version__)
    app.setWindowIcon(util.get_default_icon()[1])

    if app_config['ui']['qt_style']:
        app.setStyle(str(app_config['ui']['qt_style']))
    else:
        app.setStyle('fusion')

    app.setProperty('qt_style', app.style().objectName().lower())

    theme_key = app_config['ui']['theme'].strip(
    ) if app_config['ui']['theme'] else None
    set_theme(theme_key=theme_key, app=app, logger=logger)

    if not app_config['ui']['system_theme']:
        app.setPalette(app.style().standardPalette())

    return app
Example #10
0
def main():
    raise Exception("x", "x")
    QApplication.setApplicationName("Blender Version Manager")
    QApplication.setApplicationVersion("1.5.1")

    app = QApplication(sys.argv)

    proc_count = len([
        proc for proc in psutil.process_iter()
        if proc.name() == "Blender Version Manager.exe"
    ])

    if proc_count > 2:
        msg = QMessageBox(QMessageBox.Warning, "Blender Version Manager",
                          "Another instance is already running!",
                          QMessageBox.Ok)
        msg.setWindowIcon(QIcon(":/icons/app.svg"))
        msg.exec_()
    else:
        window = BVMQMainWindow(app, get_platform())

        if not window.is_run_minimized:
            window.show()

        app.exec_()
def main():
    # DBUS MainLoop
    if not dbus.get_default_main_loop():
        from dbus.mainloop.pyqt5 import DBusQtMainLoop
        DBusQtMainLoop(set_as_default = True)


    # Application Stuff
    from libhistorymanager.window import MainManager

    app = QApplication(sys.argv)
    app.setOrganizationName("history-manager")
    app.setApplicationName("history-manager")
    app.setApplicationVersion("0.2.8b")

    locale = QLocale.system().name()
    translator = QTranslator(app)
    translator.load(join("/usr/share/history-manager", "languages/{}.qm".format(locale)))
    app.installTranslator(translator)

    # Create Main Widget and make some settings
    mainWindow = MainManager(None, app= app)
    mainWindow.resize(640, 480)
    mainWindow.setWindowIcon(QIcon.fromTheme("view-history"))
    mainWindow.show()

    # Create connection for lastWindowClosed signal to quit app
    app.lastWindowClosed.connect(app.quit)

    # Run the applications
    app.exec_()
Example #12
0
    def __init__(self):
        # Initialize
        app = QApplication(sys.argv)
        app.setApplicationName("eKalappai")
        app.setApplicationVersion("4.0.0")
        shared = QSharedMemory("59698760-43bb-44d9-8121-181ecbb70e4d")

        # Check if already another instance of app is running and quit if it is
        if not shared.create(512, QSharedMemory.ReadWrite):
            qWarning("Cannot start more than one instance of eKalappai any time.")
            exit(0)

        # Splash Screen init
        splashImage = QPixmap(':intro/splash_screen')
        splashScreen = QSplashScreen(splashImage)
        splashScreen.show()
        # Time wait for splash screen to be shown
        time.sleep(2)
        splashScreen.hide()

        # Main application starting
        QApplication.setQuitOnLastWindowClosed(False)
        ekWindow = EKWindow(app)

        # EK Engine start
        ekWindow.engine.start()
        
        sys.exit(app.exec_())
Example #13
0
def main():
    if hasattr(Qt, 'AA_EnableHighDpiScaling'):
        QCoreApplication.setAttribute(Qt.AA_EnableHighDpiScaling, True)
    if hasattr(Qt, 'AA_Use96Dpi'):
        QCoreApplication.setAttribute(Qt.AA_Use96Dpi, True)
    if hasattr(Qt, 'AA_ShareOpenGLContexts'):
        QCoreApplication.setAttribute(Qt.AA_ShareOpenGLContexts, True)

    if sys.platform == 'darwin':
        QApplication.setStyle('Fusion')

    app = QApplication(sys.argv)
    app.setApplicationName('VidCutter Special HD Ver.')
    app.setApplicationVersion(MainWindow.get_version())
    app.setOrganizationDomain('ozmartians.com')
    app.setQuitOnLastWindowClosed(True)

    win = MainWindow()
    exit_code = app.exec_()
    if exit_code == MainWindow.EXIT_CODE_REBOOT:
        if sys.platform == 'win32':
            if hasattr(win.cutter, 'mpvWidget'):
                win.close()
            QProcess.startDetached('"%s"' % qApp.applicationFilePath())
        else:
            os.execl(sys.executable, sys.executable, *sys.argv)
    sys.exit(exit_code)
Example #14
0
def main():
    app = QApplication(sys.argv)
    app.setAttribute(Qt.AA_UseHighDpiPixmaps)

    app.setOrganizationName(ORG_NAME)
    app.setOrganizationDomain(ORG_DOMAIN)
    app.setApplicationName(APP_NAME.replace(' ', '_').lower())
    app.setApplicationVersion(VERSION)

    log_window = LogWindow()
    logger = logging.getLogger()
    logger.setLevel(logging.INFO)
    logger.addHandler(log_window)
    logger.addHandler(logging.StreamHandler(stream=sys.stdout))

    log = logging.getLogger(__name__)
    log.info('Launching {}, version {}, git hash: {}'.format(
        APP_NAME, VERSION, GITHASH))

    main_window = MainWindow(log_window)
    paths = [pathlib.Path(p) for p in sys.argv[1:]]
    pnt_files = [p for p in paths if p.is_file() and p.suffix == '.pnt']
    for f in pnt_files:
        log.info('Opening file {}'.format(f))
        main_window.open_pnts([f])

    main_window.show()

    sys.exit(app.exec())
Example #15
0
def run():
    """
    Creates all the top-level assets for the application, sets things up and
    then runs the application. Specific tasks include:

    - set up logging
    - create an application object
    - create an editor window and status bar
    - display a splash screen while starting
    - close the splash screen after startup timer ends
    """
    setup_logging()
    logging.info('\n\n-----------------\n\nStarting Mu {}'.format(__version__))
    logging.info(platform.uname())
    logging.info('Python path: {}'.format(sys.path))

    # The app object is the application running on your computer.
    app = QApplication(sys.argv)
    # By default PyQt uses the script name (run.py)
    app.setApplicationName('mu')
    # Set hint as to the .desktop files name
    app.setDesktopFileName('mu.codewith.editor')
    app.setApplicationVersion(__version__)
    app.setAttribute(Qt.AA_DontShowIconsInMenus)
    # Images (such as toolbar icons) aren't scaled nicely on retina/4k displays
    # unless this flag is set
    app.setAttribute(Qt.AA_UseHighDpiPixmaps)

    # Create the "window" we'll be looking at.
    editor_window = Window()
    # Make sure all windows have the Mu icon as a fallback
    app.setWindowIcon(load_icon(editor_window.icon))
    # Create the "editor" that'll control the "window".
    editor = Editor(view=editor_window)
    editor.setup(setup_modes(editor, editor_window))
    # Setup the window.
    editor_window.closeEvent = editor.quit
    editor_window.setup(editor.debug_toggle_breakpoint, editor.theme)
    # Restore the previous session along with files passed by the os
    editor.restore_session(sys.argv[1:])
    # Connect the various UI elements in the window to the editor.
    editor_window.connect_tab_rename(editor.rename_tab, 'Ctrl+Shift+S')
    editor_window.connect_find_replace(editor.find_replace, 'Ctrl+F')
    editor_window.connect_find_replace(editor.toggle_comments, 'Ctrl+K')
    status_bar = editor_window.status_bar
    status_bar.connect_logs(editor.show_admin, 'Ctrl+Shift+D')

    # Display a friendly "splash" icon.
    splash = QSplashScreen(load_pixmap('splash-screen'))
    splash.show()

    # Hide the splash icon.
    splash_be_gone = QTimer()
    splash_be_gone.timeout.connect(lambda: splash.finish(editor_window))
    splash_be_gone.setSingleShot(True)
    splash_be_gone.start(2000)

    # Stop the program after the application finishes executing.
    sys.exit(app.exec_())
Example #16
0
def main():
    app = QApplication(sys.argv)
    app.setApplicationName("Icons")
    app.setApplicationVersion("1.0")
    mainWin = MainWindow()
    mainWin.show()

    return app.exec_()
Example #17
0
def main():
    app = QApplication(sys.argv)
    app.setApplicationName('VidCutter')
    app.setApplicationVersion(MainWindow.get_version())
    app.setOrganizationDomain('http://vidcutter.ozmartians.com')
    app.setQuitOnLastWindowClosed(True)
    win = MainWindow()
    sys.exit(app.exec_())
Example #18
0
def main():
	if markups.__version_tuple__ < (2, ):
		sys.exit('Error: ReText needs PyMarkups 2.0 or newer to run.')

	# If we're running on Windows without a console, then discard stdout
	# and save stderr to a file to facilitate debugging in case of crashes.
	if sys.executable.endswith('pythonw.exe'):
		sys.stdout = open(devnull, 'w')
		sys.stderr = open('stderr.log', 'w')

	app = QApplication(sys.argv)
	app.setOrganizationName("ReText project")
	app.setApplicationName("ReText")
	app.setApplicationDisplayName("ReText")
	app.setApplicationVersion(app_version)
	app.setOrganizationDomain('mitya57.me')
	if hasattr(app, 'setDesktopFileName'): # available since Qt 5.7
		app.setDesktopFileName('me.mitya57.ReText.desktop')
	QNetworkProxyFactory.setUseSystemConfiguration(True)
	RtTranslator = QTranslator()
	for path in datadirs:
		if RtTranslator.load('retext_' + globalSettings.uiLanguage,
		                     join(path, 'locale')):
			break
	QtTranslator = QTranslator()
	QtTranslator.load("qtbase_" + globalSettings.uiLanguage,
		QLibraryInfo.location(QLibraryInfo.TranslationsPath))
	app.installTranslator(RtTranslator)
	app.installTranslator(QtTranslator)
	print('Using configuration file:', settings.fileName())
	if globalSettings.appStyleSheet:
		sheetfile = QFile(globalSettings.appStyleSheet)
		sheetfile.open(QIODevice.ReadOnly)
		app.setStyleSheet(QTextStream(sheetfile).readAll())
		sheetfile.close()
	window = ReTextWindow()
	window.show()
	# ReText can change directory when loading files, so we
	# need to have a list of canonical names before loading
	fileNames = list(map(canonicalize, sys.argv[1:]))
	previewMode = False
	for fileName in fileNames:
		if QFile.exists(fileName):
			window.openFileWrapper(fileName)
			if previewMode:
				window.actionPreview.setChecked(True)
				window.preview(True)
		elif fileName == '--preview':
			previewMode = True
	if globalSettings.openLastFilesOnStartup:
		window.restoreLastOpenedFiles()

	inputData = '' if (sys.stdin is None or sys.stdin.isatty()) else sys.stdin.read()
	if inputData or not window.tabWidget.count():
		window.createNew(inputData)
	signal.signal(signal.SIGINT, lambda sig, frame: window.close())
	sys.exit(app.exec())
Example #19
0
def set_app_display_metadata(app: QtWidgets.QApplication) -> None:
    with resources.open_binary(speedwagon.__name__, "favicon.ico") as icon:
        app.setWindowIcon(QtGui.QIcon(icon.name))
    try:
        app.setApplicationVersion(metadata.version(__package__))
    except metadata.PackageNotFoundError:
        pass
    app.setApplicationDisplayName(f"{speedwagon.__name__.title()}")
    QtWidgets.QApplication.processEvents()
Example #20
0
def main():
    app = QApplication(sys.argv)
    app.setStyle(OverrideStyle())
    app.setApplicationName(FixedSettings.applicationName)
    app.setOrganizationDomain(FixedSettings.organizationDomain)
    app.setApplicationVersion(FixedSettings.applicationVersion)
    app.setQuitOnLastWindowClosed(True)
    tvlinker = TVLinker(FixedSettings.get_app_settings())
    sys.exit(app.exec_())
Example #21
0
def main():

    app = QApplication(sys.argv)
    app.setOrganizationName("Pisi Linux")
    app.setApplicationName("Pisi Player")
    app.setApplicationVersion("0.9")
    pisiplayer = PisiPlayer()
    pisiplayer.show()

    sys.exit(app.exec_())
Example #22
0
def main():

    app = QApplication(sys.argv)
    app.setOrganizationName("Pisi Linux")
    app.setApplicationName("Pisi Player")
    app.setApplicationVersion("0.9")
    pisiplayer = PisiPlayer()
    pisiplayer.show()

    sys.exit(app.exec_())
Example #23
0
 def app(self):
     """
     The global Qt QApplication object for your app. Feel free to overwrite
     this property, eg. if you wish to use your own subclass of QApplication.
     An example of this is given in the Manual.
     """
     result = QApplication([])
     result.setApplicationName(self.build_settings['app_name'])
     result.setApplicationVersion(self.build_settings['version'])
     return result
Example #24
0
def app():
    app = QApplication(sys.argv)
    app.setApplicationName('CuriElements')
    app.setApplicationDisplayName('CuriElements')
    app.setOrganizationName('CodeHuntersLab')
    app.setOrganizationDomain('CodeHuntersLab.com')
    app.setApplicationVersion('1.0')
    w = CuriWidget()
    w.show()
    sys.exit(app.exec_())
Example #25
0
def main():
    app = QApplication(sys.argv)
    app.setApplicationVersion(__version__)
    app.setApplicationName(__appname__)
    app.setDesktopFileName(__desktopid__)

    window = MainWindow()
    configure_theme(app)
    window.show()
    sys.exit(app.exec_())
Example #26
0
def instantiate():
    """Instantiate the global QApplication object."""
    global qApp
    args = list(map(os.fsencode, [os.path.abspath(sys.argv[0])] + sys.argv[1:]))
    qApp = QApplication(args)
    QApplication.setApplicationName(appinfo.name)
    QApplication.setApplicationVersion(appinfo.version)
    QApplication.setOrganizationName(appinfo.name)
    QApplication.setOrganizationDomain(appinfo.domain)
    appInstantiated()
Example #27
0
def instantiate():
    """Instantiate the global QApplication object."""
    global qApp
    args = list(map(os.fsencode,
                    [os.path.abspath(sys.argv[0])] + sys.argv[1:]))
    qApp = QApplication(args)
    QApplication.setApplicationName(appinfo.name)
    QApplication.setApplicationVersion(appinfo.version)
    QApplication.setOrganizationName(appinfo.name)
    QApplication.setOrganizationDomain(appinfo.domain)
    appInstantiated()
Example #28
0
def main():
	if markups.__version_tuple__ < (2, ):
		sys.exit('Error: ReText needs PyMarkups 2.0 or newer to run.')

	# If we're running on Windows without a console, then discard stdout
	# and save stderr to a file to facilitate debugging in case of crashes.
	if sys.executable.endswith('pythonw.exe'):
		sys.stdout = open(devnull, 'w')
		sys.stderr = open('stderr.log', 'w')

	app = QApplication(sys.argv)
	app.setOrganizationName("ReText project")
	app.setApplicationName("ReText")
	app.setApplicationDisplayName("ReText")
	app.setApplicationVersion(app_version)
	app.setOrganizationDomain('mitya57.me')
	if hasattr(app, 'setDesktopFileName'): # available since Qt 5.7
		app.setDesktopFileName('me.mitya57.ReText.desktop')
	QNetworkProxyFactory.setUseSystemConfiguration(True)
	RtTranslator = QTranslator()
	for path in datadirs:
		if RtTranslator.load('retext_' + globalSettings.uiLanguage,
		                     join(path, 'locale')):
			break
	QtTranslator = QTranslator()
	QtTranslator.load("qt_" + globalSettings.uiLanguage,
		QLibraryInfo.location(QLibraryInfo.TranslationsPath))
	app.installTranslator(RtTranslator)
	app.installTranslator(QtTranslator)
	print('Using configuration file:', settings.fileName())
	if globalSettings.appStyleSheet:
		sheetfile = QFile(globalSettings.appStyleSheet)
		sheetfile.open(QIODevice.ReadOnly)
		app.setStyleSheet(QTextStream(sheetfile).readAll())
		sheetfile.close()
	window = ReTextWindow()
	window.show()
	# ReText can change directory when loading files, so we
	# need to have a list of canonical names before loading
	fileNames = list(map(canonicalize, sys.argv[1:]))
	previewMode = False
	for fileName in fileNames:
		if QFile.exists(fileName):
			window.openFileWrapper(fileName)
			if previewMode:
				window.actionPreview.setChecked(True)
				window.preview(True)
		elif fileName == '--preview':
			previewMode = True
	inputData = '' if (sys.stdin is None or sys.stdin.isatty()) else sys.stdin.read()
	if inputData or not window.tabWidget.count():
		window.createNew(inputData)
	signal.signal(signal.SIGINT, lambda sig, frame: window.close())
	sys.exit(app.exec())
Example #29
0
def main():
    
    app = QApplication(sys.argv)
    app.setApplicationName("3DPricing")
    app.setApplicationVersion('1.2')
    tmp = Window()
    win = QMainWindow()
    tmp.setupUi(win)
    win.show()
    tmp.run_init_config()

    sys.exit(app.exec_())
Example #30
0
def main():
    QApplication.setApplicationName("Blender Version Manager")
    QApplication.setApplicationVersion("1.2.0")

    app = QApplication(sys.argv)
    window = B3dVersionMangerMainWindow(app)
    window.setWindowFlags(Qt.FramelessWindowHint)

    if not window.is_run_minimized:
        window.show()

    app.exec_()
Example #31
0
def instantiate():
    """Instantiate the global QApplication object."""
    global qApp
    args = [os.path.abspath(sys.argv[0])] + sys.argv[1:]
    ### on Python3, QApplication args must be byte strings
    if sys.version_info >= (3, 0):
        args = list(map(os.fsencode, args))
    qApp = QApplication(args)
    QApplication.setApplicationName(appinfo.name)
    QApplication.setApplicationVersion(appinfo.version)
    QApplication.setOrganizationName(appinfo.name)
    QApplication.setOrganizationDomain(appinfo.domain)
    appInstantiated()
Example #32
0
def instantiate():
    """Instantiate the global QApplication object."""
    global qApp
    args = [os.path.abspath(sys.argv[0])] + sys.argv[1:]
    ### on Python3, QApplication args must be byte strings
    if sys.version_info >= (3, 0):
        args = list(map(os.fsencode, args))
    qApp = QApplication(args)
    QApplication.setApplicationName(appinfo.name)
    QApplication.setApplicationVersion(appinfo.version)
    QApplication.setOrganizationName(appinfo.name)
    QApplication.setOrganizationDomain(appinfo.domain)
    appInstantiated()
Example #33
0
def main():
    app = QApplication(sys.argv)
    app.setApplicationVersion("v1.3.1")
    app.setQuitOnLastWindowClosed(False)

    socket = QLocalSocket()
    socket.connectToServer("blender-launcher-server")
    is_running = socket.waitForConnected()

    if not is_running:
        socket.close()
        BlenderLauncher(app)
        app.exec_()
Example #34
0
def main():
    from obsmaker import __version__
    print('Obsmaker version ', __version__)
    app = QApplication(sys.argv)
    app.setApplicationName('OBSMAKER')
    app.setApplicationVersion(__version__)
    gui = GUI()
    # Adjust geometry to size of the screen
    screen_resolution = app.desktop().screenGeometry()
    width = screen_resolution.width()
    height = screen_resolution.height()
    gui.setGeometry(width * 0.01, 0, width * 0.96, height * 0.92)  # X, Y, W, H

    sys.exit(app.exec_())
Example #35
0
def run():
    app = QApplication(sys.argv)
    app.setOrganizationName("manuskript")
    app.setOrganizationDomain("www.theologeek.ch")
    app.setApplicationName("manuskript")
    app.setApplicationVersion(_version)

    icon = QIcon()
    for i in [16, 31, 64, 128, 256, 512]:
        icon.addFile(appPath("icons/Manuskript/icon-{}px.png".format(i)))
    qApp.setWindowIcon(icon)

    app.setStyle("Fusion")

    # Load style from QSettings
    settings = QSettings(app.organizationName(), app.applicationName())
    if settings.contains("applicationStyle"):
        style = settings.value("applicationStyle")
        app.setStyle(style)

    # Translation process
    locale = QLocale.system().name()

    appTranslator = QTranslator()
    # By default: locale
    translation = appPath(
        os.path.join("i18n", "manuskript_{}.qm".format(locale)))

    # Load translation from settings
    if settings.contains("applicationTranslation"):
        translation = appPath(
            os.path.join("i18n", settings.value("applicationTranslation")))
        print("Found translation in settings:", translation)

    if appTranslator.load(translation):
        app.installTranslator(appTranslator)
        print(app.tr("Loaded translation: {}.").format(translation))

    else:
        print(
            app.tr("Warning: failed to load translator for locale {}...").
            format(locale))

    QIcon.setThemeSearchPaths(QIcon.themeSearchPaths() + [appPath("icons")])
    QIcon.setThemeName("NumixMsk")
    # qApp.setWindowIcon(QIcon.fromTheme("im-aim"))

    # Seperating launch to avoid segfault, so it seem.
    # Cf. http://stackoverflow.com/questions/12433491/is-this-pyqt-4-python-bug-or-wrongly-behaving-code
    launch()
Example #36
0
def instantiate():
    """Instantiate the global QApplication object."""
    global qApp
    args = list(map(os.fsencode,
                    [os.path.abspath(sys.argv[0])] + sys.argv[1:]))
    if platform.system() == "Windows":
        args.append("-platform")
        args.append("windows:fontengine=freetype")
    qApp = QApplication(args)
    QApplication.setApplicationName(appinfo.name)
    QApplication.setApplicationVersion(appinfo.version)
    QApplication.setOrganizationName(appinfo.name)
    QApplication.setOrganizationDomain(appinfo.domain)
    appInstantiated()
Example #37
0
def main():
    app = QApplication(sys.argv)
    app.setApplicationName("Kaptan")
    app.setOrganizationName("Kaptan")
    app.setApplicationVersion("5.0 Beta3")
    #app.setStyleSheet(open(join(dirPath, "data/libkaptan.qss").read())

    locale = QLocale.system().name()
    translator = QTranslator(app)
    translator.load("/usr/share/kaptan/languages/kaptan_{}.qm".format(locale))
    app.installTranslator(translator)

    kaptan = Kaptan()
    kaptan.show()
    app.exec_()
Example #38
0
def run():
    app = QApplication(sys.argv)
    app.setOrganizationName("manuskript")
    app.setOrganizationDomain("www.theologeek.ch")
    app.setApplicationName("manuskript")
    app.setApplicationVersion(_version)

    icon = QIcon()
    for i in [16, 31, 64, 128, 256, 512]:
        icon.addFile(appPath("icons/Manuskript/icon-{}px.png".format(i)))
    qApp.setWindowIcon(icon)

    app.setStyle("Fusion")

    # Load style from QSettings
    settings = QSettings(app.organizationName(), app.applicationName())
    if settings.contains("applicationStyle"):
        style = settings.value("applicationStyle")
        app.setStyle(style)

    # Translation process
    locale = QLocale.system().name()

    appTranslator = QTranslator()
    # By default: locale
    translation = appPath(os.path.join("i18n", "manuskript_{}.qm".format(locale)))

    # Load translation from settings
    if settings.contains("applicationTranslation"):
        translation = appPath(os.path.join("i18n", settings.value("applicationTranslation")))
        print("Found translation in settings:", translation)

    if appTranslator.load(translation):
        app.installTranslator(appTranslator)
        print(app.tr("Loaded translation: {}.").format(translation))

    else:
        print(app.tr("Warning: failed to load translator for locale {}...").format(locale))

    QIcon.setThemeSearchPaths(QIcon.themeSearchPaths() + [appPath("icons")])
    QIcon.setThemeName("NumixMsk")
    # qApp.setWindowIcon(QIcon.fromTheme("im-aim"))

    # Seperating launch to avoid segfault, so it seem.
    # Cf. http://stackoverflow.com/questions/12433491/is-this-pyqt-4-python-bug-or-wrongly-behaving-code
    launch()
Example #39
0
    def __init__(self):
        app = QApplication(sys.argv)
        app.setApplicationName("eKalappai")
        app.setApplicationVersion("4.0.0")
        shared = QSharedMemory("59698760-43bb-44d9-8121-181ecbb70e4d")

        if not shared.create(512, QSharedMemory.ReadWrite):
            qWarning("Cannot start more than one instance of eKalappai any time.")
            exit(0)
        splashImage = QPixmap(':intro/splash_screen')
        splashScreen = QSplashScreen(splashImage)
        splashScreen.show()
        time.sleep(2)
        splashScreen.hide()
        QApplication.setQuitOnLastWindowClosed(False)
        ekWindow = EKWindow()
        ekWindow.engine.start()
        sys.exit(app.exec_())
Example #40
0
def main():
	app = QApplication(sys.argv)
	app.setOrganizationName("ReText project")
	app.setApplicationName("ReText")
	app.setApplicationDisplayName("ReText")
	app.setApplicationVersion(app_version)
	app.setOrganizationDomain('mitya57.me')
	if hasattr(app, 'setDesktopFileName'): # available since Qt 5.7
		app.setDesktopFileName('me.mitya57.ReText.desktop')
	QNetworkProxyFactory.setUseSystemConfiguration(True)
	RtTranslator = QTranslator()
	for path in datadirs:
		if RtTranslator.load('retext_' + globalSettings.uiLanguage,
		                     join(path, 'locale')):
			break
	QtTranslator = QTranslator()
	QtTranslator.load("qt_" + globalSettings.uiLanguage,
		QLibraryInfo.location(QLibraryInfo.TranslationsPath))
	app.installTranslator(RtTranslator)
	app.installTranslator(QtTranslator)
	if globalSettings.appStyleSheet:
		sheetfile = QFile(globalSettings.appStyleSheet)
		sheetfile.open(QIODevice.ReadOnly)
		app.setStyleSheet(QTextStream(sheetfile).readAll())
		sheetfile.close()
	window = ReTextWindow()
	window.show()
	# ReText can change directory when loading files, so we
	# need to have a list of canonical names before loading
	fileNames = list(map(canonicalize, sys.argv[1:]))
	previewMode = False
	for fileName in fileNames:
		if QFile.exists(fileName):
			window.openFileWrapper(fileName)
			if previewMode:
				window.actionPreview.trigger()
		elif fileName == '--preview':
			previewMode = True
	if sys.stdin:
		inputData = '' if sys.stdin.isatty() else sys.stdin.read()
		if inputData or not window.tabWidget.count():
			window.createNew(inputData)
	signal.signal(signal.SIGINT, lambda sig, frame: window.close())
	sys.exit(app.exec())
Example #41
0
def main():
    parser = get_parser()
    args = parser.parse_args()
    app = QApplication([])
    app.setWindowIcon(QIcon(QPixmap(":/logo_small")))
    app.setOrganizationName('Hardcoded Software')
    app.setApplicationName('moneyGuru')
    settings = QSettings()
    if args.debug:
        LOGGING_LEVEL = logging.DEBUG
    else:
        LOGGING_LEVEL = logging.DEBUG if adjust_after_deserialization(settings.value('DebugMode')) else logging.WARNING
    setupQtLogging(level=LOGGING_LEVEL, log_to_stdout=args.log_to_stdout)
    logging.debug('started in debug mode')
    if ISLINUX:
        stylesheetFile = QFile(':/stylesheet_lnx')
    else:
        stylesheetFile = QFile(':/stylesheet_win')
    stylesheetFile.open(QFile.ReadOnly)
    textStream = QTextStream(stylesheetFile)
    style = textStream.readAll()
    stylesheetFile.close()
    app.setStyleSheet(style)
    lang = settings.value('Language')
    locale_folder = op.join(BASE_PATH, 'locale')
    hscommon.trans.install_gettext_trans_under_qt(locale_folder, lang)
    # Many strings are translated at import time, so this is why we only import after the translator
    # has been installed
    from qt.app import MoneyGuru
    app.setApplicationVersion(MoneyGuru.VERSION)
    mgapp = MoneyGuru(filepath=args.filepath)
    install_excepthook('https://github.com/hsoft/moneyguru/issues')
    exec_result = app.exec_()
    del mgapp
    # Since PyQt 4.7.2, I had crashes on exit, and from reading the mailing list, it seems to be
    # caused by some weird crap about C++ instance being deleted with python instance still living.
    # The worst part is that Phil seems to say this is expected behavior. So, whatever, this
    # gc.collect() below is required to avoid a crash.
    gc.collect()
    return exec_result
Example #42
0
def main(argv):
    # Avoid performance issues with X11 engine when rendering objects
    if sys.platform == 'linux':
        QApplication.setGraphicsSystem("raster")

    a = QApplication(argv)
    a.setOrganizationDomain("mapeditor.org")
    a.setApplicationName("TmxViewer")
    a.setApplicationVersion("1.0")
    options = CommandLineOptions()
    parseCommandLineArguments(options)
    if (options.showVersion):
        showVersion()
    if (options.showHelp or (options.fileToOpen=='' and not options.showVersion)):
        showHelp()
    if (options.showVersion
            or options.showHelp
            or options.fileToOpen==''):
        return 0
    w = TmxViewer()
    if (not w.viewMap(options.fileToOpen)):
        return 1
    w.show()
    return a.exec()
Example #43
0
from PyQt5.QtCore import QCommandLineParser, QCommandLineOption
from PyQt5.QtCore import QCoreApplication
from PyQt5.QtWidgets import QApplication

from constant import PROJECT_NAME, PROJECT_VERSION
from constant import MAIN_QML

if os.name == 'posix':
    QCoreApplication.setAttribute(Qt.AA_X11InitThreads, True)

appTranslator = QTranslator()
translationsPath = "qt_" + QLocale.system().name()
appTranslator.load("qt_zh_CN.qm", QLibraryInfo.location(QLibraryInfo.TranslationsPath))
app = QApplication(sys.argv)
QApplication.setApplicationName(PROJECT_NAME)
QApplication.setApplicationVersion(PROJECT_VERSION)
app.installTranslator(appTranslator)
app.setQuitOnLastWindowClosed(True)

from window import Window
from database import Database
from config import config
from movie_info import MovieModule
from utils import utils
from menu_controller import MenuController
from dbus_services import (DeepinMovieServie, check_multiple_instances,
                           DeepinMovieInterface, session_bus, DBUS_PATH)

if __name__ == "__main__":
    windowView = None
    menu_controller = None
Example #44
0
from PyQt5.QtWidgets import QApplication
from PyQt5.QtGui import QIcon

from constants import QSS_PATH, LOGFILE, \
    MODE, DEBUG, WINDOW_ICON

from controllers import Controller
from quamash import QEventLoop


if __name__ == "__main__":
    app = QApplication(sys.argv)
    app.setQuitOnLastWindowClosed(True)
    app.setWindowIcon(QIcon(WINDOW_ICON))
    app.setApplicationName("FeelUOwn")
    app.setApplicationVersion("v3.1.0")

    app_event_loop = QEventLoop(app)
    asyncio.set_event_loop(app_event_loop)

    qss = QSS_PATH
    with open(qss, "r") as qssfile:
        app.setStyleSheet(qssfile.read())

    if MODE != DEBUG:
        f_handler = open(LOGFILE, 'w')
        sys.stdout = f_handler
        sys.stderr = f_handler

    w = Controller()
    w.move((QApplication.desktop().width() - w.width())/2, (QApplication.desktop().height() - w.height())/2)
        csv.register_dialect('CSV', delimiter='\t', quoting=csv.QUOTE_NONE)

        now = time.strftime('%Y%m%d_%H%M%S', time.localtime(time.time()))
        output_file = os.getcwd() + "\\" + type.upper() + "_aggregation_" + now + ".txt"
        
        #the write-out
        with open(output_file, 'w',newline='') as f:
            writer = csv.writer(f, 'CSV')
            
            writer.writerow(self.full_AOI_complement[0][0])
            
            for i in range(len(self.full_AOI_complement)):
                for j in range(1,len(self.full_AOI_complement[i])):
                    writer.writerow(self.full_AOI_complement[i][j])
                    
    def close(self):
        self.parent.ui.logOutput.append("")
        self.done(55)
        
# main loop - runs the main application
if __name__ == "__main__":
    app = QApplication(sys.argv)
    QApplication.setApplicationName("Biometric - Data Manipulator")
    version = "2.0"
    QApplication.setApplicationVersion(version)
    QApplication.setOrganizationName("Biometrics")
    myapp = DataManipulator(app, version)
    myapp.show()
    sys.exit(app.exec_())
    
Example #46
0
from PyQt5.QtWidgets import QApplication
from PyQt5.QtGui import QIcon

from constants import QSS_PATH, LOGFILE, \
    MODE, DEBUG, WINDOW_ICON

from controllers import MainWidget
from quamash import QEventLoop


if __name__ == "__main__":
    app = QApplication(sys.argv)
    app.setQuitOnLastWindowClosed(True)
    QApplication.setWindowIcon(QIcon(WINDOW_ICON))
    QApplication.setApplicationName("FeelUOwn")
    QApplication.setApplicationVersion("v3.1.0")

    app_event_loop = QEventLoop(app)
    asyncio.set_event_loop(app_event_loop)

    qss = QSS_PATH
    with open(qss, "r") as qssfile:
        app.setStyleSheet(qssfile.read())

    if MODE != DEBUG:
        f_handler = open(LOGFILE, 'w')
        sys.stdout = f_handler
        sys.stderr = f_handler

    w = MainWidget()
    w.move((QApplication.desktop().width() - w.width())/2, (QApplication.desktop().height() - w.height())/2)
Example #47
0
def start(test=False):

	if os.name == 'posix':
		main_path = os.path.dirname(os.path.realpath(__file__))
		log_path = os.path.join(main_path, 'happypanda.log')
		debug_log_path = os.path.join(main_path, 'happypanda_debug.log')
	else:
		log_path = 'happypanda.log'
		debug_log_path = 'happypanda_debug.log'

	parser = argparse.ArgumentParser(prog='Happypanda',
								  description='A manga/doujinshi manager with tagging support')
	parser.add_argument('-d', '--debug', action='store_true',
					 help='happypanda_debug_log.log will be created in main directory')
	parser.add_argument('-t', '--test', action='store_true',
					 help='Run happypanda in test mode. 5000 gallery will be preadded in DB.')
	parser.add_argument('-v', '--versi on', action='version',
					 version='Happypanda v{}'.format(gui_constants.vs))
	parser.add_argument('-e', '--exceptions', action='store_true',
					 help='Disable custom excepthook')

	args = parser.parse_args()
	if args.debug:
		print("happypanda_debug.log created at {}".format(os.getcwd()))
		# create log
		try:
			with open(debug_log_path, 'x') as f:
				pass
		except FileExistsError:
			pass

		logging.basicConfig(level=logging.DEBUG,
						format='%(asctime)-8s %(levelname)-6s %(name)-6s %(message)s',
						datefmt='%d-%m %H:%M',
						filename='happypanda_debug.log',
						filemode='w')
		gui_constants.DEBUG = True
	else:
		try:
			with open(log_path, 'x') as f:
				pass
		except FileExistsError: pass
		file_handler = logging.handlers.RotatingFileHandler(
			log_path, maxBytes=1000000*10, encoding='utf-8', backupCount=2)
		logging.basicConfig(level=logging.INFO,
						format='%(asctime)-8s %(levelname)-6s %(name)-6s %(message)s',
						datefmt='%d-%m %H:%M',
						handlers=(file_handler,))


	log = logging.getLogger(__name__)
	log_i = log.info
	log_d = log.debug
	log_w = log.warning
	log_e = log.error
	log_c = log.critical

	if not args.exceptions:
		def uncaught_exceptions(ex_type, ex, tb):
			log_c(''.join(traceback.format_tb(tb)))
			log_c('{}: {}'.format(ex_type, ex))
			traceback.print_exception(ex_type, ex, tb)

		sys.excepthook = uncaught_exceptions

	application = QApplication(sys.argv)
	application.setOrganizationName('Pewpews')
	application.setOrganizationDomain('https://github.com/Pewpews/happypanda')
	application.setApplicationName('Happypanda')
	application.setApplicationDisplayName('Happypanda')
	application.setApplicationVersion('v{}'.format(gui_constants.vs))
	log_i('Happypanda Version {}'.format(gui_constants.vs))
	log_i('OS: {} {}\n'.format(platform.system(), platform.release()))
	try:
		if args.test:
			conn = db.init_db(True)
		else:
			conn = db.init_db()
		log_d('Init DB Conn: OK')
		log_i("DB Version: {}".format(db_constants.REAL_DB_VERSION))
	except:
		log_c('Invalid database')
		log.exception('Database connection failed!')
		from PyQt5.QtGui import QIcon
		from PyQt5.QtWidgets import QMessageBox
		msg_box = QMessageBox()
		msg_box.setWindowIcon(QIcon(gui_constants.APP_ICO_PATH))
		msg_box.setText('Invalid database')
		msg_box.setInformativeText("Do you want to create a new database?")
		msg_box.setIcon(QMessageBox.Critical)
		msg_box.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
		msg_box.setDefaultButton(QMessageBox.Yes)
		if msg_box.exec() == QMessageBox.Yes:
			pass
		else:
			application.exit()
			log_d('Normal Exit App: OK')
			sys.exit()

	def start_main_window(conn):
		DB = db.DBThread(conn)
		#if args.test:
		#	import threading, time
		#	ser_list = []
		#	for x in range(5000):
		#		s = gallerydb.gallery()
		#		s.profile = gui_constants.NO_IMAGE_PATH
		#		s.title = 'Test {}'.format(x)
		#		s.artist = 'Author {}'.format(x)
		#		s.path = gui_constants.static_dir
		#		s.type = 'Test'
		#		s.chapters = {0:gui_constants.static_dir}
		#		s.language = 'English'
		#		s.info = 'I am number {}'.format(x)
		#		ser_list.append(s)

		#	done = False
		#	thread_list = []
		#	i = 0
		#	while not done:
		#		try:
		#			if threading.active_count() > 5000:
		#				thread_list = []
		#				done = True
		#			else:
		#				thread_list.append(
		#					threading.Thread(target=gallerydb.galleryDB.add_gallery,
		#					  args=(ser_list[i],)))
		#				thread_list[i].start()
		#				i += 1
		#				print(i)
		#				print('Threads running: {}'.format(threading.activeCount()))
		#		except IndexError:
		#			done = True

		WINDOW = app.AppWindow()

		# styling
		d_style = gui_constants.default_stylesheet_path
		u_style =  gui_constants.user_stylesheet_path

		if len(u_style) is not 0:
			try:
				style_file = QFile(u_style)
				log_i('Select userstyle: OK')
			except:
				style_file = QFile(d_style)
				log_i('Select defaultstyle: OK')
		else:
			style_file = QFile(d_style)
			log_i('Select defaultstyle: OK')

		style_file.open(QFile.ReadOnly)
		style = str(style_file.readAll(), 'utf-8')
		application.setStyleSheet(style)
		try:
			os.mkdir(gui_constants.temp_dir)
		except FileExistsError:
			try:
				for root, dirs, files in scandir.walk('temp', topdown=False):
					for name in files:
						os.remove(os.path.join(root, name))
					for name in dirs:
						os.rmdir(os.path.join(root, name))
			except:
				log_i('Empty temp: FAIL')
		log_d('Create temp: OK')

		if test:
			return application, WINDOW

		sys.exit(application.exec_())

	def db_upgrade():
		log_d('Database connection failed')
		from PyQt5.QtGui import QIcon
		from PyQt5.QtWidgets import QMessageBox

		msg_box = QMessageBox()
		msg_box.setWindowIcon(QIcon(gui_constants.APP_ICO_PATH))
		msg_box.setText('Incompatible database!')
		msg_box.setInformativeText("Do you want to upgrade to newest version?" +
							 " It shouldn't take more than a second. Don't start a new instance!")
		msg_box.setIcon(QMessageBox.Critical)
		msg_box.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
		msg_box.setDefaultButton(QMessageBox.Yes)
		if msg_box.exec() == QMessageBox.Yes:

			import threading
			db_p = db_constants.DB_PATH
			threading.Thread(target=db.add_db_revisions,
					args=(db_p,)).start()
			done = None
			while not done:
				done = db.ResultQueue.get()
			conn = db.init_db()
			start_main_window(conn)
		else:
			application.exit()
			log_d('Normal Exit App: OK')
			sys.exit()

	if conn:
		start_main_window(conn)
	else:
		db_upgrade()
Example #48
0
def start(test=False):
    app_constants.APP_RESTART_CODE = -123456789

    if os.name == 'posix':
        main_path = os.path.dirname(os.path.realpath(__file__))
        log_path = os.path.join(main_path, 'happypanda.log')
        debug_log_path = os.path.join(main_path, 'happypanda_debug.log')
    else:
        log_path = 'happypanda.log'
        debug_log_path = 'happypanda_debug.log'
    if os.path.exists('cacert.pem'):
        os.environ["REQUESTS_CA_BUNDLE"] = os.path.join(os.getcwd(), "cacert.pem")

    parser = argparse.ArgumentParser(prog='Happypanda',
                                  description='A manga/doujinshi manager with tagging support')
    parser.add_argument('-d', '--debug', action='store_true',
                     help='happypanda_debug_log.log will be created in main directory')
    parser.add_argument('-v', '--version', action='version',
                     version='Happypanda v{}'.format(app_constants.vs))
    parser.add_argument('-e', '--exceptions', action='store_true',
                     help='Disable custom excepthook')
    parser.add_argument('-x', '--dev', action='store_true',
                     help='Development Switch')

    args = parser.parse_args()
    log_handlers = []
    log_level = logging.INFO
    if args.dev:
        log_handlers.append(logging.StreamHandler())
    if args.debug:
        print("happypanda_debug.log created at {}".format(os.getcwd()))
        # create log
        try:
            with open(debug_log_path, 'x') as f:
                pass
        except FileExistsError:
            pass

        log_handlers.append(logging.FileHandler(debug_log_path, 'w', 'utf-8'))
        log_level = logging.DEBUG
        app_constants.DEBUG = True
    else:
        try:
            with open(log_path, 'x') as f:
                pass
        except FileExistsError: pass
        log_handlers.append(logging.handlers.RotatingFileHandler(
            log_path, maxBytes=1000000*10, encoding='utf-8', backupCount=2))

    # Fix for logging not working
    # clear the handlers first before adding these custom handler
    # http://stackoverflow.com/a/15167862
    logging.getLogger('').handlers = []
    logging.basicConfig(level=log_level,
                    format='%(asctime)-8s %(levelname)-6s %(name)-6s %(message)s',
                    datefmt='%d-%m %H:%M',
                    handlers=tuple(log_handlers))

    log = logging.getLogger(__name__)
    log_i = log.info
    log_d = log.debug
    log_w = log.warning
    log_e = log.error
    log_c = log.critical

    if not args.exceptions:
        def uncaught_exceptions(ex_type, ex, tb):
            log_c(''.join(traceback.format_tb(tb)))
            log_c('{}: {}'.format(ex_type, ex))
            traceback.print_exception(ex_type, ex, tb)

        sys.excepthook = uncaught_exceptions

    if app_constants.FORCE_HIGH_DPI_SUPPORT:
        log_i("Enabling high DPI display support")
        os.environ.putenv("QT_DEVICE_PIXEL_RATIO", "auto")

    effects = [Qt.UI_AnimateCombo, Qt.UI_FadeMenu, Qt.UI_AnimateMenu,
            Qt.UI_AnimateTooltip, Qt.UI_FadeTooltip]
    for effect in effects:
        QApplication.setEffectEnabled(effect)

    application = QApplication(sys.argv)
    application.setOrganizationName('Pewpews')
    application.setOrganizationDomain('https://github.com/Pewpews/happypanda')
    application.setApplicationName('Happypanda')
    application.setApplicationDisplayName('Happypanda')
    application.setApplicationVersion('v{}'.format(app_constants.vs))
    application.setAttribute(Qt.AA_UseHighDpiPixmaps)
    application.font().setStyleStrategy(application.font().PreferAntialias)

    log_i('Starting Happypanda...'.format(app_constants.vs))
    if args.debug:
        log_i('Running in debug mode'.format(app_constants.vs))
        import pprint
        sys.displayhook = pprint.pprint
    app_constants.load_icons()
    log_i('Happypanda Version {}'.format(app_constants.vs))
    log_i('OS: {} {}\n'.format(platform.system(), platform.release()))
    conn = None
    try:
        conn = db.init_db()
        log_d('Init DB Conn: OK')
        log_i("DB Version: {}".format(db_constants.REAL_DB_VERSION))
    except:
        log_c('Invalid database')
        log.exception('Database connection failed!')
        from PyQt5.QtGui import QIcon
        from PyQt5.QtWidgets import QMessageBox
        msg_box = QMessageBox()
        msg_box.setWindowIcon(QIcon(app_constants.APP_ICO_PATH))
        msg_box.setText('Invalid database')
        msg_box.setInformativeText("Do you want to create a new database?")
        msg_box.setIcon(QMessageBox.Critical)
        msg_box.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
        msg_box.setDefaultButton(QMessageBox.Yes)
        if msg_box.exec() == QMessageBox.Yes:
            pass
        else:
            application.exit()
            log_d('Normal Exit App: OK')
            sys.exit()

    def start_main_window(conn):
        db.DBBase._DB_CONN = conn
        #if args.test:
        #	import threading, time
        #	ser_list = []
        #	for x in range(5000):
        #		s = gallerydb.gallery()
        #		s.profile = app_constants.NO_IMAGE_PATH
        #		s.title = 'Test {}'.format(x)
        #		s.artist = 'Author {}'.format(x)
        #		s.path = app_constants.static_dir
        #		s.type = 'Test'
        #		s.language = 'English'
        #		s.info = 'I am number {}'.format(x)
        #		ser_list.append(s)

        #	done = False
        #	thread_list = []
        #	i = 0
        #	while not done:
        #		try:
        #			if threading.active_count() > 5000:
            #				thread_list = []
        #				done = True
        #			else:
        #				thread_list.append(
        #					threading.Thread(target=gallerydb.galleryDB.add_gallery,
        #					  args=(ser_list[i],)))
        #				thread_list[i].start()
        #				i += 1
        #				print(i)
        #				print('Threads running: {}'.format(threading.activeCount()))
        #		except IndexError:
        #			done = True

        WINDOW = app.AppWindow(args.exceptions)

        # styling
        d_style = app_constants.default_stylesheet_path
        u_style =  app_constants.user_stylesheet_path

        if len(u_style) is not 0:
            try:
                style_file = QFile(u_style)
                log_i('Select userstyle: OK')
            except:
                style_file = QFile(d_style)
                log_i('Select defaultstyle: OK')
        else:
            style_file = QFile(d_style)
            log_i('Select defaultstyle: OK')

        style_file.open(QFile.ReadOnly)
        style = str(style_file.readAll(), 'utf-8')
        application.setStyleSheet(style)
        try:
            os.mkdir(app_constants.temp_dir)
        except FileExistsError:
            try:
                for root, dirs, files in scandir.walk('temp', topdown=False):
                    for name in files:
                        os.remove(os.path.join(root, name))
                    for name in dirs:
                        os.rmdir(os.path.join(root, name))
            except:
                log.exception("Empty temp: FAIL")
        log_d('Create temp: OK')

        if test:
            return application, WINDOW

        return application.exec_()

    def db_upgrade():
        log_d('Database connection failed')
        from PyQt5.QtGui import QIcon
        from PyQt5.QtWidgets import QMessageBox

        msg_box = QMessageBox()
        msg_box.setWindowIcon(QIcon(app_constants.APP_ICO_PATH))
        msg_box.setText('Incompatible database!')
        msg_box.setInformativeText("Do you want to upgrade to newest version?" +
                             " It shouldn't take more than a second. Don't start a new instance!")
        msg_box.setIcon(QMessageBox.Critical)
        msg_box.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
        msg_box.setDefaultButton(QMessageBox.Yes)
        if msg_box.exec() == QMessageBox.Yes:
            utils.backup_database()
            import threading
            db_p = db_constants.DB_PATH
            db.add_db_revisions(db_p)
            conn = db.init_db()
            return start_main_window(conn)
        else:
            application.exit()
            log_d('Normal Exit App: OK')
            return 0

    if conn:
        return start_main_window(conn)
    else:
        return db_upgrade()
Example #49
0
os.environ["QT_QPA_PLATFORM"] = "dxcb"

from OpenGL import GL
from PyQt5 import QtCore
from PyQt5.QtCore import QCoreApplication
if os.name == 'posix':
    QCoreApplication.setAttribute(QtCore.Qt.AA_X11InitThreads, True)

# from PyQt5.QtGui import QFont
from PyQt5.QtCore import QTranslator, QLocale, QLibraryInfo
from PyQt5.QtWidgets import QApplication
appTranslator = QTranslator()
translationsPath = "qt_" + QLocale.system().name()
appTranslator.load("qt_zh_CN.qm", QLibraryInfo.location(QLibraryInfo.TranslationsPath))
app = QApplication(sys.argv)
app.setApplicationVersion("2.2.2")
app.setOrganizationName("Deepin")
app.setApplicationName("Deepin Movie")
app.installTranslator(appTranslator)
app.setQuitOnLastWindowClosed(True)

from views.window import Window
from views.subtitles import Parser
from models.playlist import database
from utils.config import config
from utils.dmsettings import DMSettings
# TODO: utils module structure sucks
from utils.utils import utils, FindVideoThreadManager
from utils.constants import MAIN_QML
from controllers.menu_controller import MenuController
from utils.file_monitor import FileMonitor
from PyQt5.QtCore import QCoreApplication
if os.name == 'posix':
    QCoreApplication.setAttribute(QtCore.Qt.AA_X11InitThreads, True)

from PyQt5.QtQuick import QQuickView
from PyQt5.QtGui import (QSurfaceFormat, QColor, QImage,
    QPixmap, QCursor, QKeySequence, qRed, qGreen, qBlue)
from PyQt5.QtWidgets import QApplication, qApp, QFileDialog
from PyQt5.QtCore import (pyqtSlot, QStandardPaths, QUrl,
    QCommandLineParser, QCommandLineOption, QTimer, Qt)
from PyQt5.QtDBus import QDBusConnection, QDBusInterface
from PyQt5.QtMultimedia import QSoundEffect
app = QApplication(sys.argv)
app.setOrganizationName("Deepin")
app.setApplicationName("Deepin Screenshot")
app.setApplicationVersion("3.0")
app.setQuitOnLastWindowClosed(False)

from i18n import _
from window_info import WindowInfo
from menu_controller import MenuController
from settings import ScreenShotSettings
from dbus_services import is_service_exist, unregister_service
from dbus_interfaces import controlCenterInterface
from dbus_interfaces import notificationsInterface, socialSharingInterface
from constants import MAIN_QML, SOUND_FILE, MAIN_DIR, TMP_IMAGE_FILE

def init_cursor_shape_dict():
    global cursor_shape_dict

    file_name_except_extension = lambda x: os.path.basename(x).split(".")[0]
Example #51
0
def prepare(tests=False):
    app = QApplication(sys.argv)
    app.setOrganizationName("manuskript"+("_tests" if tests else ""))
    app.setOrganizationDomain("www.theologeek.ch")
    app.setApplicationName("manuskript"+("_tests" if tests else ""))
    app.setApplicationVersion(getVersion())

    print("Running manuskript version {}.".format(getVersion()))
    icon = QIcon()
    for i in [16, 32, 64, 128, 256, 512]:
        icon.addFile(appPath("icons/Manuskript/icon-{}px.png".format(i)))
    qApp.setWindowIcon(icon)

    app.setStyle("Fusion")

    # Load style from QSettings
    settings = QSettings(app.organizationName(), app.applicationName())
    if settings.contains("applicationStyle"):
        style = settings.value("applicationStyle")
        app.setStyle(style)

    # Translation process
    locale = QLocale.system().name()

    appTranslator = QTranslator(app)
    # By default: locale

    def extractLocale(filename):
        # len("manuskript_") = 13, len(".qm") = 3
        return filename[11:-3] if len(filename) >= 16 else ""

    def tryLoadTranslation(translation, source):
        if appTranslator.load(appPath(os.path.join("i18n", translation))):
            app.installTranslator(appTranslator)
            print(app.tr("Loaded translation from {}: {}.").format(source, translation))
            return True
        else:
            print(app.tr("Note: No translator found or loaded from {} for locale {}.").
                  format(source, extractLocale(translation)))
            return False

    # Load translation from settings
    translation = ""
    if settings.contains("applicationTranslation"):
        translation = settings.value("applicationTranslation")
        print("Found translation in settings:", translation)

    if (translation != "" and not tryLoadTranslation(translation, "settings")) or translation == "":
        # load from settings failed or not set, fallback
        translation = "manuskript_{}.qm".format(locale)
        tryLoadTranslation(translation, "system locale")

    QIcon.setThemeSearchPaths(QIcon.themeSearchPaths() + [appPath("icons")])
    QIcon.setThemeName("NumixMsk")

    # Font siue
    if settings.contains("appFontSize"):
        f = qApp.font()
        f.setPointSize(settings.value("appFontSize", type=int))
        app.setFont(f)

    # Main window
    from manuskript.mainWindow import MainWindow

    MW = MainWindow()
    # We store the system default cursor flash time to be able to restore it
    # later if necessary
    MW._defaultCursorFlashTime = qApp.cursorFlashTime()

    # Command line project
    if len(sys.argv) > 1 and sys.argv[1][-4:] == ".msk":
        if os.path.exists(sys.argv[1]):
            path = os.path.abspath(sys.argv[1])
            MW._autoLoadProject = path

    return app, MW
Example #52
0
import sys
from PyQt5.QtWidgets import QSystemTrayIcon
from PyQt5.QtWidgets import QMessageBox
from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import QCoreApplication
from PyQt5.QtGui import QIcon
from demerio_gui.main_window import MainWindow
from demerio_gui.version import get_versions
from demerio_gui.params import *

if __name__ == "__main__":
    app = QApplication(sys.argv)
    if not QSystemTrayIcon.isSystemTrayAvailable():
        QMessageBox.critical(0, QCoreApplication.translate(trad_context, "Demerio"),
                             QCoreApplication.translate(trad_context, "I couldn't detect any system tray on this system."))
        sys.exit(1)
    QApplication.setQuitOnLastWindowClosed(False)
    app.setWindowIcon(QIcon(":/images/demerio.png"))
    app.setApplicationVersion(get_versions()["version"])
    main_window = MainWindow()
    main_window.setWindowTitle("Demerio")
    sys.exit(app.exec_())

Example #53
0
class CarlaApplication(object):
    def __init__(self, appName = "Carla2", libPrefix = None):
        object.__init__(self)

        # try to find styles dir
        stylesDir = ""

        CWDl = CWD.lower()

        # standalone, installed system-wide linux
        if libPrefix is not None:
            stylesDir = os.path.join(libPrefix, "lib", "carla")

        # standalone, local source
        elif CWDl.endswith("source"):
            stylesDir = os.path.abspath(os.path.join(CWD, "..", "bin"))

            if WINDOWS:
                # Fixes local wine build
                QApplication.addLibraryPath("C:\\Python34\\Lib\\site-packages\\PyQt5\\plugins")

        # plugin
        elif CWDl.endswith("resources"):
            # installed system-wide linux
            if CWDl.endswith("/share/carla/resources"):
                stylesDir = os.path.abspath(os.path.join(CWD, "..", "..", "..", "lib", "carla"))

            # local source
            elif CWDl.endswith("native-plugins%sresources" % os.sep):
                stylesDir = os.path.abspath(os.path.join(CWD, "..", "..", "..", "..", "bin"))

            # other
            else:
                stylesDir = os.path.abspath(os.path.join(CWD, ".."))

        # everything else
        else:
            stylesDir = CWD

        if os.path.exists(stylesDir):
            QApplication.addLibraryPath(stylesDir)

            if WINDOWS:
                stylesDir = ""

        elif config_UseQt5:
            stylesDir = ""

        else:
            self._createApp(appName)
            return

        # base settings
        settings    = QSettings("falkTX", appName)
        useProTheme = settings.value(CARLA_KEY_MAIN_USE_PRO_THEME, CARLA_DEFAULT_MAIN_USE_PRO_THEME, type=bool)

        if not useProTheme:
            self._createApp(appName)
            return

        # set style
        QApplication.setStyle("carla" if stylesDir else "fusion")

        # create app
        self._createApp(appName)

        self.fApp.setStyle("carla" if stylesDir else "fusion")

        # set palette
        proThemeColor = settings.value(CARLA_KEY_MAIN_PRO_THEME_COLOR, CARLA_DEFAULT_MAIN_PRO_THEME_COLOR, type=str).lower()

        if proThemeColor == "black":
            self.fPalBlack = QPalette()
            self.fPalBlack.setColor(QPalette.Disabled, QPalette.Window, QColor(14, 14, 14))
            self.fPalBlack.setColor(QPalette.Active,   QPalette.Window, QColor(17, 17, 17))
            self.fPalBlack.setColor(QPalette.Inactive, QPalette.Window, QColor(17, 17, 17))
            self.fPalBlack.setColor(QPalette.Disabled, QPalette.WindowText, QColor(83, 83, 83))
            self.fPalBlack.setColor(QPalette.Active,   QPalette.WindowText, QColor(240, 240, 240))
            self.fPalBlack.setColor(QPalette.Inactive, QPalette.WindowText, QColor(240, 240, 240))
            self.fPalBlack.setColor(QPalette.Disabled, QPalette.Base, QColor(6, 6, 6))
            self.fPalBlack.setColor(QPalette.Active,   QPalette.Base, QColor(7, 7, 7))
            self.fPalBlack.setColor(QPalette.Inactive, QPalette.Base, QColor(7, 7, 7))
            self.fPalBlack.setColor(QPalette.Disabled, QPalette.AlternateBase, QColor(12, 12, 12))
            self.fPalBlack.setColor(QPalette.Active,   QPalette.AlternateBase, QColor(14, 14, 14))
            self.fPalBlack.setColor(QPalette.Inactive, QPalette.AlternateBase, QColor(14, 14, 14))
            self.fPalBlack.setColor(QPalette.Disabled, QPalette.ToolTipBase, QColor(4, 4, 4))
            self.fPalBlack.setColor(QPalette.Active,   QPalette.ToolTipBase, QColor(4, 4, 4))
            self.fPalBlack.setColor(QPalette.Inactive, QPalette.ToolTipBase, QColor(4, 4, 4))
            self.fPalBlack.setColor(QPalette.Disabled, QPalette.ToolTipText, QColor(230, 230, 230))
            self.fPalBlack.setColor(QPalette.Active,   QPalette.ToolTipText, QColor(230, 230, 230))
            self.fPalBlack.setColor(QPalette.Inactive, QPalette.ToolTipText, QColor(230, 230, 230))
            self.fPalBlack.setColor(QPalette.Disabled, QPalette.Text, QColor(74, 74, 74))
            self.fPalBlack.setColor(QPalette.Active,   QPalette.Text, QColor(230, 230, 230))
            self.fPalBlack.setColor(QPalette.Inactive, QPalette.Text, QColor(230, 230, 230))
            self.fPalBlack.setColor(QPalette.Disabled, QPalette.Button, QColor(24, 24, 24))
            self.fPalBlack.setColor(QPalette.Active,   QPalette.Button, QColor(28, 28, 28))
            self.fPalBlack.setColor(QPalette.Inactive, QPalette.Button, QColor(28, 28, 28))
            self.fPalBlack.setColor(QPalette.Disabled, QPalette.ButtonText, QColor(90, 90, 90))
            self.fPalBlack.setColor(QPalette.Active,   QPalette.ButtonText, QColor(240, 240, 240))
            self.fPalBlack.setColor(QPalette.Inactive, QPalette.ButtonText, QColor(240, 240, 240))
            self.fPalBlack.setColor(QPalette.Disabled, QPalette.BrightText, QColor(255, 255, 255))
            self.fPalBlack.setColor(QPalette.Active,   QPalette.BrightText, QColor(255, 255, 255))
            self.fPalBlack.setColor(QPalette.Inactive, QPalette.BrightText, QColor(255, 255, 255))
            self.fPalBlack.setColor(QPalette.Disabled, QPalette.Light, QColor(191, 191, 191))
            self.fPalBlack.setColor(QPalette.Active,   QPalette.Light, QColor(191, 191, 191))
            self.fPalBlack.setColor(QPalette.Inactive, QPalette.Light, QColor(191, 191, 191))
            self.fPalBlack.setColor(QPalette.Disabled, QPalette.Midlight, QColor(155, 155, 155))
            self.fPalBlack.setColor(QPalette.Active,   QPalette.Midlight, QColor(155, 155, 155))
            self.fPalBlack.setColor(QPalette.Inactive, QPalette.Midlight, QColor(155, 155, 155))
            self.fPalBlack.setColor(QPalette.Disabled, QPalette.Dark, QColor(129, 129, 129))
            self.fPalBlack.setColor(QPalette.Active,   QPalette.Dark, QColor(129, 129, 129))
            self.fPalBlack.setColor(QPalette.Inactive, QPalette.Dark, QColor(129, 129, 129))
            self.fPalBlack.setColor(QPalette.Disabled, QPalette.Mid, QColor(94, 94, 94))
            self.fPalBlack.setColor(QPalette.Active,   QPalette.Mid, QColor(94, 94, 94))
            self.fPalBlack.setColor(QPalette.Inactive, QPalette.Mid, QColor(94, 94, 94))
            self.fPalBlack.setColor(QPalette.Disabled, QPalette.Shadow, QColor(155, 155, 155))
            self.fPalBlack.setColor(QPalette.Active,   QPalette.Shadow, QColor(155, 155, 155))
            self.fPalBlack.setColor(QPalette.Inactive, QPalette.Shadow, QColor(155, 155, 155))
            self.fPalBlack.setColor(QPalette.Disabled, QPalette.Highlight, QColor(14, 14, 14))
            self.fPalBlack.setColor(QPalette.Active,   QPalette.Highlight, QColor(60, 60, 60))
            self.fPalBlack.setColor(QPalette.Inactive, QPalette.Highlight, QColor(34, 34, 34))
            self.fPalBlack.setColor(QPalette.Disabled, QPalette.HighlightedText, QColor(83, 83, 83))
            self.fPalBlack.setColor(QPalette.Active,   QPalette.HighlightedText, QColor(255, 255, 255))
            self.fPalBlack.setColor(QPalette.Inactive, QPalette.HighlightedText, QColor(240, 240, 240))
            self.fPalBlack.setColor(QPalette.Disabled, QPalette.Link, QColor(34, 34, 74))
            self.fPalBlack.setColor(QPalette.Active,   QPalette.Link, QColor(100, 100, 230))
            self.fPalBlack.setColor(QPalette.Inactive, QPalette.Link, QColor(100, 100, 230))
            self.fPalBlack.setColor(QPalette.Disabled, QPalette.LinkVisited, QColor(74, 34, 74))
            self.fPalBlack.setColor(QPalette.Active,   QPalette.LinkVisited, QColor(230, 100, 230))
            self.fPalBlack.setColor(QPalette.Inactive, QPalette.LinkVisited, QColor(230, 100, 230))
            self.fApp.setPalette(self.fPalBlack)

        elif proThemeColor == "blue":
            self.fPalBlue = QPalette()
            self.fPalBlue.setColor(QPalette.Disabled, QPalette.Window, QColor(32, 35, 39))
            self.fPalBlue.setColor(QPalette.Active,   QPalette.Window, QColor(37, 40, 45))
            self.fPalBlue.setColor(QPalette.Inactive, QPalette.Window, QColor(37, 40, 45))
            self.fPalBlue.setColor(QPalette.Disabled, QPalette.WindowText, QColor(89, 95, 104))
            self.fPalBlue.setColor(QPalette.Active,   QPalette.WindowText, QColor(223, 237, 255))
            self.fPalBlue.setColor(QPalette.Inactive, QPalette.WindowText, QColor(223, 237, 255))
            self.fPalBlue.setColor(QPalette.Disabled, QPalette.Base, QColor(48, 53, 60))
            self.fPalBlue.setColor(QPalette.Active,   QPalette.Base, QColor(55, 61, 69))
            self.fPalBlue.setColor(QPalette.Inactive, QPalette.Base, QColor(55, 61, 69))
            self.fPalBlue.setColor(QPalette.Disabled, QPalette.AlternateBase, QColor(60, 64, 67))
            self.fPalBlue.setColor(QPalette.Active,   QPalette.AlternateBase, QColor(69, 73, 77))
            self.fPalBlue.setColor(QPalette.Inactive, QPalette.AlternateBase, QColor(69, 73, 77))
            self.fPalBlue.setColor(QPalette.Disabled, QPalette.ToolTipBase, QColor(182, 193, 208))
            self.fPalBlue.setColor(QPalette.Active,   QPalette.ToolTipBase, QColor(182, 193, 208))
            self.fPalBlue.setColor(QPalette.Inactive, QPalette.ToolTipBase, QColor(182, 193, 208))
            self.fPalBlue.setColor(QPalette.Disabled, QPalette.ToolTipText, QColor(42, 44, 48))
            self.fPalBlue.setColor(QPalette.Active,   QPalette.ToolTipText, QColor(42, 44, 48))
            self.fPalBlue.setColor(QPalette.Inactive, QPalette.ToolTipText, QColor(42, 44, 48))
            self.fPalBlue.setColor(QPalette.Disabled, QPalette.Text, QColor(96, 103, 113))
            self.fPalBlue.setColor(QPalette.Active,   QPalette.Text, QColor(210, 222, 240))
            self.fPalBlue.setColor(QPalette.Inactive, QPalette.Text, QColor(210, 222, 240))
            self.fPalBlue.setColor(QPalette.Disabled, QPalette.Button, QColor(51, 55, 62))
            self.fPalBlue.setColor(QPalette.Active,   QPalette.Button, QColor(59, 63, 71))
            self.fPalBlue.setColor(QPalette.Inactive, QPalette.Button, QColor(59, 63, 71))
            self.fPalBlue.setColor(QPalette.Disabled, QPalette.ButtonText, QColor(98, 104, 114))
            self.fPalBlue.setColor(QPalette.Active,   QPalette.ButtonText, QColor(210, 222, 240))
            self.fPalBlue.setColor(QPalette.Inactive, QPalette.ButtonText, QColor(210, 222, 240))
            self.fPalBlue.setColor(QPalette.Disabled, QPalette.BrightText, QColor(255, 255, 255))
            self.fPalBlue.setColor(QPalette.Active,   QPalette.BrightText, QColor(255, 255, 255))
            self.fPalBlue.setColor(QPalette.Inactive, QPalette.BrightText, QColor(255, 255, 255))
            self.fPalBlue.setColor(QPalette.Disabled, QPalette.Light, QColor(59, 64, 72))
            self.fPalBlue.setColor(QPalette.Active,   QPalette.Light, QColor(63, 68, 76))
            self.fPalBlue.setColor(QPalette.Inactive, QPalette.Light, QColor(63, 68, 76))
            self.fPalBlue.setColor(QPalette.Disabled, QPalette.Midlight, QColor(48, 52, 59))
            self.fPalBlue.setColor(QPalette.Active,   QPalette.Midlight, QColor(51, 56, 63))
            self.fPalBlue.setColor(QPalette.Inactive, QPalette.Midlight, QColor(51, 56, 63))
            self.fPalBlue.setColor(QPalette.Disabled, QPalette.Dark, QColor(18, 19, 22))
            self.fPalBlue.setColor(QPalette.Active,   QPalette.Dark, QColor(20, 22, 25))
            self.fPalBlue.setColor(QPalette.Inactive, QPalette.Dark, QColor(20, 22, 25))
            self.fPalBlue.setColor(QPalette.Disabled, QPalette.Mid, QColor(28, 30, 34))
            self.fPalBlue.setColor(QPalette.Active,   QPalette.Mid, QColor(32, 35, 39))
            self.fPalBlue.setColor(QPalette.Inactive, QPalette.Mid, QColor(32, 35, 39))
            self.fPalBlue.setColor(QPalette.Disabled, QPalette.Shadow, QColor(13, 14, 16))
            self.fPalBlue.setColor(QPalette.Active,   QPalette.Shadow, QColor(15, 16, 18))
            self.fPalBlue.setColor(QPalette.Inactive, QPalette.Shadow, QColor(15, 16, 18))
            self.fPalBlue.setColor(QPalette.Disabled, QPalette.Highlight, QColor(32, 35, 39))
            self.fPalBlue.setColor(QPalette.Active,   QPalette.Highlight, QColor(14, 14, 17))
            self.fPalBlue.setColor(QPalette.Inactive, QPalette.Highlight, QColor(27, 28, 33))
            self.fPalBlue.setColor(QPalette.Disabled, QPalette.HighlightedText, QColor(89, 95, 104))
            self.fPalBlue.setColor(QPalette.Active,   QPalette.HighlightedText, QColor(217, 234, 253))
            self.fPalBlue.setColor(QPalette.Inactive, QPalette.HighlightedText, QColor(223, 237, 255))
            self.fPalBlue.setColor(QPalette.Disabled, QPalette.Link, QColor(79, 100, 118))
            self.fPalBlue.setColor(QPalette.Active,   QPalette.Link, QColor(156, 212, 255))
            self.fPalBlue.setColor(QPalette.Inactive, QPalette.Link, QColor(156, 212, 255))
            self.fPalBlue.setColor(QPalette.Disabled, QPalette.LinkVisited, QColor(51, 74, 118))
            self.fPalBlue.setColor(QPalette.Active,   QPalette.LinkVisited, QColor(64, 128, 255))
            self.fPalBlue.setColor(QPalette.Inactive, QPalette.LinkVisited, QColor(64, 128, 255))
            self.fApp.setPalette(self.fPalBlue)

        print("Using \"%s\" theme" % self.fApp.style().objectName())

    def _createApp(self, appName):
        self.fApp = QApplication(sys.argv)
        self.fApp.setApplicationName(appName)
        self.fApp.setApplicationVersion(VERSION)
        self.fApp.setOrganizationName("falkTX")

        if appName.lower() == "carla-control":
            self.fApp.setWindowIcon(QIcon(":/scalable/carla-control.svg"))
        else:
            self.fApp.setWindowIcon(QIcon(":/scalable/carla.svg"))

        if MACOS and config_UseQt5:
            self.fApp.setAttribute(Qt.AA_DontShowIconsInMenus)

    def arguments(self):
        return self.fApp.arguments()

    def exec_(self):
        return self.fApp.exec_()

    def exit_exec(self):
        return sys.exit(self.fApp.exec_())

    def getApp(self):
        return self.fApp

    def quit(self):
        self.fApp.quit()
Example #54
0
def main(argv):
    global server_thread
    print("Starting %s %s..." % (common.app_name, common.app_version))
    print("""         __
        /  \_
     __(     )_
   _(          \_
 _(              )_
(__________________)
""")
    app = QApplication(argv)
    
    network.setup()
    filtering.setup()
    
    # Create extension server.
    server_thread = extension_server.ExtensionServerThread(QCoreApplication.instance())
    
    # Start DBus loop
    if has_dbus:
        print("DBus available. Creating main loop...", end=" ")
        mainloop = DBusQtMainLoop(set_as_default = True)
        dbus.set_default_main_loop(mainloop)
        print("done.")
    else:
        print("DBus unavailable.")

    # Create app.
    app.setApplicationName(common.app_name)
    app.setApplicationVersion(common.app_version)
    app.installTranslator(translate.translator)

    # We want Nimbus to stay open when the last window is closed,
    # so we set this.
    app.setQuitOnLastWindowClosed(False)

    # If D-Bus is present...
    if has_dbus:
        print("Creating DBus session bus...", end=" ")
        try:
            bus = dbus.SessionBus()
        except:
            print("failed.")
        else:
            print("done.")

    try:
        print("Checking for running instances of %s..." % (common.app_name,), end=" ")
        proxy = bus.get_object("org.nimbus.%s" % (common.app_name,), "/%s" % common.app_name,)
    except:
        dbus_present = False
    else:
        dbus_present = True
    print("done.")

    # If Nimbus detects the existence of another Nimbus process, it
    # will send all the requested URLs to the existing process and
    # exit.
    if dbus_present:
        print("An instance of Nimbus is already running. Passing arguments via DBus.")
        for arg in argv[1:]:
            proxy.addTab(arg)
        if len(argv) < 2:
            proxy.addWindow()
        return
    elif has_dbus:
        print("No prior instances found. Continuing on our merry way.")

    # Hack together the browser's icon. This needs to be improved.
    common.app_icon = common.complete_icon("nimbus")

    app.setWindowIcon(common.app_icon)

    common.searchEditor = search_manager.SearchEditor()
    common.downloadManager = DownloadManager(windowTitle=tr("Downloads"))
    common.downloadManager.resize(QSize(480, 320))
    common.downloadManager.loadSession()

    # Create tray icon.
    common.trayIcon = SystemTrayIcon()
    common.trayIcon.newWindowRequested.connect(addWindow)
    #common.trayIcon.windowReopenRequested.connect(reopenWindow)
    common.trayIcon.show()

    # Creates a licensing information dialog.
    common.licenseDialog = custom_widgets.LicenseDialog()

    # Create instance of clear history dialog.
    common.chistorydialog = clear_history_dialog.ClearHistoryDialog()

    uc = QUrl.fromUserInput(settings.user_css)
    websettings = QWebSettings.globalSettings()
    websettings.setUserStyleSheetUrl(uc)
    websettings.enablePersistentStorage(settings.settings_folder)
    websettings.setAttribute(websettings.LocalContentCanAccessRemoteUrls, True)
    websettings.setAttribute(websettings.LocalContentCanAccessFileUrls, True)
    websettings.setAttribute(websettings.DeveloperExtrasEnabled, True)
    try: websettings.setAttribute(websettings.ScrollAnimatorEnabled, True)
    except: pass
    common.applyWebSettings()

    # Set up settings dialog.
    settings.settingsDialog = settings_dialog.SettingsDialog()
    settings.settingsDialog.setWindowFlags(Qt.Dialog)
    closeSettingsDialogAction = QAction(settings.settingsDialog)
    closeSettingsDialogAction.setShortcuts(["Esc", "Ctrl+W"])
    closeSettingsDialogAction.triggered.connect(settings.settingsDialog.hide)
    settings.settingsDialog.addAction(closeSettingsDialogAction)

    # Set up clippings manager.
    settings.clippingsManager = settings_dialog.ClippingsPanel()
    settings.clippingsManager.setWindowFlags(Qt.Dialog)
    closeClippingsManagerAction = QAction(settings.clippingsManager)
    closeClippingsManagerAction.setShortcuts(["Esc", "Ctrl+W"])
    closeClippingsManagerAction.triggered.connect(settings.clippingsManager.hide)
    settings.clippingsManager.addAction(closeClippingsManagerAction)

    # Create DBus server
    if has_dbus:
        print("Creating DBus server...", end=" ")
        server = DBusServer(bus)
        print("done.")

    # Load adblock rules.
    filtering.adblock_filter_loader.start()

    if not os.path.isdir(settings.extensions_folder):
        try:
            print("Copying extensions...", end=" ")
            shutil.copytree(common.extensions_folder,\
                             settings.extensions_folder)
        except:
            print("failed.")
        else:
            print("done.")
    if not os.path.isfile(settings.startpage):
        try:
            print("Copying start page...", end=" ")
            shutil.copy2(common.startpage, settings.startpage)
        except:
            print("failed.")
        else:
            print("done.")

    settings.reload_extensions()
    settings.reload_userscripts()

    server_thread.setDirectory(settings.extensions_folder)

    # Start extension server.
    server_thread.start()

    # On quit, save settings.
    app.aboutToQuit.connect(prepareQuit)

    # Load settings.
    data.loadData()

    # View source dialog.
    common.viewSourceDialog = ViewSourceDialogTabber()
    #common.viewSourceDialog.show()
    
    # This is a baaad name.
    common.sessionSaver = QTimer(QCoreApplication.instance())
    common.sessionSaver.timeout.connect(saveSession)
    common.sessionSaver.timeout.connect(data.saveData)
    if common.portable:
        common.sessionSaver.start(50000)
    else:
        common.sessionSaver.start(30000)

    common.desktop = QDesktopWidget()

    changeSettings = False
    if os.path.isfile(settings.crash_file):
        print("Crash file detected.", end="")
        if not has_dbus:
            print(" With no DBus, %s may already be running." % common.app_name,)
            multInstances = QMessageBox.question(None, tr("Hm."), tr("It's not good to run multiple instances of %(app_name)s. Is an instance of %(app_name)s already running?") % {"app_name": common.app_name}, QMessageBox.Yes | QMessageBox.No)
            if multInstances == QMessageBox.Yes:
                print("%s will now halt." % common.app_name,)
                return
        else:
            print()
        clearCache = QMessageBox()
        clearCache.setWindowTitle(tr("Ow."))
        clearCache.setText(tr("%(app_name)s seems to have crashed during your last session. Fortunately, your tabs were saved up to 30 seconds beforehand. Would you like to restore them?") % {"app_name": common.app_name})
        clearCache.addButton(QPushButton(tr("Yes and change &settings")), QMessageBox.YesRole)
        clearCache.addButton(QMessageBox.Yes)
        clearCache.addButton(QMessageBox.No)
        returnValue = clearCache.exec_()
        if returnValue == QMessageBox.No:
            try: os.remove(settings.session_file)
            except: pass
        if returnValue == 0:
            changeSettings = True
    else:
        f = open(settings.crash_file, "w")
        f.write("")
        f.close()

    if not "--daemon" in argv and os.path.exists(settings.session_file):
        print("Loading previous session...", end=" ")
        if changeSettings:
            settings.settingsDialog.exec_()
        loadSession()
        print("done.")
    if not "--daemon" in argv and len(argv[1:]) > 0:
        # Create instance of MainWindow.
        print("Loading the URLs you requested...", end=" ")
        if len(browser.windows) > 0:
            win = browser.windows[-1]
        else:
            win = MainWindow(appMode = ("--app" in argv))

        # Open URLs from command line.
        if len(argv[1:]) > 0:
            for arg in argv[1:]:
                if "." in arg or ":" in arg:
                    win.addTab(url=arg)

        if win.tabWidget().count() < 1:
            win.addTab(url=settings.settings.value("general/Homepage"))

            # Show window.
        win.show()
        print("done.")
    elif not "--daemon" in argv and len(argv[1:]) == 0 and len(browser.windows) == 0:
        win = MainWindow(appMode = ("--app" in argv))
        win.addTab(url=settings.settings.value("general/Homepage"))
        win.show()

    # Load filtering stuff.
    if not os.path.isdir(filtering.hosts_folder):
        common.trayIcon.showMessage(tr("Downloading content filters"), ("Ad blocking and host filtering will not work until this completes."))
        filtering.update_filters()
    else:
        filtering.load_host_rules()

    # Start app.
    print("Kon~!")
    sys.exit(app.exec_())
Example #55
0
import signal
import weakref

from PyQt5 import QtCore
from PyQt5.QtCore import QCoreApplication
if os.name == 'posix':
    QCoreApplication.setAttribute(QtCore.Qt.AA_X11InitThreads, True)

# from PyQt5.QtGui import QFont
from PyQt5.QtCore import pyqtSlot, QObject, QTranslator, QLocale, QLibraryInfo
from PyQt5.QtWidgets import QApplication
appTranslator = QTranslator()
translationsPath = "qt_" + QLocale.system().name()
appTranslator.load("qt_zh_CN.qm", QLibraryInfo.location(QLibraryInfo.TranslationsPath))
app = QApplication(sys.argv)
app.setApplicationVersion("2.1.1")
app.installTranslator(appTranslator)
app.setQuitOnLastWindowClosed(True)

from window import Window
from database import database
from config import config
from movie_info import movie_info
from browser import Browser
from utils import utils, FindVideoThreadManager
from constant import MAIN_QML
from menu_controller import MenuController
from file_monitor import FileMonitor

class PageManager(QObject):
Example #56
0
from PyQt5.QtQuick import QQuickView
from PyQt5.QtWidgets import QApplication

from qtypes.argv import ArgParser
from qtypes.vend import Vend


if __name__ == '__main__':
    # Reminder to self, see link for why we avoid a 'main' function here
    # http://pyqt.sourceforge.net/Docs/PyQt5/pyqt4_differences.html#object-destruction-on-exit

    app = QApplication(sys.argv)
    print(sys.version)
    print("InvoiceIt")
    root = os.path.dirname(__file__)

    app.setApplicationName("InvoiceIt")
    app.setApplicationDisplayName("InvoiceIt")
    app.setApplicationVersion("0.1")

    view = QQuickView()
    qmlRegisterType(ArgParser, "ArgV", 1, 0, "ArgParser")
    qmlRegisterType(Vend, "Vend", 1, 0, "Vendor")

    f = QUrl.fromLocalFile(join(root, 'qml', 'main.qml'))
    view.setResizeMode(QQuickView.SizeRootObjectToView)
    view.setSource(f)
    view.show()

    sys.exit(app.exec_())
Example #57
0
                self.fReadThread.terminate()

        QDialog.closeEvent(self, event)

    def done(self, r):
        QDialog.done(self, r)
        self.close()

# ------------------------------------------------------------------------------------------------------------
# Allow to use this as a standalone app

if __name__ == '__main__':
    # Additional imports
    from PyQt5.QtWidgets import QApplication

    # App initialization
    app = QApplication(sys.argv)
    app.setApplicationName("Cadence-Logs")
    app.setApplicationVersion(VERSION)
    app.setOrganizationName("Cadence")
    app.setWindowIcon(QIcon(":/scalable/cadence.svg"))

    # Show GUI
    gui = LogsW(None)
    gui.show()

    setUpSignals(gui)

    # App-Loop
    sys.exit(app.exec_())
Example #58
0
def run():
    """
    Creates all the top-level assets for the application, sets things up and
    then runs the application. Specific tasks include:

    - set up logging
    - create an application object
    - create an editor window and status bar
    - display a splash screen while starting
    - close the splash screen after startup timer ends
    """
    setup_logging()
    logging.info('\n\n-----------------\n\nStarting Mu {}'.format(__version__))
    logging.info(platform.uname())
    logging.info('Python path: {}'.format(sys.path))
    logging.info('Language code: {}'.format(language_code))

    # The app object is the application running on your computer.
    app = QApplication(sys.argv)
    # By default PyQt uses the script name (run.py)
    app.setApplicationName('mu')
    # Set hint as to the .desktop files name
    app.setDesktopFileName('mu.codewith.editor')
    app.setApplicationVersion(__version__)
    app.setAttribute(Qt.AA_DontShowIconsInMenus)
    # Images (such as toolbar icons) aren't scaled nicely on retina/4k displays
    # unless this flag is set
    app.setAttribute(Qt.AA_UseHighDpiPixmaps)

    # Create the "window" we'll be looking at.
    editor_window = Window()

    @editor_window.load_theme.connect
    def load_theme(theme):
        if theme == 'contrast':
            app.setStyleSheet(CONTRAST_STYLE)
        elif theme == 'night':
            app.setStyleSheet(NIGHT_STYLE)
        else:
            app.setStyleSheet(DAY_STYLE)

    # Make sure all windows have the Mu icon as a fallback
    app.setWindowIcon(load_icon(editor_window.icon))
    # Create the "editor" that'll control the "window".
    editor = Editor(view=editor_window)
    editor.setup(setup_modes(editor, editor_window))
    # Setup the window.
    editor_window.closeEvent = editor.quit
    editor_window.setup(editor.debug_toggle_breakpoint, editor.theme)
    # Restore the previous session along with files passed by the os
    editor.restore_session(sys.argv[1:])
    # Connect the various UI elements in the window to the editor.
    editor_window.connect_tab_rename(editor.rename_tab, 'Ctrl+Shift+S')
    editor_window.connect_find_replace(editor.find_replace, 'Ctrl+F')
    editor_window.connect_toggle_comments(editor.toggle_comments, 'Ctrl+K')
    status_bar = editor_window.status_bar
    status_bar.connect_logs(editor.show_admin, 'Ctrl+Shift+D')

    # Display a friendly "splash" icon.
    splash = QSplashScreen(load_pixmap('splash-screen'))
    splash.show()

    # Hide the splash icon.
    splash_be_gone = QTimer()
    splash_be_gone.timeout.connect(lambda: splash.finish(editor_window))
    splash_be_gone.setSingleShot(True)
    splash_be_gone.start(2000)

    # Stop the program after the application finishes executing.
    sys.exit(app.exec_())
Example #59
0
        elif self.iniSettings.value("shortcut_modifier") == "CTRL":
            self.engine.event_queue.register_event([['Lcontrol', self.shortcutKey], self.icon_activated, QSystemTrayIcon.Trigger])
            self.engine.event_queue.register_event([['Rcontrol', self.shortcutKey], self.icon_activated, QSystemTrayIcon.Trigger])
        elif self.iniSettings.value("shortcut_modifier") == "ALT":
            self.engine.event_queue.register_event([['LMenu', self.shortcutKey], self.icon_activated, QSystemTrayIcon.Trigger])
            self.engine.event_queue.register_event([['RMenu', self.shortcutKey], self.icon_activated, QSystemTrayIcon.Trigger])
        return True


if __name__ == "__main__":
    """
        Main Function which will initialize the app
    """
    app = QApplication(sys.argv)
    app.setApplicationName("eKalappai")
    app.setApplicationVersion("4.0.0")
    shared = QSharedMemory("59698760-43bb-44d9-8121-181ecbb70e4d")

    if not shared.create(512, QSharedMemory.ReadWrite):
        qWarning("Cannot start more than one instance of eKalappai any time.")
        exit(0)
    splashImage = QPixmap(':/images/intro.png')
    splashScreen = QSplashScreen(splashImage)
    splashScreen.show()
    time.sleep(2)
    splashScreen.hide()
    QApplication.setQuitOnLastWindowClosed(False)
    ekWindow = EKWindow()
    ekWindow.engine.start()
    sys.exit(app.exec_())
Example #60
0
def start(test=False):
    app_constants.APP_RESTART_CODE = -123456789

    if os.name == "posix":
        main_path = os.path.dirname(os.path.realpath(__file__))
        log_path = os.path.join(main_path, "happypanda.log")
        debug_log_path = os.path.join(main_path, "happypanda_debug.log")
    else:
        log_path = "happypanda.log"
        debug_log_path = "happypanda_debug.log"

    parser = argparse.ArgumentParser(prog="Happypanda", description="A manga/doujinshi manager with tagging support")
    parser.add_argument(
        "-d", "--debug", action="store_true", help="happypanda_debug_log.log will be created in main directory"
    )
    parser.add_argument(
        "-t", "--test", action="store_true", help="Run happypanda in test mode. 5000 gallery will be preadded in DB."
    )
    parser.add_argument("-v", "--version", action="version", version="Happypanda v{}".format(app_constants.vs))
    parser.add_argument("-e", "--exceptions", action="store_true", help="Disable custom excepthook")

    args = parser.parse_args()
    if args.debug:
        print("happypanda_debug.log created at {}".format(os.getcwd()))
        # create log
        try:
            with open(debug_log_path, "x") as f:
                pass
        except FileExistsError:
            pass

        logging.basicConfig(
            level=logging.DEBUG,
            format="%(asctime)-8s %(levelname)-6s %(name)-6s %(message)s",
            datefmt="%d-%m %H:%M",
            filename="happypanda_debug.log",
            filemode="w",
        )
        app_constants.DEBUG = True
    else:
        try:
            with open(log_path, "x") as f:
                pass
        except FileExistsError:
            pass
        file_handler = logging.handlers.RotatingFileHandler(
            log_path, maxBytes=1000000 * 10, encoding="utf-8", backupCount=2
        )
        logging.basicConfig(
            level=logging.INFO,
            format="%(asctime)-8s %(levelname)-6s %(name)-6s %(message)s",
            datefmt="%d-%m %H:%M",
            handlers=(file_handler,),
        )

    log = logging.getLogger(__name__)
    log_i = log.info
    log_d = log.debug
    log_w = log.warning
    log_e = log.error
    log_c = log.critical

    if not args.exceptions:

        def uncaught_exceptions(ex_type, ex, tb):
            log_c("".join(traceback.format_tb(tb)))
            log_c("{}: {}".format(ex_type, ex))
            traceback.print_exception(ex_type, ex, tb)

        sys.excepthook = uncaught_exceptions

    application = QApplication(sys.argv)
    application.setOrganizationName("Pewpews")
    application.setOrganizationDomain("https://github.com/Pewpews/happypanda")
    application.setApplicationName("Happypanda")
    application.setApplicationDisplayName("Happypanda")
    application.setApplicationVersion("v{}".format(app_constants.vs))
    log_i("Happypanda Version {}".format(app_constants.vs))
    log_i("OS: {} {}\n".format(platform.system(), platform.release()))
    conn = None
    try:
        if args.test:
            conn = db.init_db(True)
        else:
            conn = db.init_db()
        log_d("Init DB Conn: OK")
        log_i("DB Version: {}".format(db_constants.REAL_DB_VERSION))
    except:
        log_c("Invalid database")
        log.exception("Database connection failed!")
        from PyQt5.QtGui import QIcon
        from PyQt5.QtWidgets import QMessageBox

        msg_box = QMessageBox()
        msg_box.setWindowIcon(QIcon(app_constants.APP_ICO_PATH))
        msg_box.setText("Invalid database")
        msg_box.setInformativeText("Do you want to create a new database?")
        msg_box.setIcon(QMessageBox.Critical)
        msg_box.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
        msg_box.setDefaultButton(QMessageBox.Yes)
        if msg_box.exec() == QMessageBox.Yes:
            pass
        else:
            application.exit()
            log_d("Normal Exit App: OK")
            sys.exit()

    def start_main_window(conn):
        db.DBBase._DB_CONN = conn
        # if args.test:
        # 	import threading, time
        # 	ser_list = []
        # 	for x in range(5000):
        # 		s = gallerydb.gallery()
        # 		s.profile = app_constants.NO_IMAGE_PATH
        # 		s.title = 'Test {}'.format(x)
        # 		s.artist = 'Author {}'.format(x)
        # 		s.path = app_constants.static_dir
        # 		s.type = 'Test'
        # 		s.language = 'English'
        # 		s.info = 'I am number {}'.format(x)
        # 		ser_list.append(s)

        # 	done = False
        # 	thread_list = []
        # 	i = 0
        # 	while not done:
        # 		try:
        # 			if threading.active_count() > 5000:
        # 				thread_list = []
        # 				done = True
        # 			else:
        # 				thread_list.append(
        # 					threading.Thread(target=gallerydb.galleryDB.add_gallery,
        # 					  args=(ser_list[i],)))
        # 				thread_list[i].start()
        # 				i += 1
        # 				print(i)
        # 				print('Threads running: {}'.format(threading.activeCount()))
        # 		except IndexError:
        # 			done = True

        WINDOW = app.AppWindow()

        # styling
        d_style = app_constants.default_stylesheet_path
        u_style = app_constants.user_stylesheet_path

        if len(u_style) is not 0:
            try:
                style_file = QFile(u_style)
                log_i("Select userstyle: OK")
            except:
                style_file = QFile(d_style)
                log_i("Select defaultstyle: OK")
        else:
            style_file = QFile(d_style)
            log_i("Select defaultstyle: OK")

        style_file.open(QFile.ReadOnly)
        style = str(style_file.readAll(), "utf-8")
        application.setStyleSheet(style)
        try:
            os.mkdir(app_constants.temp_dir)
        except FileExistsError:
            try:
                for root, dirs, files in scandir.walk("temp", topdown=False):
                    for name in files:
                        os.remove(os.path.join(root, name))
                    for name in dirs:
                        os.rmdir(os.path.join(root, name))
            except:
                log.exception("Empty temp: FAIL")
        log_d("Create temp: OK")

        if test:
            return application, WINDOW

        return application.exec_()

    def db_upgrade():
        log_d("Database connection failed")
        from PyQt5.QtGui import QIcon
        from PyQt5.QtWidgets import QMessageBox

        msg_box = QMessageBox()
        msg_box.setWindowIcon(QIcon(app_constants.APP_ICO_PATH))
        msg_box.setText("Incompatible database!")
        msg_box.setInformativeText(
            "Do you want to upgrade to newest version?"
            + " It shouldn't take more than a second. Don't start a new instance!"
        )
        msg_box.setIcon(QMessageBox.Critical)
        msg_box.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
        msg_box.setDefaultButton(QMessageBox.Yes)
        if msg_box.exec() == QMessageBox.Yes:
            utils.backup_database()
            import threading

            db_p = db_constants.DB_PATH
            db.add_db_revisions(db_p)
            conn = db.init_db()
            return start_main_window(conn)
        else:
            application.exit()
            log_d("Normal Exit App: OK")
            return 0

    if conn:
        return start_main_window(conn)
    else:
        return db_upgrade()