Example #1
0
    def loop_gui(self):
        """
        Launch the sugaroid PyQt5 gui with Breeze theme and custom features
        If PyQt5 not installed, raise ModuleNotFoundError
        :return:
        """
        if not GUI_DEPS:
            raise ModuleNotFoundError(
                "PyQt5 is not Installed. Install it by pip3 install PyQt5")

        print("Launching GUI")
        QApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling, True)
        QApplication.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps,
                                  True)  # use highdpi icons
        app = QtWidgets.QApplication(sys.argv)
        app.setStyle("Breeze")
        from sugaroid.gui.ux import InterfaceSugaroidQt

        window = InterfaceSugaroidQt(parent=self)
        window.init()
        try:
            app.exec_()
        except KeyboardInterrupt:
            pass
        self.database.close()
Example #2
0
def run_gui_tests(tstcls, gui_test_bag):
    assert tstcls.app is None, "Should only encounter every class once. Check Sorting"
    tst_queue = queue.Queue()
    app = tstcls.app = QApplication([])
    app.setQuitOnLastWindowClosed(False)
    app.thread_router = ThreadRouter(app)
    tstcls.shell = launchShell(None, [], [])

    platform_str = platform.platform().lower()
    if "ubuntu" in platform_str or "fedora" in platform_str:
        QApplication.setAttribute(Qt.AA_X11InitThreads, True)

    if ilastik.config.cfg.getboolean("ilastik", "debug"):
        QApplication.setAttribute(Qt.AA_DontUseNativeMenuBar, True)

    # Note on the class test execution lifecycle
    # pytest infers that finalizer teardown_class should be called when
    # nextitem is None
    for item, nextitem in pairwise(gui_test_bag, tail=None):
        tst_queue.put((item, nextitem))

    # Spawn a suite runner as a interval task
    suite = GuiTestSuite(tst_queue, tstcls.shell)
    timer = QTimer()
    # This timer will fire only after application is started running
    timer.timeout.connect(suite.poll)
    timer.start(100)  # Every 100 ms

    app.exec_()
    timer.stop()

    tst_queue.join()
Example #3
0
def bootstrap0():
    # enable highdpi scaling
    QApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling, True)
    QApplication.setAttribute(
        QtCore.Qt.AA_UseHighDpiPixmaps, True)  # use highdpi icons
    app = QtWidgets.QApplication(sys.argv)

    app.setStyle('Breeze')
    app.setStyleSheet(darkstylesheet())

    window = QtWidgets.QMainWindow()  # Create windwo
    prog = InterfaceGuiscrcpy(window)

    splash_pix = QPixmap(":/res/ui/guiscrcpy-branding.png")
    splash = QtWidgets.QSplashScreen(splash_pix)
    splash.setMask(splash_pix.mask())
    splash.show()
    app.processEvents()

    adb.devices(adb.path)

    app.processEvents()

    window.show()
    splash.hide()
    app.exec_()
    sys.exit()
Example #4
0
    def __init__(self, parent = None):
        """Create a wizard or the mainwindow"""
        self._parent = parent

        super().__init__(self._parent)

        print("runner/HelperTool parent: ", self._parent, " -> self: ", self) if oPB.PRINTHIER else None

        QApplication.setAttribute(QtCore.Qt.AA_UseOpenGLES)
        self.app = QApplication(sys.argv)

        # instantiate configuration class
        confighandler.ConfigHandler(oPB.CONFIG_INI)

        # installing translators
        self.translator = Translator(self.app, "opsipackagebuilder")
        self.translator.install_translations(confighandler.ConfigHandler.cfg.language)

        # instantiate help viewer and translate it, if necessary
        self.helpviewer = Help(oPB.HLP_FILE, oPB.HLP_PREFIX)
        self.helpviewer.showHelp(oPB.HLP_DST_INDEX, False)
        event = QtCore.QEvent(QtCore.QEvent.LanguageChange)
        self.helpviewer._help.ui.changeEvent(event)

        # run main loop
        # return to os
        sys.exit(self.app.exec_())
Example #5
0
def startShellGui(workflow_cmdline_args, eventcapture_mode, playback_args, preinit_funcs, postinit_funcs):
    """
    Create an application and launch the shell in it.
    """

    """
    The next two lines fix the following xcb error on Ubuntu by calling X11InitThreads before loading the QApplication:
       [xcb] Unknown request in queue while dequeuing
       [xcb] Most likely this is a multi-threaded client and XInitThreads has not been called
       [xcb] Aborting, sorry about that.
       python: ../../src/xcb_io.c:178: dequeue_pending_request: Assertion !xcb_xlib_unknown_req_in_deq failed.
    """
    platform_str = platform.platform().lower()
    if 'ubuntu' in platform_str or 'fedora' in platform_str or 'debian' in platform_str:
        QApplication.setAttribute(Qt.AA_X11InitThreads, True)

    if ilastik.config.cfg.getboolean("ilastik", "debug"):
        QApplication.setAttribute(Qt.AA_DontUseNativeMenuBar, True)

    if eventcapture_mode is not None:
        # Only use a special QApplication subclass if we are recording.
        # Otherwise, it's a performance penalty for every event processed by Qt.
        from eventcapture.eventRecordingApp import EventRecordingApp
        app = EventRecordingApp.create_app(eventcapture_mode, **playback_args)
    else:
        app = QApplication([])
    _applyStyleSheet(app)

    splashScreen.showSplashScreen()
    app.processEvents()
    QTimer.singleShot( 0, functools.partial(launchShell, workflow_cmdline_args, preinit_funcs, postinit_funcs ) )
    QTimer.singleShot( 0, splashScreen.hideSplashScreen)

    return app.exec_()
Example #6
0
def main():
    sys.excepthook = excepthook

    QApplication.setDesktopSettingsAware(False)
    QApplication.setStyle(QStyleFactory.create("Fusion"))
    app = QApplication(sys.argv)
    app.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps)
    sys.stderr.write("\n")
    cli = BaseCLI(
        "DERIVA Authentication Agent",
        "For more information see: https://github.com/informatics-isi-edu/deriva-qt",
        VERSION)
    cli.parser.add_argument(
        "--cookie-persistence",
        action="store_true",
        help="Enable cookie and local storage persistence for QtWebEngine.")
    args = cli.parse_cli()
    config = read_config(args.config_file,
                         create_default=False) if args.config_file else None
    authWindow = AuthWindow(config,
                            args.credential_file,
                            cookie_persistence=args.cookie_persistence)
    authWindow.show()
    ret = app.exec_()
    return ret
Example #7
0
def qt_main(args):
    SPECIALS.init()

    if hasattr(Qt, 'AA_DisableWindowContextHelpButton'):
        QApplication.setAttribute(Qt.AA_DisableWindowContextHelpButton)
    QApplication.setAttribute(Qt.AA_EnableHighDpiScaling)

    app = QApplication(args)

    Application().use_args(args[1:])

    Application().use_thread_manager(QTThreadManager())
    Application().use_ruler(QTRuler())

    Application().start()

    install_exception_hook()

    splash = SplashScreen()

    splash.start()

    SPECIALS.before_start()

    no = app.exec_()

    SPECIALS.after_quit()

    Application().stop()

    return no
Example #8
0
def run_gui_tests(tstcls, gui_test_bag):
    assert tstcls.app is None, "Should only encounter every class once. Check Sorting"
    tst_queue = queue.Queue()
    app = tstcls.app = QApplication([])
    app.setQuitOnLastWindowClosed(False)
    ThreadRouter.app_is_shutting_down = False
    app.thread_router = ThreadRouter(app)
    tstcls.shell = launchShell(None, [], [])

    platform_str = platform.platform().lower()
    if 'ubuntu' in platform_str or 'fedora' in platform_str:
        QApplication.setAttribute(Qt.AA_X11InitThreads, True)

    if ilastik.config.cfg.getboolean("ilastik", "debug"):
        QApplication.setAttribute(Qt.AA_DontUseNativeMenuBar, True)

    # Note on the class test execution lifecycle
    # pytest infers that finalizer teardown_class should be called when
    # nextitem is None
    for item, nextitem in pairwise(gui_test_bag, tail=None):
        tst_queue.put((item, nextitem))

    # Spawn a suite runner as a interval task
    suite = GuiTestSuite(tst_queue, tstcls.shell)
    timer = QTimer()
    # This timer will fire only after application is started running
    timer.timeout.connect(suite.poll)
    timer.start(100)  # Every 100 ms

    app.exec_()
    timer.stop()

    tst_queue.join()
Example #9
0
def main():
	QApplication.setAttribute(Qt.AA_EnableHighDpiScaling, True)
	QApplication.setAttribute(Qt.AA_UseHighDpiPixmaps, True)
	app = QApplication(sys.argv)
	software = App()
	software.initUI()
	sys.exit(app.exec_())
Example #10
0
    def createApp(self, appName):
        if LINUX:
            # AA_X11InitThreads is not available on old PyQt versions
            try:
                attr = Qt.AA_X11InitThreads
            except:
                attr = 10
            QApplication.setAttribute(attr)

        if MACOS:
            QApplication.setAttribute(Qt.AA_DontShowIconsInMenus)

        self.fApp = QCoreApplication(
            sys.argv) if gCarla.nogui else QApplication(sys.argv)
        self.fApp.setApplicationName(appName)
        self.fApp.setApplicationVersion(VERSION)
        self.fApp.setOrganizationName("falkTX")

        if gCarla.nogui:
            return

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

        print("Using \"%s\" theme" % self.fApp.style().objectName())
    def __init__(self) -> None:
        if hasattr(Qt, 'AA_EnableHighDpiScaling'):
            QApplication.setAttribute(Qt.AA_EnableHighDpiScaling, True)
        if hasattr(Qt, 'AA_UseHighDpiPixmaps'):
            QApplication.setAttribute(Qt.AA_UseHighDpiPixmaps, True)

        self.app = QApplication(sys.argv)

        if settings.vara_cfg()["config_file"].value is None:
            err = QMessageBox()
            err.setIcon(QMessageBox.Warning)
            err.setWindowTitle("Missing config file.")
            err.setText(
                "Could not find VaRA config file.\n"
                "Should we create a config file in the current folder?"
            )

            err.setStandardButtons(
                tp.cast(
                    QMessageBox.StandardButtons,
                    QMessageBox.Yes | QMessageBox.No
                )
            )
            answer = err.exec_()
            if answer == QMessageBox.Yes:
                settings.save_config()
            else:
                sys.exit()

        self.main_window = MainWindow()
Example #12
0
def main():
    """ Основная функция сервера"""
    # Загружаем файл конфигурации
    config = config_load()

    # Проверяем параметры командной строки
    listen_address, listen_port, gui_flag = create_arg_parser(
        config['SETTINGS']['Listen_Address'], config['SETTINGS']['Default_port'])

    database = ServerDatabase(os.path.join(
        config['SETTINGS']['Database_path'],
        config['SETTINGS']['Database_file']))

    # Создание экземпляра класса - сервера и его запуск:
    server = Server(listen_address, listen_port, database)
    server.daemon = True
    server.start()

    if gui_flag:
        while True:
            command = input('Введите exit для завершения работы сервера.')
            if command == 'exit':
                # Если выход, то завршаем основной цикл сервера.
                server.running = False
                server.join()
                break
    else:
        # Графическое окружение сервера
        server_app = QApplication(sys.argv)
        server_app.setAttribute(Qt.AA_DisableWindowContextHelpButton)
        main_window = MainWindow(database, server, config)
        # Запуск графического интерфейса
        server_app.exec_()
        # По закрытию окон останавливаем обработчик сообщений
        server.running = False
Example #13
0
def main():
    """Main server method.

    Loads the settings, starts network part in the background and then opens the main window."""

    config = config_load()

    address, port, gui_flag = arg_parser(config['SETTINGS']['default_port'],
                                         config['SETTINGS']['listen_address'])
    db = ServerBase(
        os.path.join(config['SETTINGS']['database_path'],
                     config['SETTINGS']['database_file']))
    server = MessageProcessor(address, port, db)
    server.daemon = True
    server.start()

    # print_help()
    if gui_flag:
        while True:
            command = input('Type "exit" to stop the server...')
            if command == 'exit':
                server.running = False
                server.join()
                break
    else:
        server_app = QApplication(sys.argv)
        server_app.setAttribute(Qt.AA_DisableWindowContextHelpButton)
        main_window = MainWindow(db, server, config)

        server_app.exec_()
        server.running = False
Example #14
0
def startShellGui(workflow_cmdline_args, preinit_funcs, postinit_funcs):
    """
    Create an application and launch the shell in it.
    """
    """
    The next two lines fix the following xcb error on Ubuntu by calling X11InitThreads before loading the QApplication:
       [xcb] Unknown request in queue while dequeuing
       [xcb] Most likely this is a multi-threaded client and XInitThreads has not been called
       [xcb] Aborting, sorry about that.
       python: ../../src/xcb_io.c:178: dequeue_pending_request: Assertion !xcb_xlib_unknown_req_in_deq failed.
    """
    platform_str = platform.platform().lower()
    if "ubuntu" in platform_str or "fedora" in platform_str or "debian" in platform_str:
        QApplication.setAttribute(Qt.AA_X11InitThreads, True)

    if ilastik.config.cfg.getboolean("ilastik", "debug"):
        QApplication.setAttribute(Qt.AA_DontUseNativeMenuBar, True)

    app = QApplication([])
    _applyStyleSheet(app)

    splash = getSplashScreen()
    splash.show()
    app.processEvents()
    QTimer.singleShot(
        0,
        functools.partial(launchShell, workflow_cmdline_args, preinit_funcs,
                          postinit_funcs))
    QTimer.singleShot(0, functools.partial(splash.finish, shell))

    return app.exec_()
Example #15
0
def main():
	"""
	Main server function
	:return:
	"""
	# Загрузка файла конфигурации сервера
	config = config_load()
	
	# Загрузка параметров командной строки, если нет параметров, то задаём
	# значения по умоланию.
	listen_address, listen_port = arg_parser(
		config['SETTINGS']['default_port'], config['SETTINGS']['default_address'])
	
	# Инициализация базы данных
	database = ServerDB('server_dataBase.db3')
	
	# Создание экземпляра класса - сервера и его запуск:
	server = MessageProcessor(listen_address, listen_port, database)
	server.daemon = True
	server.start()
	
	# Создаём графическое окружение для сервера:
	server_app = QApplication(sys.argv)
	server_app.setAttribute(Qt.AA_DisableWindowContextHelpButton)
	main_window = MainWindow(database, server, config)
	
	# Запускаем GUI
	server_app.exec_()
	
	# По закрытию окон останавливаем обработчик сообщений
	server.running = False
Example #16
0
def main():
    parser = ArgumentParser()
    parser.add_argument('--info',
                        dest='do_info',
                        action='store_true',
                        default=False,
                        help='Run info mode if chosen.')
    parser.add_argument('--noverify',
                        dest='do_verify',
                        action='store_false',
                        default=True,
                        help='Do not verify SSL transactions if chosen.')
    args = parser.parse_args()
    logger = logging.getLogger()
    if args.do_info: logger.setLevel(logging.INFO)
    #
    app = QApplication([])
    app.setAttribute(Qt.AA_UseHighDpiPixmaps)
    icn = QIcon(
        os.path.join(resourceDir, 'icons',
                     'howdy_config_gui_SQUARE_VECTA.svg'))
    app.setWindowIcon(icn)
    qtmodern.styles.dark(app)
    hcgui = core_gui.HowdyConfigGUI(verify=args.do_verify)
    mw = qtmodern.windows.ModernWindow(hcgui)
    mw.show()
    result = app.exec_()
Example #17
0
class GUI():
    def __init__(self, loggers, stats, signals, db):
        # pyqt definitions
        os.environ["QT_AUTO_SCREEN_SCALE_FACTOR"] = "1"
        self.app = QApplication([])
        self.app.setAttribute(Qt.AA_EnableHighDpiScaling)

        # variables received
        self.loggers = loggers
        self.stats = stats
        self.signals = signals
        self.db = db

        # windows
        self.main = main_window.MainWindow(self.loggers, self.stats,
                                           self.signals, self.db)
        self.options = options_window.OptionsWindow(self.signals, self.db)

        # init
        self.connect_events()

        # start
        self.main.window.show()
        exit(self.app.exec_())

    def connect_events(self):
        self.main.contents.chrome_options.clicked.connect(self.show_options)
        self.main.contents.firefox_options.clicked.connect(self.show_options)

    def show_options(self):
        self.options.fill_fields()
        self.options.window.show()
Example #18
0
    def createApp(self, appName):
        if LINUX:
            # AA_X11InitThreads is not available on old PyQt versions
            try:
                attr = Qt.AA_X11InitThreads
            except:
                attr = 10
            QApplication.setAttribute(attr)

        if MACOS:
            QApplication.setAttribute(Qt.AA_DontShowIconsInMenus)

        args = sys.argv[:]

        if WINDOWS:
            args += ["-platform", "windows:fontengine=freetype"]

        self.fApp = QCoreApplication(args) if gCarla.nogui else QApplication(args)
        self.fApp.setApplicationName(appName)
        self.fApp.setApplicationVersion(VERSION)
        self.fApp.setOrganizationName("falkTX")

        if gCarla.nogui:
            return

        if appName.lower() == "carla-control":
            self.fApp.setWindowIcon(QIcon(":/scalable/carla-control.svg"))
        else:
            self.fApp.setWindowIcon(QIcon(":/scalable/carla.svg"))
Example #19
0
def main():
    app = QApplication(sys.argv)
    app.setAttribute(Qt.AA_EnableHighDpiScaling)
    app.setStyle("Fusion")
    form = MainWindow()
    form.show()
    sys.exit(app.exec_())
Example #20
0
def run():
    QApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling, True)
    QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_ShareOpenGLContexts)
    app = QApplication(sys.argv)
    app.aboutToQuit.connect(app.deleteLater)
    controller = multiangleController(app, 1)
    return app.exec_()
Example #21
0
    def run(self):
        # Enable Qt built-in High DPI scaling attribute (must be set *before* creating a QApplication!)
        QApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
        app = QApplication(sys.argv)

        self.logger.info("Running Controller instance")
        vid_limit = read_config('Model', 'loaded_videos')

        start_with_stored_videos = read_config('Debug',
                                               'start_with_stored_videos')

        main_model = MainModel([], vid_limit)
        if start_with_stored_videos:
            main_model.update_subfeed_videos_from_db()
        else:
            main_model.update_subfeed_videos_from_remote()

        main_model.update_playback_videos_from_db()

        self.logger.info(
            "Created MainModel: len(subscription_feed) = {}, vid_limit = {}".
            format(len(main_model.subfeed_videos), vid_limit))

        self.logger.info("Created QApplication({})".format(sys.argv))
        window = MainWindow(app, main_model)
        window.show()
        self.logger.info("Executing Qt Application")
        app.exec_()
        self.logger.info("*** APPLICATION EXIT ***\n")
def run_app():
    # Handle high resolution displays:
    if hasattr(Qt, 'AA_EnableHighDpiScaling'):
        QApplication.setAttribute(Qt.AA_EnableHighDpiScaling, True)
    if hasattr(Qt, 'AA_UseHighDpiPixmaps'):
        QApplication.setAttribute(Qt.AA_UseHighDpiPixmaps, True)
    app = QApplication(sys.argv)
    app.setApplicationName("Offline Docs")
    app.setWindowIcon(QIcon('resources/assets/images/logo.png'))
    app_font = RegularFont()
    app.setFont(app_font)
    my_style = MyProxyStyle('Fusion')
    app.setStyle(my_style)
    screen = app.primaryScreen()
    rect = screen.availableGeometry()
    screen_center = screen.availableGeometry().center()
    print('Available: %dx%d' % (rect.width(), rect.height()))
    SessionWrapper.screen_dim = ('%dx%d' % (rect.width(), rect.height()))
    SessionWrapper.screen_width = rect.width()
    SessionWrapper.screen_height = rect.height()
    # print('Screen: %s' % screen.name())
    # size = screen.size()
    # print('Size: %d x %d' % (size.width(), size.height()))

    css_file = "resources/assets/css/style.qss"
    app.setStyleSheet(open(css_file, "r").read())
    login = Login()
    ############################################################
    # if login succeed start the main page                     #
    ############################################################
    login_result = login.exec_()
    if login_result == QDialog.Accepted and login.status == "Done":
        window = LandingForm()
        window.show()
        sys.exit(app.exec_())
Example #23
0
    def createApp(self, appName):
        if LINUX:
            # AA_X11InitThreads is not available on old PyQt versions
            try:
                attr = Qt.AA_X11InitThreads
            except:
                attr = 10
            QApplication.setAttribute(attr)

        if MACOS:
            QApplication.setAttribute(Qt.AA_DontShowIconsInMenus)

        args = sys.argv[:]

        if WINDOWS:
            args += ["-platform", "windows:fontengine=freetype"]

        self.fApp = QCoreApplication(args) if gCarla.nogui else QApplication(args)
        self.fApp.setApplicationName(appName)
        self.fApp.setApplicationVersion(VERSION)
        self.fApp.setOrganizationName("falkTX")

        if gCarla.nogui:
            return

        if appName.lower() == "carla-control":
            self.fApp.setWindowIcon(QIcon(":/scalable/carla-control.svg"))
        else:
            self.fApp.setWindowIcon(QIcon(":/scalable/carla.svg"))
Example #24
0
def main():
    config = config_load()

    # Загрузка параметров командной строки
    listen_address, listen_port, gui_flag = arg_parser(
        config['SETTINGS']['Default_port'],
        config['SETTINGS']['Listen_Address'])

    # Инициализация базы данных
    database = ServerStorage(
        os.path.join(config['SETTINGS']['Database_path'],
                     config['SETTINGS']['Database_file']))

    server = MessageProcessor(listen_address, listen_port, database)
    server.daemon = True
    server.start()

    if gui_flag:
        while True:
            command = input('Введите exit для завершения работы сервера.')
            if command == 'exit':
                server.running = False
                server.join()
                break

    else:
        # графическое окуружение для сервера:
        server_app = QApplication(sys.argv)
        server_app.setAttribute(Qt.AA_DisableWindowContextHelpButton)
        main_window = MainWindow(database, server, config)

        # Запускаем GUI
        server_app.exec_()

        server.running = False
Example #25
0
def run():
    """Run the app"""
    app = QApplication(sys.argv)
    app.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps)
    # app.main = GUI()
    gui = MainWindow()
    sys.exit(app.exec_())
Example #26
0
def main():
    """Основная функция"""
    config = config_load()

    listen_address, listen_port, gui_flag = arg_parser(
        config['SETTINGS']['Default_port'],
        config['SETTINGS']['Listen_Address'])

    database = ServerStorage(
        os.path.join(config['SETTINGS']['Database_path'],
                     config['SETTINGS']['Database_file']))

    server = MessageProcessor(listen_address, listen_port, database)
    server.daemon = True
    server.start()

    if gui_flag:
        while True:
            command = input('Введите exit для завершения работы сервера.')
            if command == 'exit':
                server.running = False
                server.join()
                break

    else:
        server_app = QApplication(sys.argv)
        server_app.setAttribute(Qt.AA_DisableWindowContextHelpButton)
        main_window = MainWindow(database, server, config)

        server_app.exec_()

        server.running = False
Example #27
0
    def createApp(self, appName):
        if LINUX:
            # AA_X11InitThreads is not available on old PyQt versions
            try:
                attr = Qt.AA_X11InitThreads
            except:
                attr = 10
            QApplication.setAttribute(attr)

        if MACOS:
            QApplication.setAttribute(Qt.AA_DontShowIconsInMenus)

        self.fApp = QCoreApplication(sys.argv) if gCarla.nogui else QApplication(sys.argv)
        self.fApp.setApplicationName(appName)
        self.fApp.setApplicationVersion(VERSION)
        self.fApp.setOrganizationName("falkTX")

        if gCarla.nogui:
            return

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

        print("Using \"%s\" theme" % self.fApp.style().objectName())
Example #28
0
def main(image,
         template,
         threshold,
         options: "NavOptions",
         blurImage=True,
         blurTemplate=True):
    global inputThreshold
    inputThreshold = threshold

    global navOptions
    navOptions = options

    global pts
    pts = []

    global finalPts
    finalPts = []

    QApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
    app = QApplication([])
    w = MainWindow()
    w.openImage(image)
    if template is not None:
        w.setTemplate(template)
        w.search()

    app.exec_()

    return finalPts, navOptions
Example #29
0
def main():
    """
    Initializing the neccessary processes
    """
    if globals.DEBUGGING:
        print("DEBUGGING MODE")
    # Start splash screen (loading)
    app = QApplication(argv)
    globals.app = app
    globals.standard_palette = app.palette(
    )  # Store standard palette if user wants to change back to the default light palette
    app.setAttribute(Qt.AA_DisableHighDpiScaling)
    MainWindow = QMainWindow()
    ui = startWindow_player()
    ui.setupUi(MainWindow)
    ui.setUpSlots()
    ui.setUpValidators()
    ui.setUpImages()
    ui.setUpTheme()
    ui.setUpFonts()
    ui.setUpMisc()
    clientNetwork = ClientNetwork(ui)
    clientNetwork.start()
    # end splash screen
    MainWindow.show()
    app.exit(app.exec_())
    clientNetwork.stop()
Example #30
0
    def run(self):
        QApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
        mainapp = QApplication(sys.argv)  # 创建GUI应用程序
        mainform = QmyMainWindow(self.flog, self.hand)  # 创建窗体
        mainform.show()

        sys.exit(mainapp.exec_())
Example #31
0
def run():
    try:
        QApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
        app = QSingleApplication(sys.argv)
        try:
            if app.isRunning():
                # 发送信息
                app.sendMessage('app is running.')
                # 激活之前的窗口
                app.activateWindow()
                sys.exit(0)
            wallet = Wallet()
            app.messageReceived.connect(wallet.singleton)
            wallet.setApp(app)
            app.setActivationWindow(wallet)
            wallet.showMaximized()
            sys.exit(app.exec_())
        except Exception as e:
            traceback.print_exc()
        finally:
            app.removeServer()
    except Exception as e:
        traceback.print_exc()
    finally:
        pass
Example #32
0
def demo_run():
    app = QApplication(sys.argv)
    # get screen size.
    desktop = QApplication.desktop().screenGeometry()
    ratio = QApplication.desktop().screen().devicePixelRatio()
    width = desktop.width()
    height = desktop.height()
    # setting up welcome screen.
    screen = QPixmap(icon["SCREEN"])
    screen.setDevicePixelRatio(ratio)
    if ratio == 2:
        # under Mac Retina
        screen = screen.scaled(height * 0.9, height * 0.9)
    else:
        # under Windows and Linux
        screen = screen.scaled(height * 0.5, height * 0.5)
    splash = QSplashScreen(screen)
    splash.show()
    # handle the main process event.
    qApp.processEvents()
    # setting up main window.
    size = (width * 0.8, height * 0.8)
    editor = KMBMainWindow(size)
    stylesheet = load_stylesheet(SS_COMMON)
    app.setStyleSheet(stylesheet)
    # Mac: set the icon in dock.
    app.setWindowIcon(editor.win_icon)
    # compatible with Mac Retina screen.
    app.setAttribute(Qt.AA_UseHighDpiPixmaps, True)
    app.setAttribute(Qt.AA_EnableHighDpiScaling, True)
    # editor show up
    editor.show()
    splash.finish(editor)
    sys.exit(app.exec_())
Example #33
0
def show(objs, options=None, interest=None):
	''' shortcut to create a QApplication showing only one view with the given objects inside.
		the functions returns when the window has been closed and all GUI destroyed
	'''
	if isinstance(objs, list):	objs = dict(enumerate(objs))
	
	import sys
	
	QApplication.setAttribute(Qt.AA_ShareOpenGLContexts, True)
	app = QApplication(sys.argv)
	
	# use the Qt color scheme if specified
	if settings.display['system_theme']: 
		settings.use_qt_colors()
	
	# create the scene as a window
	view = View(Scene(objs, options))
	view.show()
	
	# make the camera see everything
	if not interest:	interest = view.scene.box()
	view.center()
	view.adjust()
	
	err = app.exec()
	if err != 0:	print('error: Qt exited with code', err)
Example #34
0
def startShellGui(workflow_cmdline_args, preinit_funcs, postinit_funcs):
    """
    Create an application and launch the shell in it.
    """

    """
    The next two lines fix the following xcb error on Ubuntu by calling X11InitThreads before loading the QApplication:
       [xcb] Unknown request in queue while dequeuing
       [xcb] Most likely this is a multi-threaded client and XInitThreads has not been called
       [xcb] Aborting, sorry about that.
       python: ../../src/xcb_io.c:178: dequeue_pending_request: Assertion !xcb_xlib_unknown_req_in_deq failed.
    """
    platform_str = platform.platform().lower()
    if 'ubuntu' in platform_str or 'fedora' in platform_str or 'debian' in platform_str:
        QApplication.setAttribute(Qt.AA_X11InitThreads, True)

    if ilastik.config.cfg.getboolean("ilastik", "debug"):
        QApplication.setAttribute(Qt.AA_DontUseNativeMenuBar, True)

    app = QApplication([])
    _applyStyleSheet(app)

    splashScreen.showSplashScreen()
    app.processEvents()
    QTimer.singleShot( 0, functools.partial(launchShell, workflow_cmdline_args, preinit_funcs, postinit_funcs ) )
    QTimer.singleShot( 0, splashScreen.hideSplashScreen)

    return app.exec_()
Example #35
0
def main():
    """Run Halo Wars Casting Tool."""
    from hwctool.view.main import MainWindow
    from PyQt5.QtCore import QSize
    from PyQt5.QtGui import QIcon

    translator = None
    os.environ["QT_AUTO_SCREEN_SCALE_FACTOR"] = "1"

    currentExitCode = MainWindow.EXIT_CODE_REBOOT
    while currentExitCode == MainWindow.EXIT_CODE_REBOOT:
        try:
            hwctool.settings.loadSettings()
            app = QApplication(sys.argv)
            app.setAttribute(Qt.AA_EnableHighDpiScaling)
            app.setStyle(QStyleFactory.create('Fusion'))
            translator = choose_language(app, translator)

            icon = QIcon()
            icon.addFile(hwctool.settings.getResFile('hwct.ico'),
                         QSize(32, 32))
            app.setWindowIcon(icon)

            showChangelog, updater = initial_download()
            if updater:
                hwctool.settings.loadSettings()
            main_window(app, showChangelog)
            currentExitCode = app.exec_()
            app = None
        except Exception as e:
            logger.exception("message")
            break

    sys.exit(currentExitCode)
Example #36
0
def start(mode):
    # Install message handler for Qt messages
    qInstallMessageHandler(gui_msg_handler)

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

    # Start the bluesky network client
    client = GuiClient()

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

    splash = Splash()

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

    splash.show()

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

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

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

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

    # Start the Qt main loop
    app.exec_()
Example #37
0
def main():
    app = QApplication([''])
    #print(app.testAttribute(Qt.AA_UseHighDpiPixmaps))
    app.setAttribute(Qt.AA_UseHighDpiPixmaps)
    w = PadCalc()

    w.resize(250,150)
    w.move(300, 300)
    w.setWindowTitle('Padulator')
    w.show()

    sys.exit(app.exec_())
Example #38
0
class Application(object):

    def __init__(self, config, use_qt_notifications):

        # This is done dynamically so localization
        # support can be configure beforehand.
        from plover.gui_qt.main_window import MainWindow

        self._app = None
        self._win = None
        self._engine = None
        self._translator = None

        QCoreApplication.setApplicationName(__software_name__.capitalize())
        QCoreApplication.setApplicationVersion(__version__)
        QCoreApplication.setOrganizationName('Open Steno Project')
        QCoreApplication.setOrganizationDomain('openstenoproject.org')

        self._app = QApplication([])
        self._app.setAttribute(Qt.AA_UseHighDpiPixmaps)

        # Enable localization of standard Qt controls.
        self._translator = QTranslator()
        translations_dir = QLibraryInfo.location(QLibraryInfo.TranslationsPath)
        self._translator.load('qtbase_' + get_language(), translations_dir)
        self._app.installTranslator(self._translator)

        QApplication.setQuitOnLastWindowClosed(False)

        signal.signal(signal.SIGINT, lambda signum, stack: QCoreApplication.quit())

        # Make sure the Python interpreter runs at least every second,
        # so signals have a chance to be processed.
        self._timer = QTimer()
        self._timer.timeout.connect(lambda: None)
        self._timer.start(1000)

        self._engine = Engine(config, KeyboardEmulation())

        self._win = MainWindow(self._engine, use_qt_notifications)

        self._app.aboutToQuit.connect(self._win.on_quit)

    def __del__(self):
        del self._win
        del self._app
        del self._engine
        del self._translator

    def run(self):
        self._app.exec_()
        self._engine.quit()
        self._engine.wait()
    def setupClass(cls):
        """
        Start the shell and wait until it is finished initializing.
        """
        init_complete = threading.Event()

        def initTest(shell):
            cls.shell = shell
            init_complete.set()

        appCreationEvent = threading.Event()
        def createApp():
            # Create the application in the current thread.
            # The current thread is now the application main thread.
            assert threading.current_thread().getName() == "MainThread", "Error: app must be created in the main thread."
            ShellGuiTestCaseBase.app = QApplication([])
            app = ShellGuiTestCaseBase.app

            # Don't auto-quit the app when the window closes.  We want to re-use it for the next test.
            app.setQuitOnLastWindowClosed(False)

            # Create a threadRouter object that allows us to send work to the app from other threads.
            ShellGuiTestCaseBase.threadRouter = ThreadRouter(app)

            # Set the appCreationEvent so the tests can proceed after the app's event loop has started
            QTimer.singleShot(0, appCreationEvent.set )

            # Start the event loop
            app.exec_()

        # If nose was run from the main thread, exit now.
        # If nose is running in a non-main thread, we assume the main thread is available to launch the gui.
        if threading.current_thread().getName() == "MainThread":
            # Don't run GUI tests in the main thread.
            sys.stderr.write( "NOSE WAS RUN FROM THE MAIN THREAD.  SKIPPING GUI TEST\n" )
            raise nose.SkipTest
        else:
            # We're currently running in a non-main thread.
            # Start the gui IN THE MAIN THREAD.  Workflow is provided by our subclass.
            run_in_main_thread( createApp )
            appCreationEvent.wait()

        platform_str = platform.platform().lower()
        if 'ubuntu' in platform_str or 'fedora' in platform_str:
            QApplication.setAttribute(Qt.AA_X11InitThreads, True)

        if ilastik.config.cfg.getboolean("ilastik", "debug"):
            QApplication.setAttribute(Qt.AA_DontUseNativeMenuBar, True)

        # Use the thread router to launch the shell in the app thread
        ShellGuiTestCaseBase.threadRouter.routeToParent.emit( partial(launchShell, None, [], [initTest] ) )
        init_complete.wait()
Example #40
0
def createQApplication(app_name = 'Back In Time'):
    global qapp
    try:
        return qapp
    except NameError:
        pass
    if StrictVersion(QT_VERSION_STR) >= StrictVersion('5.6') and \
        hasattr(Qt, 'AA_EnableHighDpiScaling'):
        QApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
    qapp = QApplication(sys.argv + ['-title', app_name])
    if os.geteuid() == 0 and                                   \
        qapp.style().objectName().lower() == 'windows' and  \
        'GTK+' in QStyleFactory.keys():
            qapp.setStyle('GTK+')
    return qapp
Example #41
0
File: app.py Project: willingc/mu
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)
    app.setAttribute(Qt.AA_DontShowIconsInMenus)

    # Create the "window" we'll be looking at.
    editor_window = Window()
    # 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')
    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()

    # Finished starting up the application, so 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(5000)

    # Stop the program after the application finishes executing.
    sys.exit(app.exec_())
Example #42
0
            elif (event.key() == QtCore.Qt.Key_Control): # Control is Cmd in Mac.
                global modifierKeypressed
                modifierKeypressed = True
                global lastModifierKeypressDatetime
                lastModifierKeypressDatetime = datetime.now()
                return True
            else:
                #Call Base Class Method to Continue Normal Event Processing
                return super(ModifierEventFilter,self).eventFilter(receiver, event)
        else:
            #Call Base Class Method to Continue Normal Event Processing
            return super(ModifierEventFilter,self).eventFilter(receiver, event)

ef = ModifierEventFilter()
app.installEventFilter(ef)
app.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps)


class aetherMainWindow(QWebView):
    def __init__(self, reactor):
        super(aetherMainWindow, self).__init__()
        self.reactor = reactor
        self.initUI()

    def initUI(self):
        self.resize(1148, 680)
        self.move(126,300)
        self.setContextMenuPolicy(Qt.NoContextMenu)
        self.load(QUrl('file:///'+baseURL+'GUI/WebKitApp/index.html'))
        self.page().setLinkDelegationPolicy(QWebPage.DelegateAllLinks)
Example #43
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 #44
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('-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

	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)

	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
	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(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 #45
0
def main():
    global app
    # register representation factories
    baseRepresentationFactories.registerAllFactories()
    representationFactories.registerAllFactories()
    if hasattr(Qt, "AA_EnableHighDpiScaling"):
        QApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
    # initialize the app
    app = Application(sys.argv)
    app.setOrganizationName("TruFont")
    app.setOrganizationDomain("trufont.github.io")
    app.setApplicationName("TruFont")
    app.setApplicationVersion(__version__)
    app.setWindowIcon(QIcon(":app.png"))
    app.setAttribute(Qt.AA_UseHighDpiPixmaps, True)
    app.setStyleSheet(platformSpecific.appStyleSheet())

    # Install stream redirection
    app.outputWindow = OutputWindow()
    # Exception handling
    sys.excepthook = errorReports.exceptionCallback

    # Qt's translation for itself. May not be installed.
    qtTranslator = QTranslator()
    qtTranslator.load("qt_" + QLocale.system().name(),
                      QLibraryInfo.location(QLibraryInfo.TranslationsPath))
    app.installTranslator(qtTranslator)

    appTranslator = QTranslator()
    appTranslator.load("trufont_" + QLocale.system().name(),
                       os.path.dirname(os.path.realpath(__file__)) +
                       "/resources")
    app.installTranslator(appTranslator)

    # parse options and open fonts
    parser = QCommandLineParser()
    parser.setApplicationDescription(QApplication.translate(
        "Command-line parser", "The TruFont font editor."))
    parser.addHelpOption()
    parser.addVersionOption()
    parser.addPositionalArgument(QApplication.translate(
        "Command-line parser", "files"), QApplication.translate(
        "Command-line parser", "The UFO files to open."))
    parser.process(app)
    # bootstrap extensions
    folder = app.getExtensionsDirectory()
    for file in os.listdir(folder):
        if not file.rstrip("\\/ ").endswith(".tfExt"):
            continue
        path = os.path.join(folder, file)
        try:
            extension = TExtension(path)
            if extension.launchAtStartup:
                extension.run()
        except Exception as e:
            msg = QApplication.translate(
                "Extensions", "The extension at {0} could not be run.".format(
                    path))
            errorReports.showWarningException(e, msg)
            continue
        app.registerExtension(extension)
    # load menu
    if platformSpecific.useGlobalMenuBar():
        menuBar = app.fetchMenuBar()  # noqa
        app.setQuitOnLastWindowClosed(False)
    # process files
    args = parser.positionalArguments()
    if not args:
        fontPath = None
        # maybe load recent file
        settings = QSettings()
        loadRecentFile = settings.value("misc/loadRecentFile", False, bool)
        if loadRecentFile:
            recentFiles = settings.value("core/recentFiles", [], type=str)
            if len(recentFiles) and os.path.exists(recentFiles[0]):
                fontPath = recentFiles[0]
                app.openFile(fontPath)
        # otherwise, create a new file
        if fontPath is None:
            app.newFile()
    else:
        for fontPath in args:
            app.openFile(fontPath)
    sys.exit(app.exec_())
Example #46
0
    @pyqtSlot(str, int, result=QVariant)
    def getSuggest(self, text, num=10):
        return get_suggest(text, num)

    @pyqtSlot(str, result=QVariant)
    def getMainQuery(self, text):
        return get_main_query(text)

    @pyqtSlot(str)
    def playSound(self, url):
        self.getword_daemon.PlaySound(url)

    @pyqtSlot()
    def stopSound(self):
        self.getword_daemon.StopSound()


if __name__ == '__main__':
    import sys
    import signal
    from PyQt5.QtCore import Qt
    from PyQt5.QtWidgets import QApplication
    if os.name == 'posix':
        QApplication.setAttribute(Qt.AA_X11InitThreads, True)

    app = QApplication(sys.argv)
    obj = ExternalApi()

    signal.signal(signal.SIGINT, signal.SIG_DFL)
    sys.exit(app.exec_())
Example #47
0
def _firstrun():
    imotion.globalvars.logger.debug("Creating APPDIR...")
    functions.create_dir(APPDIR)


def _setlogfile():
    imotion.globalvars.logger.debug('Enabling file logging...')
    fh = logging.FileHandler(APPDIR + '/imotion.log')
    fh.setFormatter(logging.Formatter(
        '(%(asctime)s) [%(levelname)s] %(message)s'))
    fh.setLevel(logging.DEBUG)
    imotion.globalvars.logger.addHandler(fh)
    imotion.globalvars.logger.info('File logging has been started.')


if __name__ == '__main__':
    imotion.globalvars.logger = _initlogger()
    try:
        _firstrun()
        _setlogfile()
    except OSError as e:
        imotion.globalvars.logger.warning("OSError: %s" % e)
    # Init database at startup.
    # Database()
    QApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
    imotionapp = QApplication(sys.argv)
    imotionmain = ImotionMain()
    imotionmain.show()
    sys.exit(imotionapp.exec_())
Example #48
0
import tempfile
import sys

from os.path import basename, dirname, splitext
from PyQt5.QtCore import Qt, QSettings
from PyQt5.QtGui import QColor, QFont
from PyQt5.QtWidgets import QApplication
from ReText import readListFromSettings, writeListToSettings, \
 readFromSettings, writeToSettings
from ReText.highlighter import colorScheme, updateColorScheme

# For this particular test, QCoreApplication is enough. However, we should
# only have one QCoreApplication instance for all tests in a process. As
# other tests need QApplication, we should not create a bare QCoreApplication
# here. Also, keep a reference so it is not garbage collected.
QApplication.setAttribute(Qt.AA_ShareOpenGLContexts)
app = QApplication.instance() or QApplication(sys.argv)

class TestSettings(unittest.TestCase):
	def setUp(self):
		self.tempFile = tempfile.NamedTemporaryFile(prefix='retext-', suffix='.ini')
		baseName = splitext(basename(self.tempFile.name))[0]
		QSettings.setPath(QSettings.IniFormat, QSettings.UserScope,
		                  dirname(self.tempFile.name))
		self.settings = QSettings(QSettings.IniFormat,
		                          QSettings.UserScope, baseName)

	def tearDown(self):
		del self.settings # this should be deleted before tempFile

	def test_storingLists(self):
Example #49
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_())
    def __init__(self):
        # check for new Starcheat version online in seperate thread
        update_result = [None]
        update_thread = Thread(target=update_check_worker, args=[update_result], daemon=True)
        update_thread.start()

        if platform.system() == "Darwin":
            QApplication.setAttribute(QtCore.Qt.AA_DontShowIconsInMenus)

        """Display the main Starcheat window."""
        self.app = QApplication(sys.argv)
        self.window = StarcheatMainWindow(self)
        self.ui = qt_mainwindow.Ui_MainWindow()
        self.ui.setupUi(self.window)

        logging.info("Main window init")

        self.players = None
        self.filename = None

        self.item_browser = None
        # remember the last selected item browser category
        self.remember_browser = "<all>"
        self.options_dialog = None
        self.preview_armor = True
        self.preview_bg = "#ffffff"

        # connect action menu
        self.ui.actionSave.triggered.connect(self.save)
        self.ui.actionReload.triggered.connect(self.reload)
        self.ui.actionOpen.triggered.connect(self.open_file)
        self.ui.actionQuit.triggered.connect(self.app.closeAllWindows)
        self.ui.actionOptions.triggered.connect(self.new_options_dialog)
        self.ui.actionItemBrowser.triggered.connect(self.new_item_browser)
        self.ui.actionAbout.triggered.connect(self.new_about_dialog)
        self.ui.actionMods.triggered.connect(self.new_mods_dialog)
        self.ui.actionImageBrowser.triggered.connect(self.new_image_browser_dialog)

        self.ui.actionExportPlayerBinary.triggered.connect(self.export_save)
        self.ui.actionExportPlayerJSON.triggered.connect(self.export_json)
        self.ui.actionImportPlayerBinary.triggered.connect(self.import_save)
        self.ui.actionImportPlayerJSON.triggered.connect(self.import_json)

        # set up bag tables
        bags = ("head", "chest", "legs", "back", "main_bag", "object_bag",
                "tile_bag", "reagent_bag", "food_bag", "essentials", "mouse")
        for bag in bags:
            logging.debug("Setting up %s bag", bag)
            self.bag_setup(getattr(self.ui, bag), bag)

        self.preview_setup()

        # signals
        self.ui.blueprints_button.clicked.connect(self.new_blueprint_edit)
        self.ui.appearance_button.clicked.connect(self.new_appearance_dialog)
        self.ui.techs_button.clicked.connect(self.new_techs_dialog)
        self.ui.quests_button.clicked.connect(self.new_quests_dialog)
        self.ui.ship_button.clicked.connect(self.new_ship_dialog)

        self.ui.name.textChanged.connect(self.set_name)
        self.ui.male.clicked.connect(self.set_gender)
        self.ui.female.clicked.connect(self.set_gender)
        self.ui.pixels.valueChanged.connect(self.set_pixels)

        self.ui.health.valueChanged.connect(lambda: self.set_stat_slider("health"))
        self.ui.energy.valueChanged.connect(lambda: self.set_stat_slider("energy"))
        self.ui.health_button.clicked.connect(lambda: self.max_stat("health"))
        self.ui.energy_button.clicked.connect(lambda: self.max_stat("energy"))

        self.ui.copy_uuid_button.clicked.connect(self.copy_uuid)

        self.window.setWindowModified(False)

        logging.debug("Showing main window")
        self.window.show()

        # launch first setup if we need to
        if not new_setup_dialog(self.window):
            logging.error("Config/index creation failed")
            return
        logging.info("Starbound folder: %s", Config().read("starbound_folder"))

        logging.info("Checking assets hash")
        if not check_index_valid(self.window):
            logging.error("Index creation failed")
            return

        logging.info("Loading assets database")
        self.assets = Assets(Config().read("assets_db"),
                             Config().read("starbound_folder"))
        self.items = self.assets.items()

        # populate species combobox
        for species in self.assets.species().get_species_list():
            self.ui.race.addItem(species)
        self.ui.race.currentTextChanged.connect(self.update_species)

        # populate game mode combobox
        for mode in sorted(self.assets.player().mode_types.values()):
            self.ui.game_mode.addItem(mode)
        self.ui.game_mode.currentTextChanged.connect(self.set_game_mode)

        # launch open file dialog
        self.player = None
        logging.debug("Open file dialog")
        open_player = self.open_file()
        # we *need* at least an initial save file
        if not open_player:
            logging.warning("No player file selected")
            return

        self.ui.name.setFocus()

        # block for update check result (should be ready now)
        update_thread.join()
        if update_result[0]:
            update_check_dialog(self.window, update_result[0])

        sys.exit(self.app.exec_())
Example #51
0
def main():
    try:
        locale.setlocale(locale.LC_ALL, '')
    except locale.Error:
        pass # ignore this as it might fail on macOS, we'll fallback to UTF-8 in that case

    if config.get_use_fusion_gui_style():
        sys.argv += ['-style', 'fusion']

    if '--error-report' in sys.argv:
        sys.exit(error_report_main())

    # Catch all uncaught exceptions and show an error message for them.
    # PyQt5 does not silence exceptions in slots (as did PyQt4), so there
    # can be slots which try to (for example) send requests but don't wrap
    # them in an async call with error handling.
    argv = deepcopy(sys.argv) # Deep copy because QApplication (i.e. BrickViewer) constructor parses away Qt args and we want to know the style.
    if '--no-error-reporter' not in sys.argv:
        ExceptionReporter(argv)

    # Exceptions that happen before the event loop runs (f.e. syntax errors) kill the brickv so fast, that the error reporter thread
    # (which is daemonized) can not report the error before it is killed. Report them manually.
    try:
        # importing the MainWindow after creating the QApplication instance triggers this warning
        #
        #  Qt WebEngine seems to be initialized from a plugin. Please set Qt::AA_ShareOpenGLContexts
        #  using QCoreApplication::setAttribute before constructing QGuiApplication.
        #
        # do what the warnings says to avoid it
        QApplication.setAttribute(Qt.AA_ShareOpenGLContexts)

        brick_viewer = BrickViewer(sys.argv)

        if sys.platform == 'darwin':
            # workaround macOS QTBUG-61562
            from brickv.mac_pasteboard_mime_fixed import MacPasteboardMimeFixed
            mac_pasteboard_mime_fixed = MacPasteboardMimeFixed()

        splash = QSplashScreen(load_pixmap('splash.png'), Qt.WindowStaysOnTopHint)
        splash.show()

        message = 'Starting Brick Viewer ' + config.BRICKV_VERSION

        if config.INTERNAL != None:
            message += '~{}'.format(config.INTERNAL)

        splash.showMessage(message, Qt.AlignHCenter | Qt.AlignBottom, Qt.white)

        brick_viewer.processEvents()

        from brickv.mainwindow import MainWindow

        main_window = MainWindow()
        main_window.show()

        splash.finish(main_window)
    except:
        if '--no-error-reporter' in sys.argv:
            raise

        etype, value, tb = sys.exc_info()
        error = "".join(traceback.format_exception(etype, value, tb))
        error = "The following error is fatal. Exiting now.\n\n" + error

        traceback.print_exception(etype, value, tb)

        try:
            splash.close()
        except:
            pass

        # Either sys.executable is /path/to/python, then run calls /path/to/python /path/to/main.py --error-report,
        # or sys.executable is brickv[.exe], then the --error-report flag ensures, that the path to main.py is ignored.
        subprocess.run([sys.executable, os.path.realpath(__file__), "--error-report"] + argv, input=error, universal_newlines=True)
        sys.exit(1)

    sys.exit(brick_viewer.exec_())
Example #52
0
 def __init__(self):
     QApplication.__init__(self, sys.argv)
     QApplication.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps)
     QApplication.setQuitOnLastWindowClosed(False)
Example #53
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')

	if hasattr(Qt, 'AA_ShareOpenGLContexts'):
		# Needed for Qt WebEngine on Windows
		QApplication.setAttribute(Qt.AA_ShareOpenGLContexts)
	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)
	initializeDataDirs()
	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
	readStdIn = False
	if globalSettings.openLastFilesOnStartup:
		window.restoreLastOpenedFiles()
	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
		elif fileName == '-':
			readStdIn = True

	inputData = ''
	if readStdIn and sys.stdin is not None:
		if sys.stdin.isatty():
			print('Reading stdin, press ^D to end...')
		inputData = 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())