Ejemplo n.º 1
0
def windowLauncher():
    app = QApplication(argv)
    loop = QEventLoop(app)

    w = Main()
    w.show()
    loop.run_forever()
Ejemplo n.º 2
0
    def __init__(self):
        super().__init__()
        topics = {
            'Projection.0.Out': '_auto_Projection.0.Out',
            'Projection.1.Out': '_auto_Projection.1.Out'
        }
        # Use the same topics for multiple traces in a plot
        # AsyncFetcher deduplicate and only makes as many sockets as needed
        terms = {
            'X': 'Projection.0.Out',
            'Y': 'Projection.1.Out',
            'X.1': 'Projection.1.Out',
            'Y.1': 'Projection.0.Out'
        }

        self.app = QtGui.QApplication([])
        self.loop = QEventLoop(self.app)
        asyncio.set_event_loop(self.loop)

        self.win = QtGui.QMainWindow()

        addr = Addr('graph', 'tcp://127.0.0.1:5557')
        self.widget = ScatterWidget(topics, terms, addr, parent=self.win)
        self.task = asyncio.ensure_future(self.widget.update())

        self.win.setCentralWidget(self.widget)
        self.win.show()

        try:
            self.loop.run_forever()
        finally:
            if not self.task.done():
                self.task.cancel()

            self.widget.close()
Ejemplo n.º 3
0
    def __init__(self):
        # QT
        app = QApplication(sys.argv)
        loop = QEventLoop(app)
        asyncio.set_event_loop(loop)
        self.running = True
        # com
        self.com_plug_event = asyncio.Event()
        self.com = com_connect.Comports(RS_Devices, self.com_plug_event)
        asyncio.create_task(self.comport_cb())

        # processes
        self.stop_flag = Value('i', 0)
        self.par_p, self.chi_p = Pipe()
        c = Process(target=cameras.Cameras, args=(self.chi_p, self.stop_flag, 0, 1))
        c.start()

        # loops
        self.duration = 4
        self.value = 0

        self.close_event = asyncio.Event()
        self.mw = MainWindow(self.close_event)
        self.mw.show()
        asyncio.create_task(self.handle_close_event())

        # --tasks
        asyncio.create_task(self.handle_frames())
        # asyncio.create_task(self.send_stop())

        # loops here...
        with loop:
            sys.exit(loop.run_forever())
Ejemplo n.º 4
0
    def __init__(self, host: str = "::1", channel: str = "ch1",
                 port: int = 3281, rpc_host: str = "", rpc_port: int = 3280, rpc_target="wavemeter_server",
                 title: str = None, window_width: int = 611, window_x: int = 0, window_y: int = 0,
                 enable_stripchart: bool = True, stripchart_height: int = 350, stripchart_num_points: int = 100,
                 plot_freq: bool = True, plot_offset: float = 0., plot_pen: Any = pyqtgraph.mkPen(color="k", width=3),
                 plot_symbol: Any = None, plot_bgr: str = "w", enable_lcd: bool = True, lcd_height: int = 160,
                 lcd_ndigits: int = 10, lcd_freq: bool = False, enable_interferograms: bool = False,
                 interferogram_update_interval: int = 1, show_interferogram_update_control: bool = False,
                 if0_pen: Any = pyqtgraph.mkPen(color="g", width=1),
                 if1_pen: Any = pyqtgraph.mkPen(color="b", width=1), interferogram_bgr: str = "w",
                 interferogram_height: int = 150, interferogram_exposure_control: bool = False):

        # user interface components
        self._enable_stripchart = enable_stripchart
        self._enable_lcd = enable_lcd
        self._enable_interferograms = enable_interferograms

        self.lcd_ndigits = lcd_ndigits

        self.stripchart_pen = plot_pen
        self.stripchart_symbol = plot_symbol
        self.stripchart_bgr = plot_bgr

        self._app = QApplication(sys.argv)
        self._loop = QEventLoop(self._app)
        asyncio.set_event_loop(self._loop)

        self.plot_freq = plot_freq
        self.plot_offset = plot_offset

        self.lcd_freq = lcd_freq

        try:  # accept integer (or string lacking the "ch" prefix) as channel argument
            self.channel = "ch{}".format(int(channel))
        except ValueError:
            self.channel = channel

        self.not_a_wavelength = (self.channel in ["T", "p"])  # disable frequency conversion options for T and p
        if self.not_a_wavelength:
            self.plot_freq = False
            self.lcd_freq = False
            self._enable_interferograms = False

        self.title = title if title is not None else "{} monitor ({}:{})".format(channel, host, port)

        if self._enable_interferograms and not self.not_a_wavelength:
            channel_id = int(self.channel[2:])
            self.interferograms = InterferogramWidget(rpc_host=rpc_host, rpc_port=rpc_port, rpc_target=rpc_target,
                                                      channel_id=channel_id, if0_pen=if0_pen, if1_pen=if1_pen,
                                                      bgr_color=interferogram_bgr,
                                                      update_interval=interferogram_update_interval,
                                                      show_interval_spinbox=show_interferogram_update_control,
                                                      show_exposure_ctrl=interferogram_exposure_control)

        self._build_ui(window_width, window_x, window_y, stripchart_height, stripchart_num_points, lcd_height,
                       interferogram_height)

        super().__init__(self.channel, host, port, self._loop)
Ejemplo n.º 5
0
async def main():
    QApplication.setAttribute(Qt.AA_EnableHighDpiScaling, True)
    app = QApplication(sys.argv)
    app_loop = QEventLoop(app)
    set_event_loop(app_loop)
    controller = AppController(
    )  # Need reference else garbage collector has too much fun
    with app_loop:
        sys.exit(app_loop.run_forever())
Ejemplo n.º 6
0
 def __init__(self):
     super().__init__()
     self.loop = QEventLoop(self._qapp)
     asyncio.set_event_loop(self.loop)
     for name in ('asyncqt._unix._Selector',
                  'asyncqt._QEventLoop',
                  'asyncqt._SimpleTimer'):
         log = logging.getLogger(name)
         log.setLevel(logging.WARN)
Ejemplo n.º 7
0
def windowLauncher():
    app = QApplication(sys.argv)
    app.setWindowIcon(QIcon('Files/incubus.png'))
    app.setStyleSheet(css.window())
    loop = QEventLoop(app)
    asyncio.set_event_loop(loop)

    w = MainWindow0()
    w.show()
    loop.run_forever()
Ejemplo n.º 8
0
def main():
    global loop

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

    mainWindow = MainWindow()
    mainWindow.show()

    with loop:
        sys.exit(loop.run_forever())
Ejemplo n.º 9
0
    def __init__(self,
                 host: str = "::1",
                 rpc_target: str = "wavemeter_server",
                 rpc_port: int = 3280,
                 notifier_port: int = 3281,
                 title: str = None,
                 window_x: int = 0,
                 window_y: int = 0,
                 cal_channel: int = 1,
                 cal_wl: float = 633.,
                 cal_threshold: float = 0.00005,
                 cal_interval: int = 600,
                 cal_retry_interval: int = 10,
                 start_autocal: bool = False):

        self._app = QApplication(sys.argv)
        self._loop = QEventLoop(self._app)
        asyncio.set_event_loop(self._loop)

        self.wm_status_dict = {
            "autocal_countdown": 0,
            "calibration_timestamp": -1
        }

        self._subscriber = Subscriber("status", self._subscriber_init_cb,
                                      self._subscriber_mod_cb)
        logger.info(
            "Connecting to publisher at {}:{}, notifier name: status".format(
                host, notifier_port))
        self._loop.run_until_complete(
            self._subscriber.connect(host, notifier_port))

        logger.info(
            "Connecting to RPC server at {}:{}, target name: {}".format(
                host, rpc_port, rpc_target))
        self._rpc_client = BestEffortClient(host, rpc_port, rpc_target)
        self._loop.create_task(self.keepalive_loop())

        self.title = title if title is not None else "Wavemeter remote control ({} at {})".format(
            rpc_target, host)

        self._ui_input_elements = dict(
        )  # stores all input elements, used on function calls to retrieve their values
        self._build_ui(window_x, window_y, cal_channel, cal_wl, cal_threshold,
                       cal_interval, cal_retry_interval)

        if start_autocal and self._rpc_client is not None:
            self._rpc_client.start_autocalibration(cal_channel, cal_wl,
                                                   cal_threshold, cal_interval,
                                                   cal_retry_interval)
Ejemplo n.º 10
0
    def __init__(self):
        super().__init__()

        #: Set event loop policy for windows
        if sys.platform == 'win32':
            asyncio.set_event_loop_policy(
                asyncio.WindowsSelectorEventLoopPolicy())

        self.loop = QEventLoop(self._qapp)
        asyncio.set_event_loop(self.loop)
        for name in ('asyncqt._unix._Selector', 'asyncqt._QEventLoop',
                     'asyncqt._SimpleTimer'):
            log = logging.getLogger(name)
            log.setLevel(logging.WARN)
Ejemplo n.º 11
0
class App(Observation):
    def __init__(self, subject):
        Observation.__init__(self, subject)
        self.subject = subject
        self.loop = None
        self.backend = None

        self.app = QApplication(sys.argv)
        self.app.setApplicationName(ApplicationInfo.name)
        self.app.setApplicationDisplayName(ApplicationInfo.name)

        Fonts.initDb()

        self.main = Main(subject)

        self._init_responders()

    def document_new_responder(self, e):
        self.subject = Subject()
        self._init_responders()

        self.main.close()
        self.main.deleteLater()
        self.main = Main(self.subject)
        self.backend.delete()
        self.backend = BackendRouter(self.loop, self.subject)

        self.main.show()

    def _init_responders(self):
        self.add_responder(events.view.main.FileNew,
                           self.document_new_responder)

    def run(self):
        self.loop = QEventLoop(self.app)
        self.backend = BackendRouter(self.loop, self.subject)
        asyncio.set_event_loop(self.loop)
        self.main.show()

        with self.loop:
            code = self.loop.run_forever()
            pending = asyncio.Task.all_tasks()
            self.notify(events.app.Quit())
            try:
                self.loop.run_until_complete(
                    asyncio.wait_for(asyncio.gather(*pending), 10))
            except asyncio.futures.TimeoutError as e:
                print(e)
            sys.exit(code)
Ejemplo n.º 12
0
def main():
    app = QtWidgets.QApplication(sys.argv)
    icon_file = pkg_resources.resource_filename("pypod_launcher", "icon.ico")
    app.setWindowIcon(QtGui.QIcon(icon_file))
    loop = QEventLoop(app)
    asyncio.set_event_loop(loop)
    ui_file = pkg_resources.resource_filename("pypod_launcher", "main.ui")
    ui = QtUiTools.QUiLoader().load(ui_file)
    ui.setWindowTitle("pypod-launcher [v{}]".format(version))
    config_logging(ui)
    launcher = Launcher(ui)
    launcher.center()
    ui.show()
    with loop:
        sys.exit(loop.run_forever())
Ejemplo n.º 13
0
    def run(self):
        self.loop = QEventLoop(self.app)
        self.backend = BackendRouter(self.loop, self.subject)
        asyncio.set_event_loop(self.loop)
        self.main.show()

        with self.loop:
            code = self.loop.run_forever()
            pending = asyncio.Task.all_tasks()
            self.notify(events.app.Quit())
            try:
                self.loop.run_until_complete(
                    asyncio.wait_for(asyncio.gather(*pending), 10))
            except asyncio.futures.TimeoutError as e:
                print(e)
            sys.exit(code)
Ejemplo n.º 14
0
    def __init__(self, argv):
        super().__init__(argv)
        self.setApplicationName("imagect")

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

        self.thread_pool = concurrent.futures.ThreadPoolExecutor()
Ejemplo n.º 15
0
    def __init__(self, eui_class):
        self._eui_class = eui_class
        self._app = QApplication(sys.argv)

        parser = QCommandLineParser()
        parser.addHelpOption()
        parser.addVersionOption()
        noSplash = QCommandLineOption(["n", "no-splash"],
                                      "don't show splash screen")
        parser.addOption(noSplash)
        parser.process(self._app)

        self._loop = QEventLoop(self._app)
        asyncio.set_event_loop(self._loop)

        self._comms = []
        self._splash = not (parser.isSet(noSplash))
        self._eui = None
Ejemplo n.º 16
0
    def run(self):
        app = self.app

        app.setQuitOnLastWindowClosed(False)

        # Create the icon
        icon = QIcon(self.img_icon)

        # Create the tray
        tray = QSystemTrayIcon()
        tray.setIcon(icon)
        tray.setVisible(True)

        # Create the menu
        menu = QMenu()
        self.open_site_link = open_site = QAction("Open")
        open_site.triggered.connect(self.open_site)

        menu.addAction(open_site)

        # Add a Quit option to the menu.
        quit = QAction("Quit")
        quit.triggered.connect(app.quit)
        menu.addAction(quit)

        # Add the menu to the tray
        tray.setContextMenu(menu)

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

        web_app = web.Application()

        cors = aiohttp_cors.setup(web_app, defaults={
            "*": aiohttp_cors.ResourceOptions(
                    allow_credentials=True,
                    expose_headers="*",
                    allow_headers="*",
                )
        })
        cors.add(web_app.router.add_get('/', self.web_get_root))
        cors.add(web_app.router.add_get('/inc-link/', self.web_get_inc_link))

        return loop.run_until_complete(web._run_app(web_app, port=8766, host='127.0.0.1'))
Ejemplo n.º 17
0
def run_app():
    app = QApplication()
    app.setWindowIcon(QIcon('icon.ico'))

    event_loop: AbstractEventLoop = QEventLoop()
    asyncio.set_event_loop(event_loop)

    form = MainWindow()
    form.show()

    event_loop.run_forever()
Ejemplo n.º 18
0
        def __init__(self, host: str = "::1", port: int = 3280, target: str = "wavemeter_server"):

            self._app = QApplication(sys.argv)
            self._loop = QEventLoop(self._app)
            asyncio.set_event_loop(self._loop)

            self.logging_client = WavemeterLoggingClient(host=host, port=port, target=target, event_loop=self._loop)

            self.title = "Wavelength logging client, {} at {}:{}". format(target, host, port)

            self._ui_input_elements = dict()

            self.latest_line_label = QLabel("")

            def label_cb(line):
                timestring = time.asctime(time.localtime(time.time()))
                filename = self.logging_client.filename

                self.latest_line_label.setText("At {}, added line to file {}:\n{}".format(timestring, filename, line))

            self.logging_client._output_cb = label_cb

            self._build_ui()
Ejemplo n.º 19
0
def launch_gui(filename=None):
    # check the requirements and import
    failed_requirements = []
    try:
        from PySide2.QtWidgets import QApplication
        from PySide2.QtGui import QIcon
    except ModuleNotFoundError:
        failed_requirements.append('PySide2')

    try:
        from asyncqt import QEventLoop
    except ModuleNotFoundError:
        failed_requirements.append('asyncqt')

    if failed_requirements:
        for package in failed_requirements:
            print(_module_err_msg.format(package=package))
        sys.exit()

    # if on Windows, change the taskbar icon
    try:
        from PySide2.QtWinExtras import QtWin
        myappid = f'andersonics.llc.patchbay.{__version__}'
        QtWin.setCurrentProcessExplicitAppUserModelID(myappid)
    except ImportError:
        pass

    from patchbay.qt.patchbay_ui import Patchbay

    #  launch the GUI
    app = QApplication(sys.argv)
    app.setOrganizationName('Andersonics')
    app.setOrganizationDomain('andersonics.llc')
    app.setApplicationName('patchbay')
    app.setWindowIcon(QIcon(str(root_path / 'resources' / 'pb.svg')))

    try:
        # use proper scaling for matplotlib figures in the UI
        plt.matplotlib.rcParams['figure.dpi'] = app.desktop().physicalDpiX()
    except NameError:
        pass

    asyncio.set_event_loop(QEventLoop(app))

    patchbay_ui = Patchbay(filename=filename)
    return app.exec_()
Ejemplo n.º 20
0
def run_app():
    init_environment()

    app = QApplication(sys.argv)

    event_loop: AbstractEventLoop = QEventLoop(app)
    asyncio.set_event_loop(event_loop)

    window = MainWindow(create_assistant())

    try:
        with event_loop:
            event_loop.create_task(window.start())
            event_loop.run_forever()
    except KeyboardInterrupt:
        print("App terminated")
    finally:
        if not event_loop.is_closed():
            event_loop.close()
Ejemplo n.º 21
0
def maintcp():
  app = QApplication(sys.argv)
  loop = QEventLoop(app)
  asyncio.set_event_loop(loop)
  form = MyApp()
  form.show()

  with loop:
    coro = asyncio.start_server(form.handle_echo, '', 5000, loop=loop)
    loop.run_until_complete(coro)
    try:
      loop.run_forever()
    except Exception as ex:
      print("maintcp error: ",str(ex))
Ejemplo n.º 22
0
    def configure_event_loop(self):  # pragma: no cover
        logger.info("Configuring async runtime")

        if USE_QUAMASH and not self.cli_config.headless:
            logger.info("Using Quamash for async support.")
            loop = QEventLoop(self.qt_app)
            asyncio.set_event_loop(loop)
        else:
            logger.info("Using asyncio for async support.")
            loop = asyncio.get_event_loop()

        signal_set = {
            "win32": lambda: (),  # windows has no signals, but will raise exceptions
        }.get(sys.platform, lambda: (signal.SIGHUP, signal.SIGTERM, signal.SIGINT))()
        for s in signal_set:
            logger.info("Installing shutdown signal handler for signal {s}")
            loop.add_signal_handler(s, lambda s=s: loop.create_task(self.shutdown(loop, s)))

        logger.info("Setting custom exception handler on async loop")
        loop.set_exception_handler(self.handle_exception)
        return loop
Ejemplo n.º 23
0
Archivo: client.py Proyecto: prfnv/chat
        message_text = self.message_input.text()
        self.message_input.clear()
        self.protocol.send_data(message_text)

    def append_text(self, content: str):
        self.message_box.appendPlainText(content)

    def buid_protocol(self):
        self.protocol = ClientProtocol(self)
        return self.protocol

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

        event_loop = asyncio.get_running_loop()

        coroutine = event_loop.create_connection(self.buid_protocol,
                                                 "127.0.0.1", 8000)

        await asyncio.wait_for(coroutine, 1000)


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

window = MainWindow()
window.show()

loop.create_task(window.start())
loop.run_forever()
Ejemplo n.º 24
0
import plugins.Mqtt
import plugins.Performance

logging.config.dictConfig(yaml.load(open('logging.yaml', 'r')))
logger = logging.getLogger(__name__)

logger.debug("Geo sources: %s" % QGeoPositionInfoSource.availableSources())

QGuiApplication.setAttribute(Qt.AA_DisableHighDpiScaling)
QGuiApplication.setAttribute(Qt.AA_Use96Dpi)
QGuiApplication.setAttribute(Qt.AA_ShareOpenGLContexts)

# Create the application instance.
app = QGuiApplication(sys.argv)

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

touchscreens = list(
    filter(lambda d: d.type() == QTouchDevice.TouchScreen,
           QTouchDevice.devices()))
if touchscreens:
    logger.info("touchscreens detected, disabling mouse %s" % touchscreens)
    app.setOverrideCursor(QCursor(Qt.BlankCursor))

# Create a QML engine.
engine = QQmlApplicationEngine()
engine.load('./ui/main.qml')

win = engine.rootObjects()[0]
win.show()
Ejemplo n.º 25
0
            await asyncio.wait_for(coroutine, 5)
            coroutine.close()
            return ip, port
        except (ConnectionRefusedError, ConnectionError, OSError):
            return

    async def start(self, ip, port):

        event_loop = asyncio.get_running_loop()

        coroutine = event_loop.create_connection(
            self.build_protocol,
            ip,
            port
        )
        try:
            await asyncio.wait_for(coroutine, 5)
            self.running = True
        except (ConnectionRefusedError, ConnectionError, OSError):
            self.create_error('Connection Error')


app = QApplication()
app.setWindowIcon(QtGui.QIcon("logo.png"))
loop = QEventLoop(app)
asyncio.set_event_loop(loop)

window = MainWindow()

loop.run_forever()
Ejemplo n.º 26
0
import sys
import asyncio
import time

# from PyQt5.QtWidgets import (
from PySide2.QtWidgets import (QApplication, QProgressBar)
from asyncqt import QEventLoop, QThreadExecutor

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

progress = QProgressBar()
progress.setRange(0, 99)
progress.show()


async def master():
    await first_50()
    with QThreadExecutor(1) as exec:
        await loop.run_in_executor(exec, last_50)


async def first_50():
    for i in range(50):
        progress.setValue(i)
        await asyncio.sleep(.1)


def last_50():
    for i in range(50, 100):
Ejemplo n.º 27
0
class WavemeterChannelMonitor(WavemeterClient):
    """
    Connects to a :class:`WavemeterServer` to monitor a channel wavelength, temperature or pressure. There are three
    available GUI elements: a stripchart plot, a scalable number display, and an interferogram plot.

    :param host: the address at which the :class:`WavemeterServer` publisher is running
    :param channel: wavemeter channel (can be either <n>, '<n>', 'ch<n>', 'T' or 'p')
    :param port: port of the publisher
    :param rpc_host: host of the wavemeter server (only needed for interferograms, default = same as publisher)
    :param rpc_port: port of the wavemeter server rpc target (only needed for interferograms)
    :param rpc_target: target name for rpcs (only needed for interferograms)
    :param title: the window title (generated from the server details by default)
    :param window_width: initial width of the window in pixels
    :param window_x: initial x position of the window in pixels
    :param window_y: initial y position of the window in pixels
    :param enable_stripchart: show the stripchart
    :param stripchart_height: initial stripchart height in pixels
    :param stripchart_num_points: number of data points displayed in the stripchart
    :param plot_freq: True for frequency plot, False for wavelength plot
    :param plot_offset: y offset of the plot (unit is MHz for frequencies and nm for wavelengths)
    :param plot_pen: pen specification for the plot trace (see pyqtgraph documentation)
    :param plot_symbol: symbol specification for the plot points
    :param plot_bgr: bgr color of the plot
    :param enable_lcd: show the current value (wavelength or frequency) as a scalable number
    :param lcd_height: lcd height in pixels
    :param lcd_ndigits: number of digits in the lcd
    :param lcd_freq: start with the number display showing the frequency (default is wavelength)
    :param enable_interferograms: display the interferograms
    :param interferogram_update_interval: number of values after which to update the interferograms
    :param show_interferogram_update_control: show the spinbox to adjust interferogram update rate
    :param if0_pen: pen specification for the 1st interferogram
    :param if1_pen: pen specification for the 2nd interferogram
    :param interferogram_bgr: bgr color of the interferogram plot
    :param interferogram_height: initial height of the interferogram plot in pixels
    :param interferogram_exposure_control: enable control of wavemeter exposure times
    """

    def __init__(self, host: str = "::1", channel: str = "ch1",
                 port: int = 3281, rpc_host: str = "", rpc_port: int = 3280, rpc_target="wavemeter_server",
                 title: str = None, window_width: int = 611, window_x: int = 0, window_y: int = 0,
                 enable_stripchart: bool = True, stripchart_height: int = 350, stripchart_num_points: int = 100,
                 plot_freq: bool = True, plot_offset: float = 0., plot_pen: Any = pyqtgraph.mkPen(color="k", width=3),
                 plot_symbol: Any = None, plot_bgr: str = "w", enable_lcd: bool = True, lcd_height: int = 160,
                 lcd_ndigits: int = 10, lcd_freq: bool = False, enable_interferograms: bool = False,
                 interferogram_update_interval: int = 1, show_interferogram_update_control: bool = False,
                 if0_pen: Any = pyqtgraph.mkPen(color="g", width=1),
                 if1_pen: Any = pyqtgraph.mkPen(color="b", width=1), interferogram_bgr: str = "w",
                 interferogram_height: int = 150, interferogram_exposure_control: bool = False):

        # user interface components
        self._enable_stripchart = enable_stripchart
        self._enable_lcd = enable_lcd
        self._enable_interferograms = enable_interferograms

        self.lcd_ndigits = lcd_ndigits

        self.stripchart_pen = plot_pen
        self.stripchart_symbol = plot_symbol
        self.stripchart_bgr = plot_bgr

        self._app = QApplication(sys.argv)
        self._loop = QEventLoop(self._app)
        asyncio.set_event_loop(self._loop)

        self.plot_freq = plot_freq
        self.plot_offset = plot_offset

        self.lcd_freq = lcd_freq

        try:  # accept integer (or string lacking the "ch" prefix) as channel argument
            self.channel = "ch{}".format(int(channel))
        except ValueError:
            self.channel = channel

        self.not_a_wavelength = (self.channel in ["T", "p"])  # disable frequency conversion options for T and p
        if self.not_a_wavelength:
            self.plot_freq = False
            self.lcd_freq = False
            self._enable_interferograms = False

        self.title = title if title is not None else "{} monitor ({}:{})".format(channel, host, port)

        if self._enable_interferograms and not self.not_a_wavelength:
            channel_id = int(self.channel[2:])
            self.interferograms = InterferogramWidget(rpc_host=rpc_host, rpc_port=rpc_port, rpc_target=rpc_target,
                                                      channel_id=channel_id, if0_pen=if0_pen, if1_pen=if1_pen,
                                                      bgr_color=interferogram_bgr,
                                                      update_interval=interferogram_update_interval,
                                                      show_interval_spinbox=show_interferogram_update_control,
                                                      show_exposure_ctrl=interferogram_exposure_control)

        self._build_ui(window_width, window_x, window_y, stripchart_height, stripchart_num_points, lcd_height,
                       interferogram_height)

        super().__init__(self.channel, host, port, self._loop)

    def _build_ui(self, window_width, window_x, window_y, stripchart_height, stripchart_num_points, lcd_height,
                  interferogram_height):
        self.window = QWidget()
        self.window.setWindowTitle(self.title)
        window_height = stripchart_height * self._enable_stripchart \
            + lcd_height * self._enable_lcd \
            + interferogram_height * self._enable_interferograms
        self.window.resize(window_width, window_height)
        self.window.move(window_x, window_y)

        # The layout only contains one element (the splitter), but it is needed to rescale widgets as window is rescaled
        self.v_layout = QVBoxLayout()
        self.v_splitter = QSplitter(Qt.Vertical)
        self.v_layout.addWidget(self.v_splitter)

        self.window.setLayout(self.v_layout)
        self.v_layout.addWidget(self.v_splitter)

        splitter_sizes = []
        if self._enable_stripchart:
            self._build_stripchart(stripchart_num_points)
            splitter_sizes.append(stripchart_height)
        if self._enable_lcd:
            self._build_lcd()
            splitter_sizes.append(lcd_height)
        if self._enable_interferograms:
            self.v_splitter.addWidget(self.interferograms)
            splitter_sizes.append(interferogram_height)

        self.v_splitter.setSizes(splitter_sizes)

    def _build_stripchart(self, num_points):
        plot_title = ""
        if self.plot_freq:
            plot_y_label = "frequency (MHz)"
            if self.plot_offset != 0:
                plot_title = "offset: {:11} THz".format(self.plot_offset * 1e-6)
        else:
            if self.channel == "T":
                plot_y_label = "temperature (degrees C)"
                if self.plot_offset != 0:
                    plot_title = "offset: {:5} degrees C".format(self.plot_offset)
            elif self.channel == "p":
                plot_y_label = "pressure (mbar)"
                if self.plot_offset != 0:
                    plot_title = "offset: {:6} mbar".format(self.plot_offset)
            else:
                plot_y_label = "vac. wavelength (nm)"
                if self.plot_offset != 0:
                    plot_title = "offset: {:10} nm".format(self.plot_offset)

        self.stripchart = Stripchart(num_points=num_points, xvalues=True, offset=self.plot_offset,
                                     plot_title=plot_title, plot_pen=self.stripchart_pen,
                                     plot_symbol=self.stripchart_symbol, plot_bgr=self.stripchart_bgr,
                                     x_label="wavemeter time stamp (s)", y_label=plot_y_label, y_grid=True)
        clear_button = QPushButton("&Clear")
        clear_button.clicked.connect(self.stripchart.clear_data)

        layout = QVBoxLayout()
        layout.addWidget(self.stripchart)
        layout.addWidget(clear_button)
        widget = QWidget()
        widget.setLayout(layout)
        self.v_splitter.addWidget(widget)

    def _add_stripchart_point(self):
        if self.value < 0:  # ignore error codes
            return
        if self.plot_freq:  # plot frequency in MHz
            self.stripchart.add_point(self.timestamp * 1e-3, 299792456e3 / self.value)
        else:  # plot wavelength in nm
            self.stripchart.add_point(self.timestamp * 1e-3, self.value)

    def _build_lcd(self):
        layout = QVBoxLayout()
        self.lcd = QLCDNumber()
        self.lcd.setSmallDecimalPoint(True)
        self.lcd.setDigitCount(self.lcd_ndigits)
        freq_checkbox = QCheckBox("Display frequency")
        freq_checkbox.setChecked(self.lcd_freq)

        def switch_wl_freq():
            self.lcd_freq = freq_checkbox.isChecked()
            self._update_lcd()

        freq_checkbox.clicked.connect(switch_wl_freq)
        layout.addWidget(self.lcd)
        if not self.not_a_wavelength:
            layout.addWidget(freq_checkbox)
        widget = QWidget()
        widget.setLayout(layout)
        self.v_splitter.addWidget(widget)

    def _update_lcd(self):
        if self.value > 0:
            value = 299792456e-3 / self.value if self.lcd_freq else self.value
            # next line is to keep number of decimals constant (i.e. display trailing zeros)
            self.lcd.display("{{:.0{}f}}".format(self.lcd_ndigits-len(str(int(value)))).format(value))
        elif self.value == -2:  # bad signal
            self.lcd.display("b")
        elif self.value == -3:  # underexposed
            self.lcd.display("u")
        elif self.value == -4:  # overexposed
            self.lcd.display("o")
        else:
            self.lcd.display(self.value)

    def _init_callback(self):
        if self._enable_lcd:
            self._update_lcd()
        if self._enable_interferograms:
            self.interferograms.update_data()

    def _new_value_callback(self):
        if self._enable_stripchart:
            self._add_stripchart_point()
        if self._enable_lcd:
            self._update_lcd()
        if self._enable_interferograms:
            self.interferograms.update_data()

    def run(self):
        self.window.show()
        self._loop.run_forever()
        if self._subscriber is not None:
            self._loop.run_until_complete(self._subscriber.close())
Ejemplo n.º 28
0
class Application(QtApplication):
    """ Add asyncio support . Seems like a complete hack compared to twisted
    but whatever.

    """

    loop = Instance(QEventLoop)
    queue = Instance(Queue, ())
    running = Bool()

    def __init__(self):
        super().__init__()
        self.loop = QEventLoop(self._qapp)
        asyncio.set_event_loop(self.loop)
        for name in ('asyncqt._unix._Selector',
                     'asyncqt._QEventLoop',
                     'asyncqt._SimpleTimer'):
            log = logging.getLogger(name)
            log.setLevel(logging.WARN)

    def start(self):
        """ Run using the event loop

        """
        log.info("Application starting")
        self.running = True
        with self.loop:
            try:
                self.loop.run_until_complete(self.main())
            except RuntimeError as e:
                if 'loop stopped' not in str(e):
                    raise

    async def main(self):
        """ Run any async deferred calls in the main ui loop.

        """
        while self.running:
            try:
                task = self.queue.get(block=False)
                await task
            except Empty:
                self.process_events()
                await asyncio.sleep(0.1)
            except Exception as e:
                if 'cannot enter context' in str(e):
                    # HACK: Something is jacked up
                    await asyncio.sleep(0.1)
                    continue
                log.exception(e)

    def process_events(self):
        """ Let the the app process events during long-running cpu intensive
        tasks.

        """
        self._qapp.processEvents()

    def deferred_call(self, callback, *args, **kwargs):
        """ Invoke a callable on the next cycle of the main event loop
        thread.

        Parameters
        ----------
        callback : callable
            The callable object to execute at some point in the future.

        args, kwargs
            Any additional positional and keyword arguments to pass to
            the callback.

        """
        if asyncio.iscoroutinefunction(callback) or kwargs.pop('async_', None):
            task = asyncio.create_task(callback(*args, **kwargs))
            return self.add_task(task)
        return super().deferred_call(callback, *args, **kwargs)

    def timed_call(self, ms, callback, *args, **kwargs):
        """ Invoke a callable on the main event loop thread at a
        specified time in the future.

        Parameters
        ----------
        ms : int
            The time to delay, in milliseconds, before executing the
            callable.

        callback : callable
            The callable object to execute at some point in the future.

        args, kwargs
            Any additional positional and keyword arguments to pass to
            the callback.

        """
        if asyncio.iscoroutinefunction(callback) or kwargs.pop('async_', None):
            task = asyncio.create_task(callback(*args, **kwargs))
            return super().timed_call(ms, self.add_task, task)
        return super().timed_call(ms, callback, *args, **kwargs)

    def add_task(self, task):
        """ Put a task into the queue

        """
        self.queue.put(task)
Ejemplo n.º 29
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.system.permissions import \
        getWritePermissions, setWritePermissions

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

    from asyncqt import QEventLoop  # noqa

    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)
    QApplication.setAttribute(Qt.AA_DisableWindowContextHelpButton)
    QApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
    QApplication.setAttribute(Qt.AA_UseHighDpiPixmaps)
    QApplication.setHighDpiScaleFactorRoundingPolicy(
        Qt.HighDpiScaleFactorRoundingPolicy.RoundPreferFloor)

    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)
    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)

    # 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()

    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

        with eventloop:
            sys.exit(eventloop.run_forever())

    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:
        MainWindow.showCritcalErrorDialog(None, str(e)).exec_()
        raise e

    sys.exit()
Ejemplo n.º 30
0
        app.quit()


if __name__ == "__main__":
    # asyncio debugging
    # https://docs.python.org/3.6/library/asyncio-dev.html
    # https://docs.python.org/3/using/cmdline.html#environment-variables
    os.environ['PYTHONASYNCIODEBUG'] = "1"
    os.environ['DEBUG'] = "1"
    warnings.warn("always", ResourceWarning)

    basename = os.path.splitext(os.path.basename(__file__))[0]

    # global app
    app = QApplication(sys.argv)
    eventloop = QEventLoop(app)
    asyncio.set_event_loop(eventloop)
    eventloop.set_debug(True)
    # executor = concurrent.futures.ThreadPoolExecutor(5)
    # eventloop.set_default_executor(executor)

    setup_logging()

    window = MainWindow()
    window.show()

    with eventloop:
        eventloop.create_task(new_browsertab(9232, eventloop))
        sys.exit(eventloop.run_forever())
        pass
    pass