Exemplo n.º 1
0
    def start(self):
        self._request_rerender([self._root], {})
        if self._inspector:
            logger.info("Running inspector")

            def cleanup(e):
                self._inspector_component = None

            self._inspector_component = inspector.Inspector(
                self._render_engine._component_tree,
                self._root,
                refresh=(lambda:
                         (self._render_engine._component_tree, self._root)))
            icon_path = os.path.join(
                os.path.abspath(os.path.dirname(__file__)),
                "inspector/icon.png")
            component = Window(title="Component Inspector",
                               on_close=cleanup,
                               icon=icon_path)(self._inspector_component)
            component._edifice_internal_parent = None
            self._request_rerender([component], {})

        loop = QEventLoop(self.app)
        asyncio.set_event_loop(loop)
        with loop:
            ret = loop.run_forever()
        self._render_engine._delete_component(self._root, True)
        return ret
Exemplo n.º 2
0
def run(show_config: bool):
    from PyQt5.QtWidgets import QApplication
    from qasync import QEventLoop
    from fastocr.i18n import Translation
    from fastocr.tray import AppTray

    if sys.platform not in ['win32', 'darwin', 'cygwin'] and instance_already_running():
        AppLogger().info('only one instance running allowed')
        sys.exit(1)

    def quit_application(code):
        QApplication.quit()
        sys.exit(code)

    app = QApplication(sys.argv)
    Translation().load().install(app)
    loop = QEventLoop(app)
    asyncio.set_event_loop(loop)
    loop = asyncio.get_event_loop()
    for s in [signal.SIGINT, signal.SIGTERM]:
        loop.add_signal_handler(s, partial(quit_application, s))
    if DesktopInfo.dbus_supported():
        from fastocr.bus import app_dbus
        app_dbus.tray = AppTray(bus=app_dbus)
        app_dbus.tray.show()
        if show_config:
            app_dbus.tray.open_setting()
    else:
        tray = AppTray()
        tray.show()
        if show_config:
            tray.open_setting()
    with loop:
        sys.exit(loop.run_forever())
Exemplo n.º 3
0
def main() -> int:
    """
    This is the main entry point of the application.
    We must import packages here, in the function, rather than globally, because the logging subsystem
    must be set up correctly at the import time.
    """
    import atexit
    import asyncio
    import datetime
    from PyQt5.QtWidgets import QApplication
    from qasync import QEventLoop
    from . import data_dir, version, resources
    from .fuhrer import Fuhrer

    data_dir.init()

    # Only the main process will be logging into the file
    log_file_name = os.path.join(
        data_dir.LOG_DIR,
        f"{datetime.datetime.now():%Y%m%d-%H%M%S}-{os.getpid()}.log")
    file_handler = logging.FileHandler(log_file_name)
    file_handler.setLevel(LOGGING_LEVEL)
    file_handler.setFormatter(
        logging.Formatter(
            "%(asctime)s pid=%(process)-5d %(levelname)-8s %(name)s: %(message)s"
        ))
    logging.root.addHandler(file_handler)

    if "--profile" in sys.argv:
        try:
            # noinspection PyPep8Naming
            import cProfile as profile
        except ImportError:
            import profile

        def save_profile():
            prof.disable()
            prof.dump_stats(log_file_name.replace(".log", ".pstat"))

        prof = profile.Profile()
        atexit.register(save_profile)
        prof.enable()

    # Configuring the event loop
    app = QApplication(sys.argv)
    loop = QEventLoop(app)
    asyncio.set_event_loop(loop)

    # Running the application
    _logger.info(
        "Starting version %r; package root: %r",
        version.__version__,
        resources.PACKAGE_ROOT,
    )
    with loop:
        ctrl = Fuhrer()
        loop.run_until_complete(ctrl.run())

    return 0
Exemplo n.º 4
0
def windowLauncher():
    app = QtWidgets.QApplication(sys.argv)
    loop = QEventLoop(app)
    asyncio.set_event_loop(loop)

    win = MainWindow()
    win.show()
    loop.run_forever()
def main():
    app = QtWidgets.QApplication(sys.argv)
    loop = QEventLoop(app)
    asyncio.set_event_loop(loop)  # NEW must set the event loop

    win = cplib.MainWindow()
    win.show()

    with loop:  ## context manager calls .close() when loop completes, and releases all resources
        loop.run_until_complete(run(win, cp, loop))
Exemplo n.º 6
0
    def __init__(self):

        self.args = args = get_argparser().parse_args()
        init_logger_from_args(args)

        if args.log_to_file:
            log_file = pkg_resources.resource_filename("wand", "log.txt")
            fh = logging.FileHandler(log_file, mode="wt")
            fh.setLevel(logger.getEffectiveLevel())
            logger.addHandler(fh)
            logging.getLogger("qasync").addHandler(fh)
            sys.excepthook = lambda exc_type, exc_value, exc_traceback: \
                logger.exception("".join(
                    traceback.format_exception(exc_type,
                                               exc_value,
                                               exc_traceback)))

        self.config = load_config(args, "_gui")

        self.laser_db = {}
        self.freq_db = {}
        self.osa_db = {}
        self.subscribers = {}

        self.qapp = QtWidgets.QApplication(["WAnD"])
        self.loop = QEventLoop(self.qapp)
        asyncio.set_event_loop(self.loop)
        atexit.register(self.loop.close)

        # set program icon
        icon = QtGui.QIcon()
        icon.addFile(pkg_resources.resource_filename("wand", "wand.svg"))
        self.qapp.setWindowIcon(icon)

        # create main window
        self.win = MainWindow()
        self.area = dock.DockArea()
        self.win.setCentralWidget(self.area)
        self.win.setWindowTitle("Super-duper Python Wavemeter Viewer!")

        # populate GUI
        self.laser_displays = {}
        for row in self.config["layout"]:
            prev = None
            pos = 'bottom'
            for display_name in row:
                display = LaserDisplay(display_name, self)
                self.laser_displays.update({display.laser: display})
                self.area.addDock(display.dock, position=pos, relativeTo=prev)
                pos = 'right'
                prev = display.dock
Exemplo n.º 7
0
def main():
    app = QtWidgets.QApplication(sys.argv)
    loop = QEventLoop(app)

    asyncio.set_event_loop(loop)

    engine = Engine()

    controller = Controller(app, loop, engine)

    with loop:

        loop.run_forever()

    engine.terminate = True
Exemplo n.º 8
0
    def __init__(
        self,
        show_shell: bool = True,
        show_events: bool = True,
        show_status: bool = True,
        show_modules: Optional[List[str]] = None,
        widgets: Optional[List[Dict[str, Any]]] = None,
        sidebar: Optional[List[Dict[str, Any]]] = None,
        *args: Any,
        **kwargs: Any,
    ):
        """Inits a new GUI.

        Args:
            show_shell: Whether to show the shell page.
            show_events: Whether to show the events page.
            show_modules: If not empty, show only listed modules.
            widgets: List of custom widgets.
            sidebar: List of custom sidebar widgets.
        """

        # init Qt with asyncio
        self._app = QtWidgets.QApplication(sys.argv)
        loop = QEventLoop(self._app)
        asyncio.set_event_loop(loop)

        # init module
        Module.__init__(self, *args, **kwargs)
        self._window: Optional[MainWindow] = None
        self._show_shell = show_shell
        self._show_events = show_events
        self._show_status = show_status
        self._show_modules = show_modules
        self._custom_widgets = widgets
        self._custom_sidebar_widgets = sidebar
Exemplo n.º 9
0
def show(path: str, second_screen: bool = False) -> int:
    if not QApplication.instance():
        app = QApplication()
    else:
        app = QApplication.instance()
    app.setAttribute(Qt.AA_UseHighDpiPixmaps)

    # setup asyncio loop
    loop = QEventLoop(app)
    asyncio.set_event_loop(loop)

    # create widget
    widget = SketchViewer(pathlib.Path(path))

    # handle window sizing
    screens = app.screens()
    if second_screen and len(screens) > 1:
        widget.windowHandle().setScreen(screens[1])
        r = screens[1].geometry()
        widget.move(r.topLeft())
        widget.resize(r.width(), r.height())
    else:
        sz = app.primaryScreen().availableSize()
        widget.move(int(sz.width() * 0.05), int(sz.height() * 0.1))
        widget.resize(int(sz.width() * 0.9), int(sz.height() * 0.8))

    # run
    widget.show()
    return app.exec_()
Exemplo n.º 10
0
    def _connect_ui(self):

        if not self._wait_for_mainwindow:
            return
        self._wait_for_mainwindow = False
        self._iface.initializationCompleted.disconnect(self._connect_ui)

        try:
            app = QCoreApplication.instance()
            self._loop = QEventLoop(app, already_running = True)
            set_event_loop(self._loop)
        except Exception as e:
            msg_critical(e, self._mainwindow)
            return

        try:
            config = Config(os.path.join(get_config_path(), CONFIG_FN))
            self._fsm = Fsm(config = config)
        except Exception as e:
            msg_critical(e, self._mainwindow)
            return

        for name in self._action_names:
            self._ui_dict[f'action_{name:s}'].triggered.connect(self._sync(getattr(self, f'_{name:s}')))

        for name in ('connect', 'new'):
            self._ui_dict[f'action_{name:s}'].setEnabled(True)
Exemplo n.º 11
0
def _main(port: int) -> None:
    for sig in [signal.SIGINT]:
        signal.signal(sig, signal_handler)

    app, main_window = ui_proxy.create_app(
        bridge.get_md_action,
        bridge.get_md_data,
        bridge.key_up_callback,
        bridge.md_action_changed,
        bridge.md_data_changed,
    )
    loop = QEventLoop(app)
    asyncio.set_event_loop(loop)
    with loop:
        main_window.show()
        loop.run_until_complete(_setup_listeners(port, main_window.ui))
    sys.exit(0)
Exemplo n.º 12
0
def run(argv=None):
    if argv is None:
        argv = sys.argv[1:]

    p = argparse.ArgumentParser()
    p.add_argument('-l', '--local-qml', dest='local_qml', action='store_true',
        help='Use local qml files (development mode)',
    )
    p.add_argument('--palette', dest='palette', choices=['system', 'dark'], default='dark')
    args, remaining = p.parse_known_args(argv)

    if not resource_manager.ready:
        resource_manager.build_missing()
        assert resource_manager.ready is True

    QApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
    app = QApplication(remaining)
    QtGui.QIcon.setThemeName('fa-icons')
    loop = QEventLoop(app)
    asyncio.set_event_loop(loop)
    app.setOrganizationName('jvconnected')
    app.setApplicationName('jvconnected')
    engine = QtQml.QQmlApplicationEngine()
    if args.local_qml:
        logger.debug('Using local qml files')
        qml_import = str(QML_PATH)
        qml_main = str(QML_PATH / 'main.qml')
    else:
        check_qrc_hash()
        qml_import = 'qrc:/qml'
        qml_main = 'qrc:/qml/main.qml'
    register_qml_types()
    engine.addImportPath(qml_import)
    palette_manager = palette.PaletteManager(
        qmlEngine=engine,
        defaultPaletteName=args.palette,
    )
    context = engine.rootContext()
    context.setContextProperty('paletteManager', palette_manager)

    engine.load(qml_main)
    win = engine.rootObjects()[0]
    win.show()
    with loop:
        sys.exit(loop.run_forever())
Exemplo n.º 13
0
def entry_with_args(
    initial_dir: Optional[str] = None,
    install_context: Optional[bool] = False,
    uninstall_context: Optional[bool] = False,
):
    '''
    :param initial_dir: Initial directory
    :param install_context: Install the organizer in right click context menu (Windows)
    :param uninstall_context: Uninstall the organizer in right click context menu (Windows)
    '''
    if install_context:
        register_context_menu()
    elif uninstall_context:
        register_context_menu(uninstall=True)
    else:
        app = QApplication(sys.argv)
        loop = QEventLoop(app)
        asyncio.set_event_loop(loop)

        with loop:
            window = MainWindow(initial_dir)
            window.show()
            loop.run_forever()
Exemplo n.º 14
0
def run_app():
    app = QtWidgets.QApplication(sys.argv)
    app.setStyle("fusion")

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

    # if sys.platform == 'win32':
    #     asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy())

    pixmap = load_pixmap("splash.svg")
    message = "Version: {}".format(pymontecarlo_gui.__version__)
    splash_screen = QtWidgets.QSplashScreen(pixmap)
    splash_screen.showMessage(message, QtCore.Qt.AlignRight)
    splash_screen.show()
    app.processEvents()

    window = MainWindow()
    window.show()

    splash_screen.finish(window)

    with loop:
        sys.exit(loop.run_forever())
Exemplo n.º 15
0
def main():
    # initialize application
    args = get_argparser().parse_args()
    if args.db_file is None:
        args.db_file = os.path.join(get_user_config_dir(),
                                    "artiq_browser.pyon")
    widget_log_handler = log.init_log(args, "browser")

    app = QtWidgets.QApplication(["ARTIQ Browser"])
    loop = QEventLoop(app)
    asyncio.set_event_loop(loop)
    atexit.register(loop.close)

    datasets_sub = models.LocalModelManager(datasets.Model)
    datasets_sub.init({})

    smgr = state.StateManager(args.db_file)

    browser = Browser(smgr, datasets_sub, args.browse_root, args.server,
                      args.port)
    widget_log_handler.callback = browser.log.append_message

    if os.name == "nt":
        # HACK: show the main window before creating applets.
        # Otherwise, the windows of those applets that are in detached
        # QDockWidgets fail to be embedded.
        browser.show()
    smgr.load()
    smgr.start()
    atexit_register_coroutine(smgr.stop)

    if args.select is not None:
        browser.files.select(args.select)

    browser.show()
    loop.run_until_complete(browser.exit_request.wait())
Exemplo n.º 16
0
    # argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('--debug', action='store_true')
    args = parser.parse_args()

    # logger
    logger = logging.getLogger()
    if args.debug:
        hdlr = logging.FileHandler(Path('logs/session.log'))
        logger.addHandler(hdlr)
        logger.addHandler(logging.StreamHandler())
        logger.setLevel(logging.INFO)

    # ChampSelect
    champselect = ChampSelect()

    # Qt
    app = QApplication([])
    loop = QEventLoop(app)
    asyncio.set_event_loop(loop)

    window = MainWindow(logger=logger)
    window.resize(1200, 930)
    window.show()

    try:
        with loop:
            loop.run_until_complete(main())
    except RuntimeError:
        pass
Exemplo n.º 17
0
def main(gamePath: Optional[str] = None,
         configPath: Optional[str] = None,
         startupMode: StartupMode = StartupMode.Main) -> NoReturn:

    from w3modmanager.util.util import getRuntimePath
    from w3modmanager.core.model import Model
    from w3modmanager.core.errors import OtherInstanceError, InvalidGamePath, InvalidConfigPath
    from w3modmanager.ui.graphical.mainwindow import MainWindow
    from w3modmanager.domain.web.nexus import closeSession
    from w3modmanager.domain.system.permissions import \
        getWritePermissions, setWritePermissions

    from PySide6.QtCore import Qt, QSettings
    from PySide6.QtWidgets import QApplication, QMessageBox
    from PySide6.QtGui import QIcon, QPalette, QFont

    from qasync import QEventLoop

    QApplication.setOrganizationName(w3modmanager.ORG_NAME)
    QApplication.setOrganizationDomain(w3modmanager.ORG_URL)
    QApplication.setApplicationName(w3modmanager.TITLE)
    QApplication.setApplicationVersion(w3modmanager.VERSION)
    QApplication.setApplicationDisplayName('')
    QApplication.setAttribute(Qt.AA_NativeWindows)

    app = QApplication(sys.argv)
    app.setStyleSheet('''
        Link { text-decoration: none; }
    ''')

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

    palette = QPalette(QApplication.palette())
    palette.setColor(QPalette.Link, Qt.red)
    palette.setColor(QPalette.LinkVisited, Qt.red)
    palette.setColor(QPalette.PlaceholderText, Qt.gray)
    app.setPalette(palette)

    font = QFont('Segoe UI')
    font.setStyleHint(QFont.System)
    font.setWeight(QFont.Normal)
    font.setStyleStrategy(QFont.PreferDevice)
    font.setPointSize(9)
    app.setFont(font)

    icon = QIcon()
    icon.addFile(str(getRuntimePath('resources/icons/w3b.ico')))
    app.setWindowIcon(icon)

    pool = ThreadPoolExecutor()
    asyncio.get_running_loop().set_default_executor(pool)

    # configure startup overrides
    settings = QSettings()
    if gamePath:
        settings.setValue('gamePath', gamePath)
    if configPath:
        settings.setValue('configPath', configPath)
    if startupMode == StartupMode.About:
        MainWindow.showAboutDialog(None).exec_()
        sys.exit()
    if startupMode == StartupMode.Settings:
        MainWindow.showSettingsDialog(None).exec_()
        sys.exit()

    exception_hook_set = False

    def createModel(ignorelock: bool = False) -> Model:
        nonlocal settings
        return Model(
            Path(str(settings.value('gamePath'))),
            Path(str(settings.value('configPath'))),
            Path(
                appdirs.user_data_dir(w3modmanager.NAME,
                                      w3modmanager.ORG_NAME)), ignorelock)

    try:
        # try to initialize the mod management model
        try:
            model = createModel()
        # if another instance is already open, inform and ask to open anyway
        except OtherInstanceError as e:
            if MainWindow.showOtherInstanceDialog(
                    None).exec_() == QMessageBox.Yes:
                model = createModel(True)
            else:
                raise e
        # if game path or config path is invalid or not set,
        # show a special settings dialog and retry
        except (InvalidGamePath, InvalidConfigPath):
            MainWindow.showSettingsDialog(None, True).exec_()
            model = createModel()

        # check for write access to the game and config directories
        for path in (
                model.gamepath,
                model.configpath,
                model.cachepath,
        ):
            if not getWritePermissions(path):
                if MainWindow.showInvalidPermissionsDialog(None, path).exec_() != QMessageBox.Yes \
                or not setWritePermissions(path):
                    raise PermissionError(f'Not enough permissions for {path}')

        window = MainWindow(model)
        app.setActiveWindow(window)

        def show_exception_hook(exctype, value, tb) -> None:  # noqa
            nonlocal window
            MainWindow.showCritcalErrorDialog(
                window, value,
                ''.join(traceback.format_exception(exctype, value,
                                                   tb))).exec_()
            exception_hook(exctype, value, tb)

        sys.excepthook = show_exception_hook
        exception_hook_set = True

        with eventloop:
            status = eventloop.run_forever()
            eventloop.run_until_complete(closeSession())
            sys.exit(status)

    except OtherInstanceError as e:
        sys.exit(f'error: {str(e)}')

    except (InvalidGamePath, InvalidConfigPath) as e:
        MainWindow.showInvalidConfigErrorDialog(None).exec_()
        sys.exit(f'error: {str(e)}')

    except PermissionError as e:
        MainWindow.showInvalidPermissionsErrorDialog(None).exec_()
        sys.exit(f'error: {str(e)}')

    except Exception as e:
        if not exception_hook_set:
            MainWindow.showCritcalErrorDialog(None, str(e)).exec_()
        raise e

    sys.exit()
Exemplo n.º 18
0
 def new_event_loop(self):
     return QEventLoop(QApplication(sys.argv))
Exemplo n.º 19
0
class WandGUI():
    def __init__(self):

        self.args = args = get_argparser().parse_args()
        init_logger_from_args(args)

        if args.log_to_file:
            log_file = pkg_resources.resource_filename("wand", "log.txt")
            fh = logging.FileHandler(log_file, mode="wt")
            fh.setLevel(logger.getEffectiveLevel())
            logger.addHandler(fh)
            logging.getLogger("qasync").addHandler(fh)
            sys.excepthook = lambda exc_type, exc_value, exc_traceback: \
                logger.exception("".join(
                    traceback.format_exception(exc_type,
                                               exc_value,
                                               exc_traceback)))

        self.config = load_config(args, "_gui")

        self.laser_db = {}
        self.freq_db = {}
        self.osa_db = {}
        self.subscribers = {}

        self.qapp = QtWidgets.QApplication(["WAnD"])
        self.loop = QEventLoop(self.qapp)
        asyncio.set_event_loop(self.loop)
        atexit.register(self.loop.close)

        # set program icon
        icon = QtGui.QIcon()
        icon.addFile(pkg_resources.resource_filename("wand", "wand.svg"))
        self.qapp.setWindowIcon(icon)

        # create main window
        self.win = MainWindow()
        self.area = dock.DockArea()
        self.win.setCentralWidget(self.area)
        self.win.setWindowTitle("Super-duper Python Wavemeter Viewer!")

        # populate GUI
        self.laser_displays = {}
        for row in self.config["layout"]:
            prev = None
            pos = 'bottom'
            for display_name in row:
                display = LaserDisplay(display_name, self)
                self.laser_displays.update({display.laser: display})
                self.area.addDock(display.dock, position=pos, relativeTo=prev)
                pos = 'right'
                prev = display.dock

    def notifier_cb(self, db, server, mod):
        """ Called whenever we get new data from a server "notifier" interface.

        NB sync_struct takes care of updating the relevant db for us, so all we
        do here is call the relevant GUI update function.
        """
        if mod["action"] == "init":
            self.subscribers[server][db]["connected"] = True

        # check we're fully connected to the server before processing updates
        if (
            not self.subscribers[server]["laser_db"]["connected"] or
            not self.subscribers[server]["freq_db"]["connected"] or
            not self.subscribers[server]["osa_db"]["connected"]
        ):
            return

        if mod["action"] == "init":
            # called when we first connect to a Notifier
            # we only activate the GUI channel for a laser once we have initial
            # data from all three Notifier interfaces (laser, freq, osa)
            displays = self.laser_displays

            for laser in mod["struct"].keys():
                if laser not in self.laser_displays.keys():
                    continue

                if displays[laser].server not in [server, ""]:
                    logger.error("laser '{}' found on multiple servers")
                    displays.server = ""
                else:
                    displays[laser].server = server

                displays[laser].wake_loop.set()

        elif mod["action"] == "setitem":
            if mod["path"] == []:
                laser = mod["key"]
            else:
                laser = mod["path"][0]

            if laser not in self.laser_displays.keys():
                return

            if db == "freq_db":
                self.laser_displays[laser].update_freq()
            elif db == "osa_db":
                self.laser_displays[laser].update_osa_trace()
            elif db == "laser_db":
                if mod["key"] == "f_ref":
                    self.laser_displays[laser].update_reference()
                elif (mod["key"] == "exposure" or
                      (len(mod["path"]) > 1 and mod["path"][1] == "exposure")):
                    self.laser_displays[laser].update_exposure()
                elif mod["key"] == "fast_mode":
                    self.laser_displays[laser].update_fast_mode()
                elif mod["key"] == "auto_exposure":
                    self.laser_displays[laser].update_auto_exposure()
                elif mod["key"] in ["locked", "lock_owner"]:
                    self.laser_displays[laser].update_laser_status()
            else:
                raise ValueError("Unexpected notifier interface")
        else:
            raise ValueError("Unexpected 'notifier' modification: {}"
                             .format(mod))

    def start(self):
        """ Connect to the WaND servers """

        def init_cb(db, mod):
            db.update(mod)
            return db

        async def subscriber_reconnect(self, server, db):
            logger.info("No connection to server '{}'".format(server))

            for _, display in self.laser_displays.items():
                if display.server == server:
                    display.server = ""
                    display.wake_loop.set()

            server_cfg = self.config["servers"][server]
            subscriber = self.subscribers[server][db]["subscriber"]

            if self.win.exit_request.is_set():
                return

            def make_fut(self, server, db):
                fut = asyncio.ensure_future(
                    subscriber_reconnect(self, server, db))
                self.subscribers[server][db]["connected"] = False
                self.subscribers[server][db]["future"] = fut

            subscriber.disconnect_cb = functools.partial(
                make_fut, self, server, db)

            while not self.win.exit_request.is_set():
                try:
                    await subscriber.connect(server_cfg["host"],
                                             server_cfg["notify"])

                    logger.info("Reconnected to server '{}'".format(server))
                    break
                except OSError:
                    logger.info("could not connect to '{}' retry in 10s..."
                                .format(server))
                    await asyncio.sleep(10)

        for server, server_cfg in self.config["servers"].items():
            self.subscribers[server] = {}

            # ask the servers to keep us updated with changes to laser settings
            # (exposures, references, etc)
            subscriber = Subscriber(
                "laser_db",
                functools.partial(init_cb, self.laser_db),
                functools.partial(self.notifier_cb, "laser_db", server))
            fut = asyncio.ensure_future(
                subscriber_reconnect(self, server, "laser_db"))
            self.subscribers[server]["laser_db"] = {
                "subscriber": subscriber,
                "connected": False,
                "future": fut
            }

            # ask the servers to keep us updated with the latest frequency data
            subscriber = Subscriber(
                "freq_db",
                functools.partial(init_cb, self.freq_db),
                functools.partial(self.notifier_cb, "freq_db", server))
            fut = asyncio.ensure_future(
                subscriber_reconnect(self, server, "freq_db"))
            self.subscribers[server]["freq_db"] = {
                "subscriber": subscriber,
                "connected": False,
                "future": fut
            }

            # ask the servers to keep us updated with the latest osa traces
            subscriber = Subscriber(
                "osa_db",
                functools.partial(init_cb, self.osa_db),
                functools.partial(self.notifier_cb, "osa_db", server))
            fut = asyncio.ensure_future(
                subscriber_reconnect(self, server, "osa_db"))
            self.subscribers[server]["osa_db"] = {
                "subscriber": subscriber,
                "connected": False,
                "future": fut
            }

        atexit_register_coroutine(self.shutdown)

        self.win.showMaximized()
        atexit.register(self.win.exit_request.set)
        self.loop.run_until_complete(self.win.exit_request.wait())

    async def shutdown(self):
        self.win.exit_request.set()

        for _, server in self.subscribers.items():
            for _, subs_dict in server.items():
                subs = subs_dict["subscriber"]
                fut = subs_dict["future"]
                try:
                    await subs.close()
                except Exception:
                    pass
                if fut is not None and not fut.done():
                    fut.cancel()
        for _, display in self.laser_displays.items():
            display.fut.cancel()
Exemplo n.º 20
0
def main():
    # initialize application
    args = get_argparser().parse_args()
    widget_log_handler = log.init_log(args, "dashboard")

    # load any plugin modules first (to register argument_ui classes, etc.)
    if args.plugin_modules:
        for mod in args.plugin_modules:
            importlib.import_module(mod)

    if args.db_file is None:
        args.db_file = os.path.join(
            get_user_config_dir(),
            "artiq_dashboard_{server}_{port}.pyon".format(
                server=args.server.replace(":", "."), port=args.port_notify))

    app = QtWidgets.QApplication(["ARTIQ Dashboard"])
    loop = QEventLoop(app)
    asyncio.set_event_loop(loop)
    atexit.register(loop.close)
    smgr = state.StateManager(args.db_file)

    # create connections to master
    rpc_clients = dict()
    for target in "schedule", "experiment_db", "dataset_db", "device_db":
        client = AsyncioClient()
        loop.run_until_complete(
            client.connect_rpc(args.server, args.port_control,
                               "master_" + target))
        atexit.register(client.close_rpc)
        rpc_clients[target] = client

    config = Client(args.server, args.port_control, "master_config")
    try:
        server_name = config.get_name()
    finally:
        config.close_rpc()

    disconnect_reported = False

    def report_disconnect():
        nonlocal disconnect_reported
        if not disconnect_reported:
            logging.error("connection to master lost, "
                          "restart dashboard to reconnect")
        disconnect_reported = True

    sub_clients = dict()
    for notifier_name, modelf in (("explist", explorer.Model),
                                  ("explist_status", explorer.StatusUpdater),
                                  ("datasets", datasets.Model),
                                  ("schedule", schedule.Model)):
        subscriber = ModelSubscriber(notifier_name, modelf, report_disconnect)
        loop.run_until_complete(
            subscriber.connect(args.server, args.port_notify))
        atexit_register_coroutine(subscriber.close)
        sub_clients[notifier_name] = subscriber

    broadcast_clients = dict()
    for target in "log", "ccb":
        client = Receiver(target, [], report_disconnect)
        loop.run_until_complete(
            client.connect(args.server, args.port_broadcast))
        atexit_register_coroutine(client.close)
        broadcast_clients[target] = client

    # initialize main window
    main_window = MainWindow(
        args.server if server_name is None else server_name)
    smgr.register(main_window)
    mdi_area = MdiArea()
    mdi_area.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
    mdi_area.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
    main_window.setCentralWidget(mdi_area)

    # create UI components
    expmgr = experiments.ExperimentManager(main_window,
                                           sub_clients["datasets"],
                                           sub_clients["explist"],
                                           sub_clients["schedule"],
                                           rpc_clients["schedule"],
                                           rpc_clients["experiment_db"])
    smgr.register(expmgr)
    d_shortcuts = shortcuts.ShortcutsDock(main_window, expmgr)
    smgr.register(d_shortcuts)
    d_explorer = explorer.ExplorerDock(expmgr, d_shortcuts,
                                       sub_clients["explist"],
                                       sub_clients["explist_status"],
                                       rpc_clients["schedule"],
                                       rpc_clients["experiment_db"],
                                       rpc_clients["device_db"])
    smgr.register(d_explorer)

    d_datasets = datasets.DatasetsDock(sub_clients["datasets"],
                                       rpc_clients["dataset_db"])
    smgr.register(d_datasets)

    d_applets = applets_ccb.AppletsCCBDock(main_window,
                                           sub_clients["datasets"],
                                           extra_substitutes={
                                               "server": args.server,
                                               "port_notify": args.port_notify,
                                               "port_control":
                                               args.port_control,
                                           })
    atexit_register_coroutine(d_applets.stop)
    smgr.register(d_applets)
    broadcast_clients["ccb"].notify_cbs.append(d_applets.ccb_notify)

    d_ttl_dds = moninj.MonInj(rpc_clients["schedule"])
    loop.run_until_complete(d_ttl_dds.start(args.server, args.port_notify))
    atexit_register_coroutine(d_ttl_dds.stop)

    d_schedule = schedule.ScheduleDock(rpc_clients["schedule"],
                                       sub_clients["schedule"])
    smgr.register(d_schedule)

    logmgr = log.LogDockManager(main_window)
    smgr.register(logmgr)
    broadcast_clients["log"].notify_cbs.append(logmgr.append_message)
    widget_log_handler.callback = logmgr.append_message

    # lay out docks
    right_docks = [
        d_explorer, d_shortcuts, d_ttl_dds.ttl_dock, d_ttl_dds.dds_dock,
        d_ttl_dds.dac_dock, d_datasets, d_applets
    ]
    main_window.addDockWidget(QtCore.Qt.RightDockWidgetArea, right_docks[0])
    for d1, d2 in zip(right_docks, right_docks[1:]):
        main_window.tabifyDockWidget(d1, d2)
    main_window.addDockWidget(QtCore.Qt.BottomDockWidgetArea, d_schedule)

    # load/initialize state
    if os.name == "nt":
        # HACK: show the main window before creating applets.
        # Otherwise, the windows of those applets that are in detached
        # QDockWidgets fail to be embedded.
        main_window.show()
    smgr.load()
    smgr.start()
    atexit_register_coroutine(smgr.stop)

    # work around for https://github.com/m-labs/artiq/issues/1307
    d_ttl_dds.ttl_dock.show()
    d_ttl_dds.dds_dock.show()

    # create first log dock if not already in state
    d_log0 = logmgr.first_log_dock()
    if d_log0 is not None:
        main_window.tabifyDockWidget(d_schedule, d_log0)

    if server_name is not None:
        server_description = server_name + " ({})".format(args.server)
    else:
        server_description = args.server
    logging.info("ARTIQ dashboard version: %s", artiq_version)
    logging.info("ARTIQ dashboard connected to moninj_proxy (%s)",
                 server_description)
    # run
    main_window.show()
    loop.run_until_complete(main_window.exit_request.wait())
Exemplo n.º 21
0
    @asyncClose
    async def closeEvent(self, event):
        await self.session.close()

    @asyncSlot()
    async def on_btnFetch_clicked(self):
        self.btnFetch.setEnabled(False)
        self.lblStatus.setText('Fetching...')

        try:
            async with self.session.get(self.editUrl.text()) as r:
                self.editResponse.setText(await r.text())
        except Exception as exc:
            self.lblStatus.setText('Error: {}'.format(exc))
        else:
            self.lblStatus.setText('Finished!')
        finally:
            self.btnFetch.setEnabled(True)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    loop = QEventLoop(app)
    asyncio.set_event_loop(loop)

    mainWindow = MainWindow()
    mainWindow.show()

    with loop:
        sys.exit(loop.run_forever())
Exemplo n.º 22
0
            if event.key(
            ) == QtCore.Qt.Key_Return and self.message_send.hasFocus():
                if not QtWidgets.QApplication.keyboardModifiers(
                ) == QtCore.Qt.ShiftModifier:
                    self.events.chat.addSelf()
        return super().eventFilter(obj, event)

    def bindButtons(self):
        for item in self.__dict__:
            obj = self.__dict__[item]
            if isinstance(obj, QtWidgets.QPushButton) or isinstance(
                    obj, QtWidgets.QToolButton):
                self.__dict__[item].clicked.connect(
                    partial(self.events.onClick, obj, item))

    def start(self):
        self.bindButtons()
        self.show()


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    loop = QEventLoop(app)
    asyncio.set_event_loop(loop)

    w = DiscordClient(loop)
    w.show()
    loop.run_forever()

    sys.exit(app.exec_())
Exemplo n.º 23
0
def main():
    # connect to labrad
    acxn = connection()
    acxn.connect()
    acxn.add_on_connect("ParameterVault", parameter_vault_connect)
    acxn.add_on_disconnect("ParameterVault", parameter_vault_disconnect)
    # connect to laser room labrad
    laser_room_acxn = connection()
    laser_room_acxn.connect(host=laser_room_ip_address,
                            password=lase_room_password,
                            tls_mode="off")
    # initialize application
    args = get_argparser().parse_args()
    widget_log_handler = log.init_log(args, "dashboard")

    if args.db_file is None:
        args.db_file = os.path.join(
            get_user_config_dir(),
            "artiq_dashboard_{server}_{port}.pyon".format(
                server=args.server.replace(":", "."), port=args.port_notify))

    app = QtWidgets.QApplication(["ARTIQ Dashboard"])
    loop = QEventLoop(app)
    asyncio.set_event_loop(loop)
    atexit.register(loop.close)
    smgr = state.StateManager(args.db_file)

    # create connections to master
    rpc_clients = dict()
    for target in "schedule", "experiment_db", "dataset_db":
        client = AsyncioClient()
        loop.run_until_complete(
            client.connect_rpc(args.server, args.port_control,
                               "master_" + target))
        atexit.register(client.close_rpc)
        rpc_clients[target] = client

    config = Client(args.server, args.port_control, "master_config")
    try:
        server_name = config.get_name()
    finally:
        config.close_rpc()

    disconnect_reported = False

    def report_disconnect():
        nonlocal disconnect_reported
        if not disconnect_reported:
            logging.error("connection to master lost, "
                          "restart dashboard to reconnect")
        disconnect_reported = True

    sub_clients = dict()
    for notifier_name, modelf in (("explist", explorer.Model),
                                  ("explist_status", explorer.StatusUpdater),
                                  ("datasets", datasets.Model),
                                  ("schedule", schedule.Model)):
        subscriber = ModelSubscriber(notifier_name, modelf, report_disconnect)
        loop.run_until_complete(
            subscriber.connect(args.server, args.port_notify))
        atexit_register_coroutine(subscriber.close)
        sub_clients[notifier_name] = subscriber

    broadcast_clients = dict()
    for target in "log", "ccb":
        client = Receiver(target, [], report_disconnect)
        loop.run_until_complete(
            client.connect(args.server, args.port_broadcast))
        atexit_register_coroutine(client.close)
        broadcast_clients[target] = client

    # initialize main window
    tabs = TabWidget()
    main_main_window = MainWindow(
        args.server if server_name is None else server_name)
    main_window = MainWindow(
        args.server if server_name is None else server_name)
    main_main_window.setCentralWidget(tabs)
    smgr.register(tabs)
    smgr.register(main_main_window)
    smgr.register(main_window, "sortoflikeamainwindowbutnotquite")
    mdi_area = MdiArea()
    mdi_area.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
    mdi_area.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
    main_window.setCentralWidget(mdi_area)

    # create UI components
    expmgr = experiments.ExperimentManager(main_window, sub_clients["explist"],
                                           sub_clients["schedule"],
                                           rpc_clients["schedule"],
                                           rpc_clients["experiment_db"])
    smgr.register(expmgr)
    # d_shortcuts = shortcuts.ShortcutsDock(main_window, expmgr)
    # smgr.register(d_shortcuts)
    d_pmt = pmt_control.PMTControlDock(acxn)
    smgr.register(d_pmt)
    d_parameter_editor = parameter_editor.ParameterEditorDock(acxn=acxn)
    smgr.register(d_parameter_editor)
    needs_parameter_vault.append(d_parameter_editor)
    d_explorer = explorer.ExplorerDock(expmgr, None, sub_clients["explist"],
                                       sub_clients["explist_status"],
                                       rpc_clients["schedule"],
                                       rpc_clients["experiment_db"])
    smgr.register(d_explorer)

    d_datasets = datasets.DatasetsDock(sub_clients["datasets"],
                                       rpc_clients["dataset_db"])
    smgr.register(d_datasets)

    d_applets = applets_ccb.AppletsCCBDock(main_window,
                                           sub_clients["datasets"])
    atexit_register_coroutine(d_applets.stop)
    smgr.register(d_applets)
    broadcast_clients["ccb"].notify_cbs.append(d_applets.ccb_notify)

    d_ttl_dds = moninj.MonInj()
    loop.run_until_complete(d_ttl_dds.start(args.server, args.port_notify))
    atexit_register_coroutine(d_ttl_dds.stop)

    d_schedule = schedule.ScheduleDock(rpc_clients["schedule"],
                                       sub_clients["schedule"])
    smgr.register(d_schedule)

    logmgr = log.LogDockManager(main_window)
    smgr.register(logmgr)
    broadcast_clients["log"].notify_cbs.append(logmgr.append_message)
    widget_log_handler.callback = logmgr.append_message

    # lay out docks
    right_docks = [
        d_explorer,
        d_pmt,
        d_parameter_editor,
        d_ttl_dds.ttl_dock,  #d_ttl_dds.dds_dock,
        d_ttl_dds.dac_dock,
        d_datasets,
        d_applets
    ]
    main_window.addDockWidget(QtCore.Qt.RightDockWidgetArea, right_docks[0])
    for d1, d2 in zip(right_docks, right_docks[1:]):
        main_window.tabifyDockWidget(d1, d2)
    main_window.addDockWidget(QtCore.Qt.BottomDockWidgetArea, d_schedule)

    tabs.addTab(main_window, "Control")
    laser_room_tab = LaserRoomTab()
    smgr.register(laser_room_tab)
    tabs.addTab(laser_room_tab, "Laser Room")
    # temp_controller_tab = TempControllerTab()
    # smgr.register(temp_controller_tab)
    # tabs.addTab(temp_controller_tab, "Temperature Controller")
    histograms_tab = ReadoutHistograms(acxn, smgr)
    smgr.register(histograms_tab)
    needs_parameter_vault.append(histograms_tab)
    tabs.addTab(histograms_tab, "Readout")
    drift_tracker_tab = DriftTracker(laser_room_acxn)
    smgr.register(drift_tracker_tab)
    tabs.addTab(drift_tracker_tab, "Drift Tracker")
    pulse_sequence_tab = PulseSequenceTab()
    smgr.register(pulse_sequence_tab)
    tabs.addTab(pulse_sequence_tab, "Pulse Sequence")

    smgr.load()
    smgr.start()
    atexit_register_coroutine(smgr.stop)

    # load/initialize state
    if os.name == "nt":
        # HACK: show the main window before creating applets.
        # Otherwise, the windows of those applets that are in detached
        # QDockWidgets fail to be embedded.
        main_window.show()

    # work around for https://github.com/m-labs/artiq/issues/1307
    d_ttl_dds.ttl_dock.show()
    d_ttl_dds.dds_dock.show()

    # create first log dock if not already in state
    d_log0 = logmgr.first_log_dock()
    if d_log0 is not None:
        main_window.tabifyDockWidget(d_schedule, d_log0)

    if server_name is not None:
        server_description = server_name + " ({})".format(args.server)
    else:
        server_description = args.server
    logging.info("ARTIQ dashboard %s connected to %s", artiq_version,
                 server_description)

    main_main_window.show()
    loop.run_until_complete(main_main_window.exit_request.wait())
Exemplo n.º 24
0
        self.setLayout(self.l)

        self.lm = LoginMenu()
        self.l.addWidget(self.lm)
        self.l.setMargin(0)

        self.setFixedSize(450, 150)
        self.setWindowTitle("BadDiscord -- Login")
        self.setWindowIcon(self.ico)
        self.setStyleSheet("background-color: #7289da;")

        self.show()

if __name__ == "__main__":
    app = QApplication()
    loop = QEventLoop(app)
    asyncio.set_event_loop(loop)

    c = Client()

    io = IOManager("configs.json")
    if io.Read() == {}:
        # Write defaults to configs
        io.Write({
            "LoginDetails": {
                "Token": None,
                "BotUser": False,
            }
        })

    # So we don't have to ensure loop is always running,
Exemplo n.º 25
0
class SimpleApplet:
    def __init__(self,
                 main_widget_class,
                 cmd_description=None,
                 default_update_delay=0.0):
        self.main_widget_class = main_widget_class

        self.argparser = argparse.ArgumentParser(description=cmd_description)

        self.argparser.add_argument(
            "--update-delay",
            type=float,
            default=default_update_delay,
            help="time to wait after a mod (buffering other mods) "
            "before updating (default: %(default).2f)")

        group = self.argparser.add_argument_group("standalone mode (default)")
        group.add_argument("--server",
                           default="::1",
                           help="hostname or IP of the master to connect to "
                           "for dataset notifications "
                           "(ignored in embedded mode)")
        group.add_argument("--port",
                           default=3250,
                           type=int,
                           help="TCP port to connect to")

        self._arggroup_datasets = self.argparser.add_argument_group("datasets")

        self.dataset_args = set()

    def add_dataset(self, name, help=None, required=True):
        kwargs = dict()
        if help is not None:
            kwargs["help"] = help
        if required:
            self._arggroup_datasets.add_argument(name, **kwargs)
        else:
            self._arggroup_datasets.add_argument("--" + name, **kwargs)
        self.dataset_args.add(name)

    def args_init(self):
        self.args = self.argparser.parse_args()
        self.embed = os.getenv("ARTIQ_APPLET_EMBED")
        self.datasets = {
            getattr(self.args, arg.replace("-", "_"))
            for arg in self.dataset_args
        }

    def qasync_init(self):
        app = QtWidgets.QApplication([])
        self.loop = QEventLoop(app)
        asyncio.set_event_loop(self.loop)

    def ipc_init(self):
        if self.embed is not None:
            self.ipc = AppletIPCClient(self.embed)
            self.loop.run_until_complete(self.ipc.connect())

    def ipc_close(self):
        if self.embed is not None:
            self.ipc.close()

    def create_main_widget(self):
        self.main_widget = self.main_widget_class(self.args)
        if self.embed is not None:
            self.ipc.set_close_cb(self.main_widget.close)
            if os.name == "nt":
                # HACK: if the window has a frame, there will be garbage
                # (usually white) displayed at its right and bottom borders
                #  after it is embedded.
                self.main_widget.setWindowFlags(QtCore.Qt.FramelessWindowHint)
                self.main_widget.show()
                win_id = int(self.main_widget.winId())
                self.loop.run_until_complete(self.ipc.embed(win_id))
            else:
                # HACK:
                # Qt window embedding is ridiculously buggy, and empirical
                # testing has shown that the following procedure must be
                # followed exactly on Linux:
                # 1. applet creates widget
                # 2. applet creates native window without showing it, and
                #    gets its ID
                # 3. applet sends the ID to host, host embeds the widget
                # 4. applet shows the widget
                # 5. parent resizes the widget
                win_id = int(self.main_widget.winId())
                self.loop.run_until_complete(self.ipc.embed(win_id))
                self.main_widget.show()
                self.ipc.fix_initial_size()
        else:
            self.main_widget.show()

    def sub_init(self, data):
        self.data = data
        return data

    def filter_mod(self, mod):
        if self.embed is not None:
            # the parent already filters for us
            return True

        if mod["action"] == "init":
            return True
        if mod["path"]:
            return mod["path"][0] in self.datasets
        elif mod["action"] in {"setitem", "delitem"}:
            return mod["key"] in self.datasets
        else:
            return False

    def emit_data_changed(self, data, mod_buffer):
        self.main_widget.data_changed(data, mod_buffer)

    def flush_mod_buffer(self):
        self.emit_data_changed(self.data, self.mod_buffer)
        del self.mod_buffer

    def sub_mod(self, mod):
        if not self.filter_mod(mod):
            return

        if self.args.update_delay:
            if hasattr(self, "mod_buffer"):
                self.mod_buffer.append(mod)
            else:
                self.mod_buffer = [mod]
                asyncio.get_event_loop().call_later(self.args.update_delay,
                                                    self.flush_mod_buffer)
        else:
            self.emit_data_changed(self.data, [mod])

    def subscribe(self):
        if self.embed is None:
            self.subscriber = Subscriber("datasets", self.sub_init,
                                         self.sub_mod)
            self.loop.run_until_complete(
                self.subscriber.connect(self.args.server, self.args.port))
        else:
            self.ipc.subscribe(self.datasets, self.sub_init, self.sub_mod)

    def unsubscribe(self):
        if self.embed is None:
            self.loop.run_until_complete(self.subscriber.close())

    def run(self):
        self.args_init()
        self.qasync_init()
        try:
            self.ipc_init()
            try:
                self.create_main_widget()
                self.subscribe()
                try:
                    self.loop.run_forever()
                finally:
                    self.unsubscribe()
            finally:
                self.ipc_close()
        finally:
            self.loop.close()
Exemplo n.º 26
0
 def qasync_init(self):
     app = QtWidgets.QApplication([])
     self.loop = QEventLoop(app)
     asyncio.set_event_loop(self.loop)
Exemplo n.º 27
0
def main():
    args = get_argparser().parse_args()

    app = QtWidgets.QApplication(sys.argv)
    loop = QEventLoop(app)
    asyncio.set_event_loop(loop)

    magic_spec = results.parse_magic(args.path)
    if magic_spec is not None:
        paths = results.find_results(day="auto", **magic_spec)
        if len(paths) != 1:
            QtWidgets.QMessageBox.critical(
                None, "Unable to resolve experiment path",
                f"Could not resolve '{args.path}: {paths}'")
            sys.exit(1)
        path = next(iter(paths.values())).path
    else:
        path = args.path

    try:
        file = h5py.File(path, "r")
    except Exception as e:
        QtWidgets.QMessageBox.critical(None, "Unable to load file", str(e))
        sys.exit(1)

    try:
        datasets = file["datasets"]
    except KeyError:
        QtWidgets.QMessageBox.critical(
            None, "Not an ARTIQ results file",
            "No ARTIQ dataset records found in file: '{}'".format(args.path))
        sys.exit(1)

    prefix = fetch_explicit_prefix(args)
    if prefix is not None:
        try:
            # 'axes' existed since the earliest schema revisions, so we can use it to
            # detect whether the file/prefix the user specified vaguely looks like it
            # has been generated by ndscan.
            datasets[prefix + "axes"][()]
        except KeyError:
            QtWidgets.QMessageBox.critical(
                None, "Not an ndscan file",
                "Datasets '{}*' in file '{}' do not look like ndscan results.".
                format(prefix, args.path))
            sys.exit(1)
        prefixes = [prefix]
    else:
        prefixes = find_ndscan_roots(datasets)
        if not prefixes:
            QtWidgets.QMessageBox.critical(
                None, "Not an ndscan file",
                "No ndscan result datasets found in file: '{}'".format(
                    args.path))
            sys.exit(1)

    try:
        schema = extract_param_schema(
            pyon.decode(file["expid"][()])["arguments"])
    except Exception as e:
        print("No ndscan parameter arguments found:", e)
        schema = None

    if schema is not None:
        print("Scan settings")
        print("=============")
        print()
        for s in dump_scan(schema):
            print(s)
        print()

        print()

        print("Overrides")
        print("=========")
        print()
        for s in dump_overrides(schema):
            print(s)
        print()

    try:
        context = Context()
        context.set_title(os.path.basename(args.path))

        # Take source_id from first prefix. This is pretty arbitrary, but for
        # experiment-generated files, they will all be the same anyway.
        if (prefixes[0] + "source_id") in datasets:
            source = datasets[prefixes[0] + "source_id"][()]
            if isinstance(source, bytes):
                # h5py 3+ – can use datasets[…].asstr() as soon as we don't support
                # version 2 any longer.
                source = source.decode("utf-8")
            context.set_source_id(source)
        else:
            # Old ndscan versions had a rid dataset instead of source_id.
            context.set_source_id("rid_{}".format(datasets[prefixes[0] +
                                                           "rid"][()]))

        roots = [HDF5Root(datasets, p, context) for p in prefixes]
    except Exception as e:
        QtWidgets.QMessageBox.critical(
            None, "Error parsing ndscan file",
            "Error parsing datasets in '{}': {}".format(args.path, e))
        sys.exit(2)

    if len(roots) == 1:
        widget = PlotContainerWidget(roots[0].get_model())
    else:
        label_map = shorten_to_unambiguous_suffixes(
            prefixes, lambda fqn, n: ".".join(fqn.split(".")[-(n + 1):]))
        widget = MultiRootWidget(
            OrderedDict(
                zip((strip_suffix(label_map[p], ".") for p in prefixes),
                    roots)), context)
    widget.setWindowTitle(f"{context.get_title()} – ndscan.show")
    widget.show()
    widget.resize(800, 600)
    sys.exit(app.exec_())
Exemplo n.º 28
0
from modules import gui, listener, singleton
globals.discord_rpc = discord_rpc

try:
    globals.singleton = singleton.Singleton("Soundy")
except RuntimeError:
    sys.exit()

if __name__ == '__main__':

    # Create App
    globals.app = QtWidgets.QApplication(sys.argv)
    globals.app.setQuitOnLastWindowClosed(False)

    # Configure asyncio loop to work with PyQt
    globals.loop = QEventLoop(globals.app)
    asyncio.set_event_loop(globals.loop)

    # Setup fonts
    QtGui.QFontDatabase.addApplicationFont(
        "resources/fonts/materialdesignicons-webfont.ttf")
    globals.font_mdi_38 = QtGui.QFont('Material Design Icons', 38)
    globals.font_mdi_26 = QtGui.QFont('Material Design Icons', 26)
    globals.font_mdi_18 = QtGui.QFont('Material Design Icons', 18)
    globals.font_mdi_13 = QtGui.QFont('Material Design Icons', 13)
    QtGui.QFontDatabase.addApplicationFont(
        "resources/fonts/Poppins-Medium.ttf")
    globals.font_track = QtGui.QFont('Poppins Medium', 13, 400)
    QtGui.QFontDatabase.addApplicationFont("resources/fonts/Poppins-Light.ttf")
    globals.font_artist = QtGui.QFont('Poppins Light', 10, 300)
Exemplo n.º 29
0
    def build(self):
        if not self.auth_info.is_logged_in() and (
                self.login_screen is None
                or not self.login_screen.isActiveWindow()):
            self.login_screen = LoginScreen(self.__identity_service)
            self.login_screen.showFullScreen()
            if self.main_window is not None:
                self.main_window.close()
        elif (self.main_window is None
              or not self.main_window.isActiveWindow()):
            self.main_window = MainWindow(self.__identity_service)
            self.main_window.showFullScreen()
            if self.login_screen is not None:
                self.login_screen.close()
        return

    def token_info_changed(self, token):
        self.build()
        return


if __name__ == "__main__":
    with ThreadManager.instance() as tm:
        app = QApplication([])
        loop = QEventLoop(app)
        asyncio.set_event_loop(loop)
        with loop:
            status = MainApplication().run(loop)
    ThreadManager.instance().wait()
    sys.exit(status)