示例#1
0
def update_db_schema(db_path):
    if QMessageBox().warning(
            None, QApplication.translate('DB', "Database format is outdated"),
            QApplication.translate(
                'DB', "Do you agree to upgrade your data to newer format?"),
            QMessageBox.Yes, QMessageBox.No) == QMessageBox.No:
        return LedgerInitError(LedgerInitError.OutdatedDbSchema)

    db = sqlite3.connect(get_dbfilename(db_path))
    cursor = db.cursor()
    try:
        cursor.execute("SELECT value FROM settings WHERE name='SchemaVersion'")
    except:
        return LedgerInitError(LedgerInitError.DbInitFailure)

    schema_version = cursor.fetchone()[0]
    for step in range(schema_version, Setup.TARGET_SCHEMA):
        delta_file = db_path + Setup.UPDATES_PATH + os.sep + Setup.UPDATE_PREFIX + f"{step+1}.sql"
        logging.info(
            f"Applying delta schema {step}->{step+1} from {delta_file}")
        try:
            with open(delta_file) as delta_sql:
                try:
                    cursor.executescript(delta_sql.read())
                except sqlite3.OperationalError as e:
                    return LedgerInitError(LedgerInitError.SQLFailure,
                                           e.args[0])
        except FileNotFoundError:
            return LedgerInitError(LedgerInitError.NoDeltaFile, delta_file)
    db.close()
    return LedgerInitError(LedgerInitError.DbInitSuccess)
示例#2
0
        def decorated_function(*args, **kwargs):

            QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))

            normal_function(*args, **kwargs)

            QApplication.restoreOverrideCursor()
示例#3
0
 def append_data(self, x_data: float, y_data: float) -> None:
     self.x_data.append(x_data)
     self.y_data.append(y_data)
     self.plot_data_item.setData(self.x_data, self.y_data)
     if len(self.x_data) == self.x_range:
         self.plot_widget.setXRange(self.x_data[0], self.x_data[-1])
     QApplication.processEvents()
示例#4
0
def run(optimiser):
    app = QApplication(sys.argv)

    # Thread for running slow parts of the optimiser without pausing GUI

    opt_worker = OptWorker(optimiser)
    opt_thread = QThread()

    opt_worker.moveToThread(opt_thread)

    app.aboutToQuit.connect(opt_thread.quit)

    opt_thread.start()

    # Queue and thread for updating text field
    queue = Queue()
    sys.stdout = WriteStream(queue)

    window = BayesOptWindow(optimiser, opt_worker)
    window.show()

    write_thread = QThread()
    receiver = Receiver(queue)
    receiver.signal.connect(window.write_to_textfield)
    receiver.moveToThread(write_thread)
    write_thread.started.connect(receiver.run)
    app.aboutToQuit.connect(write_thread.quit)

    write_thread.start()

    # app.exec_()

    sys.exit(app.exec_())
示例#5
0
    def __init__(self):

        # gui
        self.app = QApplication([])
        self.main_window = MainWindow(controller=self)

        # device
        self.device = Device()

        # fps stats
        self.fps_timer = QTimer()
        self.fps_timer.timeout.connect(self.update_ui_fps)
        self.spf = 1  # seconds per frame
        self.timestamp_last_capture = 0

        # acquisition thread
        self.continuous_acquisition = False
        self.worker_wait_condition = QWaitCondition()
        self.acquisition_worker = AcquisitionWorker(self.worker_wait_condition,
                                                    device=self.device)
        self.acquisition_thread = QThread()
        self.acquisition_worker.moveToThread(self.acquisition_thread)
        self.acquisition_thread.started.connect(self.acquisition_worker.run)
        self.acquisition_worker.finished.connect(self.acquisition_thread.quit)
        # self.acquisition_worker.finished.connect(self.acquisition_thread.deleteLater)
        # self.acquisition_thread.finished.connect(self.acquisition_worker.deleteLater)
        self.acquisition_worker.data_ready.connect(self.data_ready_callback)
        self.acquisition_thread.start()

        # default timebase
        self.set_timebase("20 ms")

        # on app exit
        self.app.aboutToQuit.connect(self.on_app_exit)
示例#6
0
async def show_game_session(app: QtWidgets.QApplication, options, session_id: int):
    from randovania.gui.game_session_window import GameSessionWindow
    from randovania.gui.lib.qt_network_client import QtNetworkClient
    from randovania.interface_common.preset_manager import PresetManager

    network_client: QtNetworkClient = app.network_client

    sessions = [
        session
        for session in await network_client.get_game_session_list(False)
        if session.id == session_id
    ]
    if not sessions:
        app.quit()
        return
    await network_client.join_game_session(sessions[0], None)

    preset_manager = PresetManager(options.presets_path)

    app.game_session_window = await GameSessionWindow.create_and_update(
        network_client,
        app.game_connection,
        preset_manager,
        None,
        options
    )
    app.game_session_window.show()
示例#7
0
 def __init__(self):
     self.app = QApplication(sys.argv)
     self.loadSettings()
     self.login = None
     self.main = None
     self.key = ''
     self.data = {}
示例#8
0
    def show_game(self, display: GameDisplay):
        QApplication.setOverrideCursor(Qt.WaitCursor)
        self.display = display
        start_state = display.start_state
        self.start_state = start_state
        collection_name = self.get_collection_name()
        self.setWindowTitle(f'{collection_name} - {start_state.game_name}')
        self.ui.game_name.setText(start_state.game_name)
        settings = get_settings(start_state)
        is_locked = settings.value('searches_locked', False, bool)
        self.ui.searches_lock1.setChecked(is_locked)
        self.ui.searches_lock2.setChecked(is_locked)
        search_count = settings.value('searches', 600, int)
        self.ui.searches1.setValue(search_count)
        self.ui.searches2.setValue(search_count)
        self.ui.shuffle_players.setChecked(
            settings.value('shuffle_players', False, bool))
        heuristics = self.load_heuristics()
        player1_index = settings.value('player_1', 0, int)
        player2_index = settings.value('player_2', 0, int)
        self.ui.player1.clear()
        self.ui.player2.clear()
        self.ui.player1.addItem('Human', None)
        self.ui.player2.addItem('Human', None)
        for name, heuristic in heuristics:
            self.ui.player1.addItem(name, heuristic)
            self.ui.player2.addItem(name, heuristic)

        self.ui.player1.setCurrentIndex(player1_index)
        self.ui.player2.setCurrentIndex(player2_index)
        self.ui.stacked_widget.setCurrentWidget(self.ui.players_page)
        self.board_to_resume = None
        self.on_toggle_review()
        QApplication.restoreOverrideCursor()
示例#9
0
    def __init__(self):
        """ Sets up the Qt UI. """

        super().__init__()
        QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_ShareOpenGLContexts)

        signal.signal(signal.SIGINT, signal.SIG_DFL)  # fix SIGINT handling - cleanly exit on ctrl+c

        self.app = QApplication.instance() or QApplication([])

        try:
            import qt_material

            qt_material.apply_stylesheet(self.app, 'light_blue.xml')
        except ImportError:
            pass

        self.ui_file = QtCore.QFile(os.path.dirname(os.path.realpath(__file__)) + '/qt.ui')
        self.loader = QUiLoader()
        self.loader.registerCustomWidget(ViewSBQTreeWidget)
        self.loader.registerCustomWidget(ViewSBHexView)
        self.window = self.loader.load(self.ui_file) # type: QMainWindow

        # Swap columns 0 and 5 to put the expand arrow on the summary column.
        self.window.usb_tree_widget.header().swapSections(self.COLUMN_SUMMARY, self.COLUMN_SEQUENCE)

        self.window.usb_tree_widget.header().setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)

        self.window.update_timer = QtCore.QTimer()
        self.window.update_timer.timeout.connect(self._update)

        self.window.usb_tree_widget.currentItemChanged.connect(self._tree_current_item_changed)

        self.window.usb_tree_widget = self.window.usb_tree_widget
        self.window.usb_tree_widget.sortByColumn(0, Qt.SortOrder.AscendingOrder)
示例#10
0
 def update_db_schema(self, db_path) -> JalDBError:
     if QMessageBox().warning(
             None,
             QApplication.translate('DB', "Database format is outdated"),
             QApplication.translate(
                 'DB',
                 "Do you agree to upgrade your data to newer format?"),
             QMessageBox.Yes, QMessageBox.No) == QMessageBox.No:
         return JalDBError(JalDBError.OutdatedDbSchema)
     db = db_connection()
     version = readSQL(
         "SELECT value FROM settings WHERE name='SchemaVersion'")
     try:
         schema_version = int(version)
     except ValueError:
         return JalDBError(JalDBError.DbInitFailure)
     for step in range(schema_version, Setup.TARGET_SCHEMA):
         delta_file = db_path + Setup.UPDATES_PATH + os.sep + Setup.UPDATE_PREFIX + f"{step + 1}.sql"
         logging.info(
             f"Applying delta schema {step}->{step + 1} from {delta_file}")
         error = self.run_sql_script(delta_file)
         if error.code != JalDBError.NoError:
             db.close()
             return error
     return JalDBError(JalDBError.NoError)
示例#11
0
def cli(ctx, config, verbose, no_color, option):
    """
    Initialises the cli grouping with default options.
    """
    ctx.ensure_object(dict)

    init_logging(verbose, no_color, config)

    options = dict(option)

    ctx.obj["config"] = Config(
        config_path=config,
        argv={k: yaml.load(v, yaml.SafeLoader)
              for k, v in options.items()},
        env=os.environ,
    )

    if ctx.invoked_subcommand is None:
        app = QApplication(sys.argv)

        widget = MainWindow(ctx.obj["config"],
                            lambda p: init_logging(verbose, no_color, p))
        widget.show()

        sys.exit(app.exec_())
示例#12
0
文件: main.py 项目: dryerem/PyChat
def main():
    # initialize
    app = QApplication([])

    # create connection to the server
    client = Client(address=('127.0.0.1', 8888), debug=True)
    client.client_connect()

    # create a main window
    window = MainWindow(window_width=400, window_height=600)
    window.setWindowTitle("Python chat")

    # waiting for messages
    global client_worker, network_thread  # TODO: refactor this
    network_thread = QThread()
    network_thread.setTerminationEnabled(True)
    client_worker = ClientWorker(client_socket=client.client())
    client_worker.recieved_message.connect(window.recieved_message_handler)
    client_worker.moveToThread(network_thread)
    network_thread.started.connect(client_worker.start)
    network_thread.start()

    window.show()

    return app.exec_()
示例#13
0
    def __init__(self, model: Model) -> None:
        super().__init__()

        self.model = model

        self.setWindowTitle(getTitleString('Mod Manager'))
        self.setMinimumSize(QSize(750, 500))
        self.setupMenu()

        settings = QSettings()
        if settings.value('mainWindowGeometry'):
            self.restoreGeometry(
                settings.value('mainWindowGeometry'))  # type: ignore
        if settings.value('mainWindowState'):
            self.restoreState(
                settings.value('mainWindowState'))  # type: ignore

        # TODO: enhancement: add an url handler for 'nxm://' urls
        # see https://docs.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/platform-apis/aa767914(v=vs.85)  # noqa

        # TODO: enhancement: import settings from the witcher 3 mod manager

        QApplication.clipboard().dataChanged.connect(
            self.copyBufferChangedEvent)

        self.mainwidget = MainWidget(self, model)
        self.setCentralWidget(self.mainwidget)
        self.show()
        self.raise_()
        self.activateWindow()
示例#14
0
def run():
    # Be able to close with Ctrl+C in the terminal once Qt is started https://stackoverflow.com/a/5160720
    signal.signal(signal.SIGINT, signal.SIG_DFL)

    arguments = sys.argv
    # Remove warning about invalid style override
    arguments.extend(['-style', 'Fusion'])
    app = QApplication(arguments)
    apply_dark_theme(app)

    # Show splash screen
    pixmap = QPixmap(':/icons/splash.png')
    splash = QSplashScreen(pixmap)
    splash.setWindowTitle('The Little Hat')
    splash.showMessage('loading...',
                       alignment=Qt.AlignBottom | Qt.AlignCenter,
                       color=Qt.white)
    splash.show()
    app.processEvents()

    window = MainWindow(app)

    window.show()
    splash.finish(window)
    return app.exec_()
示例#15
0
def main():
    app = QApplication(sys.argv)

    main_window = MainWindow()
    main_window.show()

    sys.exit(app.exec_())
示例#16
0
def run():
    app = QApplication(sys.argv)

    ruler = Ruler()
    ruler.show()

    app.exec_()
示例#17
0
def main() -> None:
    """Mainline for interactive review of layout."""
    app = QApplication(sys.argv)
    win = MainWin()
    win.exit_action.triggered.connect(sys.exit)
    win.show()
    app.exec()
示例#18
0
 def center(self):
     """Center Window on the Current Screen,with Multi-Monitor support."""
     window_geometry = self.frameGeometry()
     mousepointer_position = QApplication.desktop().cursor().pos()
     screen = QApplication.desktop().screenNumber(mousepointer_position)
     centerPoint = QApplication.desktop().screenGeometry(screen).center()
     window_geometry.moveCenter(centerPoint)
     self.move(window_geometry.topLeft())
示例#19
0
def main():
    app = QApplication([])
    QtWebEngine.initialize()
    engine = QQmlApplicationEngine()
    qml_file_path = os.path.join(os.path.dirname(__file__), 'browser.qml')
    qml_url = QUrl.fromLocalFile(os.path.abspath(qml_file_path))
    engine.load(qml_url)
    app.exec_()
示例#20
0
def main():
    app = QApplication(sys.argv)
    window = MainWindow()

    window.show()

    # exit code == PySide returned val
    sys.exit(app.exec_())
示例#21
0
 def slot_copy_js_code(self) -> None:
     QApplication.clipboard().setText(
         'javascript:var script = document.createElement("script");script.src = "http://localhost:10241/static/bridge.js";document.body.appendChild(script);'
     )
     self.api.show_message(
         'CExplore Bridge',
         'Copied JS code to clipboard.\nPaste it as the url to a bookmark.\nThen go open the CExplore instance and click on the bookmark to connect.'
     )
示例#22
0
 def closeEvent(self, event):
     self.data.save({
         'width': self.width(),
         'height': self.height(),
         'optionsOpened': self.options_window.isVisible()
     })
     event.accept()
     QApplication.quit()
示例#23
0
def main():
    import sys

    pg.setConfigOptions(antialias=True)
    app = QApplication(sys.argv)
    mainwindow = MainWindow()
    mainwindow.show()
    sys.exit(app.exec_())
示例#24
0
def draw(game):
    app = QApplication()

    widget = MyWidget(game)
    widget.resize(800, 600)
    widget.show()

    sys.exit(app.exec_())
示例#25
0
def main():

    app = QApplication(sys.argv)
    app.setStyle('Fusion')
    ex = MainWindow()
    ex.show()
    print("here goes")
    sys.exit(app.exec_())
示例#26
0
class Dephaser(object):
    def __init__(self):
        self.app = QApplication(sys.argv)

    def run(self):
        self.main = MainWidget(self)
        self.main.resize(1200, 400)
        self.main.show()
        self.app.exec()
def main():
    """main function
    """
    app = QApplication(sys.argv)
    ui = main_ui.Ui_MainWindow()
    window = MainWindow(app, ui)
    atexit.register(window._exit)
    window.show()
    sys.exit(app.exec_())
 def __init__(self):
     """Show the main application window"""
     app = QApplication(sys.argv)
     # Open the main window
     self._main_window = SimilaritiesWindow()
     self._main_window.show()
     self._main_window.do_show_loaded_songs_gui_action()
     # Quit when the user exits the program
     sys.exit(app.exec_())
示例#29
0
def test():
    import sys

    from PySide6.QtWidgets import QApplication

    app = QApplication(sys.argv)
    mainWindow = MainWindow()
    mainWindow.show()
    sys.exit(app.exec_())
示例#30
0
async def show_main_window(app: QtWidgets.QApplication, options, is_preview: bool):
    from randovania.interface_common.preset_manager import PresetManager
    from randovania.interface_common.options import Options
    options = typing.cast(Options, options)
    preset_manager = PresetManager(options.presets_path)

    logger.info("Loading user presets...")
    await preset_manager.load_user_presets()
    logger.info("Finished loading presets!")

    from randovania.gui.lib.qt_network_client import QtNetworkClient
    network_client: QtNetworkClient = app.network_client

    async def attempt_login():
        from randovania.network_client.network_client import UnableToConnect
        from randovania.gui.lib import async_dialog

        try:
            from randovania.gui import main_online_interaction
            if not await main_online_interaction.ensure_logged_in(None, network_client):
                await async_dialog.warning(None, "Login required",
                                           "Logging in is required to use dev builds.")
                return False

        except UnableToConnect as e:
            s = e.reason.replace('\n', '<br />')
            await async_dialog.warning(
                None, "Connection Error",
                f"<b>Unable to connect to the server:</b><br /><br />{s}<br /><br />"
                f"Logging in is required to use dev builds.")
            return False

        return True

    if randovania.is_frozen() and randovania.is_dev_version():
        try:
            logger.info("Disabling quit on last window closed")
            app.setQuitOnLastWindowClosed(False)
            if not await attempt_login():
                app.quit()
                return
        finally:
            def reset_last_window_quit():
                logger.info("Re-enabling quit on last window closed")
                app.setQuitOnLastWindowClosed(True)

            QtCore.QTimer.singleShot(1000, reset_last_window_quit)

    from randovania.gui.main_window import MainWindow
    logger.info("Preparing main window...")
    main_window = MainWindow(options, preset_manager, network_client, is_preview)
    app.main_window = main_window

    logger.info("Displaying main window")
    main_window.show()
    await main_window.request_new_data()