def main(self):
        evl = urwid.AsyncioEventLoop(loop=asyncio.get_event_loop())
        self.loop = urwid.MainLoop(
            self.app_widget,
            self.app_widget.palette,
            event_loop=evl
        )
        self.loop.screen.set_terminal_properties(colors=256)

        async def q():
            try:
                task = self.dev_rant_service.get_rants()
                w = weakref.ref(task)
                await task
            except Exception as e:
                task_future = w()
                if task_future:
                    task_future.cancel()
                    await task_future
                raise e

        asyncio.ensure_future(
            q()
        )

        self.loop.run()
Beispiel #2
0
def run(argv) -> None:
    args = parser.parse_args(argv)

    palette = [
        ("text", "white", "black", ""),
        ("edit", "black", "yellow", ""),
        ("btn focus", "white", "dark red", ""),
        ("btn normal", "white", "dark blue", ""),
        ("li normal", "light cyan", "black", ""),
        ("li focus", "white", "dark red", ""),
        ("pg normal", "white", "black", "standout"),
        ("pg inverted", "black", "light gray", "standout"),
        ("pg complete", "white", "dark magenta"),
        ("pg smooth", "dark magenta", "black"),
        ("screen header", "white", "brown", "standout"),
        ("screen header divider", "black", "brown", ""),
        ("bg", "light gray", "black", ""),
        ("success message", "light green", "black", ""),
        ("success banner", "white", "dark green", ""),
        ("error message", "light red", "black", ""),
        ("error banner", "yellow", "dark red", ""),
        ("progress", "light magenta", "black", ""),
        ("remark", "dark gray", "black", ""),
        ("highlight", "yellow", "black", ""),
        ("topbar", "black", "white", ""),
        # Indicator color scheme
        ("ind normal", "black", "white", ""),
        ("ind error", "dark red", "white", ""),
        ("ind warning", "brown", "white", ""),
        ("ind good", "dark green", "white", ""),
        # Light color scheme (for modals and popups)
        ("bg light", "black", "white", ""),
        ("li normal light", "dark blue", "white", ""),
        ("success message light", "dark green", "white", ""),
        ("error message light", "dark red", "white", ""),
        ("pg normal light", "white", "black", "standout"),
    ]

    asyncioloop = asyncio.get_event_loop()
    evl = urwid.AsyncioEventLoop(loop=asyncioloop)

    urwidloop = urwid.MainLoop(
        None, palette=palette, event_loop=evl, input_filter=debounce_esc, pop_ups=True,
    )

    screen = ScreenManagerImpl(urwidloop)

    shell = OpenvarioShellImpl(screen, config=args.config, rootfs=args.sim)
    shell.extensions.load_all(shell)
    shell.apps.install_new_apps()

    asyncioloop.call_soon(startui, (shell, args.run))

    try:
        urwidloop.run()
    except KeyboardInterrupt:
        pass

    # Clear the screen on exit
    print("\033[H\033[J", end="")
Beispiel #3
0
    def run(self, debug: bool = False) -> None:
        """
        Starts the long running co-routines and the urwid event loop.

        :param debug:
            Enables/Disables asyncio event loop debugging
        """
        screen = urwid.raw_display.Screen()
        screen.set_terminal_properties(256)

        self.aloop = asyncio.get_event_loop()
        self.aloop.set_debug(debug)

        # Gracefully handle SIGTERM and SIGINT signals
        cancel_signals = [signal.SIGTERM, signal.SIGINT]
        for sig in cancel_signals:
            self.aloop.add_signal_handler(sig, self.kill_app)

        event_loop = urwid.AsyncioEventLoop(loop=self.aloop)
        main_loop = urwid.MainLoop(urwid.AttrMap(self.window, 'background'),
                                   unhandled_input=self.unhandled_input,
                                   screen=screen,
                                   palette=palette,
                                   handle_mouse=True,
                                   event_loop=event_loop)

        create_task(self.manage_connection(), self.aloop)
        try:
            main_loop.run()
        except Exception as err:
            logging.error('%s\n%s\n', str(err), pretty_traceback())
            raise err
Beispiel #4
0
    def __init__(self, cookies_path, keybindings, palette):
        """Start the user interface."""
        self._keys = keybindings

        # These are populated by on_connect when it's called.
        self._conv_widgets = {}  # {conversation_id: ConversationWidget}
        self._tabbed_window = None  # TabbedWindowWidget
        self._conv_list = None  # hangups.ConversationList
        self._user_list = None  # hangups.UserList
        self._notifier = None  # hangups.notify.Notifier

        # TODO Add urwid widget for getting auth.
        try:
            cookies = hangups.auth.get_auth_stdin(cookies_path)
        except hangups.GoogleAuthError as e:
            sys.exit('Login failed ({})'.format(e))

        self._client = hangups.Client(cookies)
        self._client.on_connect.add_observer(self._on_connect)

        loop = asyncio.get_event_loop()
        self._urwid_loop = urwid.MainLoop(
            LoadingWidget(),
            palette,
            handle_mouse=False,
            event_loop=urwid.AsyncioEventLoop(loop=loop))

        self._urwid_loop.start()
        try:
            # Returns when the connection is closed.
            loop.run_until_complete(self._client.connect())
        finally:
            # Ensure urwid cleans up properly and doesn't wreck the terminal.
            self._urwid_loop.stop()
Beispiel #5
0
    async def __call__(self):
        btask = self.loop.create_task(self.bus.notify(False))
        context = self.load_suite()
        reporter = functools.partial(self.exception_handler, context)
        self.loop.set_exception_handler(reporter)
        if self.skin == "tui":
            screen = urwid.raw_display.Screen()
            screen.set_terminal_properties(256)
            view = TUIView(self.bus, context, screen)
            view_controller = urwid.MainLoop(
                view,
                palette,
                screen=screen,
                event_loop=urwid.AsyncioEventLoop(loop=self.loop),
                unhandled_input=view.input_handler)
        else:
            view = RawView(self.bus, context)
            view_controller = NoopViewController()

        if self.xunit:
            xunit = XUnitView(self.bus, context, self.xunit)  # noqa

        try:
            view_controller.start()
            await self.connect_controller(context)
            await self.run(context)
        finally:
            # Wait for any unprocessed events before exiting the loop
            await btask
            view_controller.stop()
            await context.juju_controller.disconnect()
        self.loop.stop()
        if self._exc and not isinstance(self._exc, ShutdownException):
            raise self._exc[0](self._exc[1]).with_traceback(self._exc[2])
Beispiel #6
0
Datei: ui.py Projekt: rr-/soladm
    def __init__(
            self,
            connection: net.Connection,
            log_path: Optional[Path]) -> None:
        self._connection = connection
        self._connection.on_connecting.append(self._on_connecting)
        self._connection.on_connect.append(self._on_connect)
        self._connection.on_disconnect.append(self._on_disconnect)
        self._connection.on_message.append(self._on_message)
        self._connection.on_refresh.append(self._on_refresh)
        self._connection.on_exception.append(self._on_exception)
        self._refreshed = False
        self._log_path = log_path

        self._main_widget = MainWidget(self._connection.game_info)
        urwid.signals.connect_signal(
            self._main_widget.console.input_box, 'command', self._command)
        urwid.signals.connect_signal(
            self._main_widget.console.input_box, 'chat', self._chat)
        self._loop = urwid.MainLoop(
            self._main_widget, event_loop=urwid.AsyncioEventLoop())
        self._loop.screen.set_terminal_properties(256)

        self._load_palette()
        self._load_last_log()
Beispiel #7
0
    def __init__(self, pubpen, cli_args):
        super().__init__(pubpen, cli_args)

        # Note: We don't have any extra command line args

        # Windows

        self.title_card = TitleScreen(pubpen)
        self.login_screen = LoginScreen(pubpen)
        self.main_window = MainScreen(pubpen)
        self.root_win = urwid.Frame(urwid.SolidFill(' '))

        # Arrange the widgets

        self.show_title_card()

        # Connect to UI events

        urwid.connect_signal(self.title_card, 'close_title_card',
                             self.show_login_screen)
        urwid.connect_signal(self.login_screen, 'logged_in',
                             self.show_main_window)

        # Setup the main loop

        self.urwid_loop = urwid.MainLoop(
            self.root_win,
            event_loop=urwid.AsyncioEventLoop(loop=self.pubpen.loop),
            palette=(('reversed', 'standout', ''), ),
        )
Beispiel #8
0
 def __init__(self, loop):
     base = urwid.SolidFill("")
     self.loop = urwid.MainLoop(
         base,
         event_loop=urwid.AsyncioEventLoop(loop=loop),
         palette=palettes)
     self.base = base
Beispiel #9
0
    def __init__(self):
        super().__init__(False if (len(sys.argv) > 1 and sys.argv[1] == '1') else True)

        self.notifInfo = {'buffer': '', 'timer': 0, 'endTimer': 6}

        self.loop = asyncio.get_event_loop()

        self.loop.create_task(self.initSessions())

        self.main_widget = self.build_main_widget()

        self.mainKeyList = [{'keybind' : self.fileIO.cfg['keybinds']['upload'],
                             'widget' : self.build_upload_widget,
                             'input' : self.handle_keys_null},

                            {'keybind' : self.fileIO.cfg['keybinds']['download'],
                             'widget' : self.build_download_widget,
                             'input' : self.handle_keys_download},

                            {'keybind' : self.fileIO.cfg['keybinds']['resume'],
                             'widget' : self.build_resume_widget,
                             'input' : self.handle_keys_null}]

        palette = [('boldtext', 'default,bold', 'default', 'bold'), ('reversed', 'standout', '')]

        self.urwid_loop = urwid.MainLoop(
            widget=self.main_widget,
            palette=palette,
            handle_mouse=False,
            unhandled_input=self.handle_keys_main,
            event_loop=urwid.AsyncioEventLoop(loop=self.loop)
        )
Beispiel #10
0
    def __init__(self, vehicle, joystick):
        self._vehicle = vehicle
        self._joystick = joystick
        self.mapping = {}
        self.success = False
        palette = [('bg', 'black', 'white'), ('title', 'black,bold', 'white')]

        title = urwid.Text(('title', '\n{}\n'.format(TITLE)), align='center')
        self._text = urwid.Text('')

        def skip_or_finish(obj):
            if self._current >= len(self._vehicle.inputs):
                self.success = True
                raise urwid.ExitMainLoop()
            self._next_input()

        self._btn = urwid.Button('', on_press=skip_or_finish)

        def exit(obj):
            raise urwid.ExitMainLoop()

        exit_btn = urwid.Button('Exit', on_press=exit)

        rows = urwid.Pile([title, self._text, self._btn, exit_btn])
        top = urwid.AttrMap(urwid.Filler(rows, 'top'), 'bg')
        evl = urwid.AsyncioEventLoop(loop=asyncio.get_event_loop())
        self._loop = urwid.MainLoop(top, palette, event_loop=evl)

        self._locked_axes = set()
        self._current = 0
        self._current_sub = 0  # for trimmer
        self._update_text()
Beispiel #11
0
def main(args=None):
    loop = asyncio.get_event_loop()
    bus = Bus(loop=loop)
    # logging resolves default bus from the module
    set_default_bus(bus)

    matrix = rules.RuleEngine(bus=bus)
    options = setup(matrix, args)
    loop.set_debug(options.log_level == logging.DEBUG)
    loop.create_task(matrix())

    if options.skin == "tui":
        view = TUIView(bus)
        view_controller = urwid.MainLoop(
            view.widgets,
            event_loop=urwid.AsyncioEventLoop(loop=loop),
            unhandled_input=unhandled)
    else:
        view = RawView(bus)
        view_controller = NoopViewController()

    try:
        loop.create_task(bus.notify(False))
        view_controller.start()
        loop.run_forever()
    finally:
        view_controller.stop()
        loop.stop()
        loop.close()
Beispiel #12
0
    def run(self):
        if not sys.stdout.isatty():
            print("Error: mitmproxy's console interface requires a tty. "
                  "Please run mitmproxy in an interactive shell environment.", file=sys.stderr)
            sys.exit(1)

        self.ui = window.Screen()
        self.ui.set_terminal_properties(256)
        self.set_palette(self.options, None)
        self.options.subscribe(
            self.set_palette,
            ["console_palette", "console_palette_transparent"]
        )
        self.loop = urwid.MainLoop(
            urwid.SolidFill("x"),
            event_loop=urwid.AsyncioEventLoop(loop=asyncio.get_event_loop()),
            screen = self.ui,
            handle_mouse = self.options.console_mouse,
        )
        self.window = window.Window(self)
        self.loop.widget = self.window
        self.window.refresh()

        if self.start_err:
            def display_err(*_):
                self.sig_add_log(None, self.start_err)
                self.start_err = None
            self.loop.set_alarm_in(0.01, display_err)

        super().run_loop(self.loop.run)
Beispiel #13
0
def test_pop_activity() -> None:
    # GIVEN
    # Create a basic palette and an urwid main loop - we are messing with the internal
    # implementation of palette handling.
    urwid_mock = UrwidMock()
    palette = [
        ("text", "white", "black", ""),
    ]
    asyncioloop = asyncio.get_event_loop()
    evl = urwid.AsyncioEventLoop(loop=asyncioloop)
    mainloop = urwid.MainLoop(None, palette=palette, event_loop=evl)

    screen = ScreenManagerImpl(mainloop)
    act1 = ActivityStub("Activity One")
    act2 = ActivityStub("Activity Two")
    screen.push_activity(act1)
    screen.push_activity(act2)

    assert "Activity Two" in urwid_mock.render(mainloop.widget)

    # WHEN
    screen.pop_activity()

    # THEN
    assert "Activity One" in urwid_mock.render(mainloop.widget)
    assert act2.activated == 1
    assert act2.destroyed == 1
    assert act2.shown == 1
    assert act2.hidden == 1

    assert act1.activated == 1
    assert act1.shown == 2
    assert act1.hidden == 1
    def run(self, loop):
        urwid_loop = urwid.MainLoop(
            self.root_widget,
            event_loop=urwid.AsyncioEventLoop(loop=loop),
            unhandled_input=self.unhandled,
        )

        return urwid_loop
Beispiel #15
0
 def runloop(self):
     self.loop = urwid.MainLoop(
         self.main_widget,
         self.palette,
         # This event loop plays nicer with vlc callbacks
         event_loop=urwid.AsyncioEventLoop(),
         unhandled_input=self.handle_input,
     )
     self.loop.run()
Beispiel #16
0
def demo1():
    txt = urwid.Text(u"Hello World!!!!")
    fill = urwid.Filler(txt, 'top')
    urwid_loop = urwid.MainLoop(
        fill,
        event_loop=urwid.AsyncioEventLoop(loop=asyncio.get_event_loop()),
        unhandled_input=unhandled,
    )
    urwid_loop.run()
Beispiel #17
0
 def loop(self, handle_mouse=False):
     # self.eloop=urwid.MainLoop(self, self.PALLETE, handle_mouse=handle_mouse)
     # self._eloop_thread=threading.current_thread()
     # self.eloop.run()
     import asyncio
     evl = urwid.AsyncioEventLoop(loop=asyncio.get_event_loop())
     self.eloop = urwid.MainLoop(self, self.PALLETE, event_loop=evl, handle_mouse=True)
     self._eloop_thread=threading.current_thread()
     self.eloop.run()
Beispiel #18
0
 def main(self):
     self.setup_view()
     evl = urwid.AsyncioEventLoop(loop=asyncio.get_event_loop())
     loop = urwid.MainLoop(self.view,
                           palette=self.palette,
                           unhandled_input=self.keypress,
                           event_loop=evl)
     loop.set_alarm_in(self.timer, self.refresh)
     loop.run()
Beispiel #19
0
def wiredolphin(filename):
    asyncio.ensure_future(capture_memeory_packets(filename))
    main_loop = urwid.MainLoop(
        urwid.Frame(pile),
        palette=palette,
        screen=screen,
        unhandled_input=global_input,
        event_loop=urwid.AsyncioEventLoop(loop=event_loop))
    main_loop.run()
Beispiel #20
0
 def run(self):
     self.loop=urwid.MainLoop(
       self.tui,
       self.PALETTE,
       event_loop=urwid.AsyncioEventLoop(loop=self.aloop),
       unhandled_input=self.handle_keys,
       handle_mouse=False
     )
     self.state.set_text(self.GLOBAL_STATES['CONWAIT'])
     self.loop.run()
Beispiel #21
0
 def build_loop(cls, ui, palette, **kwargs):
     """ Builds eventloop
     """
     cls.extra_opts['screen'].set_terminal_properties(colors=256)
     cls.extra_opts.update(**kwargs)
     evl = asyncio.get_event_loop()
     cls.loop = urwid.MainLoop(ui,
                               palette,
                               event_loop=urwid.AsyncioEventLoop(loop=evl),
                               pop_ups=True,
                               **cls.extra_opts)
Beispiel #22
0
    def main(self) -> None:
        self._asyncio_loop = asyncio.get_event_loop()
        self._loop = urwid.MainLoop(
            self._view,
            palette=self._palette_generator.create_palette(),
            event_loop=urwid.AsyncioEventLoop(loop=self._asyncio_loop),
        )
        self._loop.screen.set_terminal_properties(colors=256)

        self._asyncio_loop.create_task(self._get_zone_websocket_jobs())
        self._loop.run()
Beispiel #23
0
    def __init__(self, argv):
        signal.signal(signal.SIGINT, self.sigint)
        self.file = argv[1]
        self.readonly = False
        if self.file.startswith('ip:'):
            ip = tuple(self.file.split(':')[1:])
            print(ip)
            self.fd = socket.create_connection(self.file.split(':')[1:])
            self.io = self.fd.makefile('rw')
        else:
            if stat.S_ISCHR(os.stat(self.file).st_mode):
                self.fd = serial.Serial(self.file, 115200, timeout=1)
                self.io = io.TextIOWrapper(io.BufferedRandom(self.fd))
            else:
                self.fd = io.FileIO(self.file, 'r')
                self.io = io.TextIOWrapper(io.BufferedReader(self.fd))
                self.readonly = True

        self.leftbox = urwid.ListBox(
            urwid.SimpleFocusListWalker([urwid.Text('')]))
        self.rightbox = urwid.ListBox(
            urwid.SimpleFocusListWalker([urwid.Text(''),
                                         urwid.Text('')]))
        self.column = urwid.Columns([self.leftbox, self.rightbox])
        self.header = urwid.AttrMap(urwid.Text('CAN Bus data stats'), 'header')

        self.status_icons = urwid.WidgetPlaceholder(urwid.Text(''))
        self.status_packets = urwid.WidgetPlaceholder(urwid.Text(''))

        self.footer = urwid.AttrMap(
            urwid.Columns([self.status_icons, self.status_packets]), 'footer')
        self.frame = urwid.PopUpTarget(
            urwid.Frame(self.column, header=self.header, footer=self.footer))

        self.statline = []
        self.c_packets = 0
        self.errors = 0
        self.packets = []
        self.packets_by_id = dictlist()
        self.packet_last_time = {}
        self.packet_avg_times = {}
        self.ids = Counter()
        self.classes = Counter()
        self.event_loop = urwid.AsyncioEventLoop()
        self.main_loop = urwid.MainLoop(self.frame,
                                        event_loop=self.event_loop,
                                        unhandled_input=self.handle_key)
        self.watch_file_handle = None
        self.toggle_watch()
        self.event_loop.alarm(0.25, self.update_display)

        if self.readonly:
            self.update_statline('RO')
Beispiel #24
0
def main():
    global loop, client, urwid_loop
    client = motor.motor_asyncio.AsyncIOMotorClient(host="localhost")
    loop = asyncio.get_event_loop()
    urwid_loop = urwid.MainLoop(
        urwid.SolidFill(),  # Placeholder
        palette=[('reversed', 'standout', '')],
        event_loop=urwid.AsyncioEventLoop(loop=loop),
        unhandled_input=lambda k: asyncio.create_task(handle_input(k)),
    )
    loop.create_task(render())
    urwid_loop.run()
Beispiel #25
0
 def build_app(self):
     widgets, scrolled_texts = self.create_widgets()
     top = self.build_top(widgets)
     evl = urwid.AsyncioEventLoop(loop=self.loop)
     urwid_loop = urwid.MainLoop(top,
                                 self.palette,
                                 event_loop=evl,
                                 unhandled_input=self.key_handler,
                                 handle_mouse=False)
     self.widgets = widgets
     self.scrolled_texts = scrolled_texts
     return urwid_loop
Beispiel #26
0
    def start(self, loop, will_align):
        widgets = self.build_widgets(will_align)

        uaioloop = urwid.AsyncioEventLoop(loop=loop)
        self.urwid_loop = urwid.MainLoop(widgets,
                                         event_loop=uaioloop,
                                         palette=self.palette,
                                         unhandled_input=self.exit_on_q)

        self.start_update_hooks(loop)

        self.urwid_loop.start()
Beispiel #27
0
def get_app_in_loop(pallete):
    screen = urwid.raw_display.Screen()
    screen.set_terminal_properties(256)
    screen.register_palette(pallete)

    ui = UI(urwid.SolidFill())
    decorated_ui = urwid.AttrMap(ui, "root")
    loop = ThreadSafeLoop(decorated_ui, screen=screen, event_loop=urwid.AsyncioEventLoop(),
                          handle_mouse=False)
    ui.loop = loop

    return loop, ui
Beispiel #28
0
    def __init__(self, refresh_token_path, keybindings, palette,
                 palette_colors, datetimefmt, notifier_,
                 discreet_notifications):
        """Start the user interface."""
        self._keys = keybindings
        self._datetimefmt = datetimefmt
        self._notifier = notifier_
        self._discreet_notifications = discreet_notifications

        set_terminal_title('hangups')

        # These are populated by on_connect when it's called.
        self._conv_widgets = {}  # {conversation_id: ConversationWidget}
        self._tabbed_window = None  # TabbedWindowWidget
        self._conv_list = None  # hangups.ConversationList
        self._user_list = None  # hangups.UserList

        # TODO Add urwid widget for getting auth.
        try:
            cookies = hangups.auth.get_auth_stdin(refresh_token_path)
        except hangups.GoogleAuthError as e:
            sys.exit('Login failed ({})'.format(e))

        self._client = hangups.Client(cookies)
        self._client.on_connect.add_observer(self._on_connect)

        loop = asyncio.get_event_loop()
        try:
            self._urwid_loop = urwid.MainLoop(
                LoadingWidget(),
                palette,
                handle_mouse=False,
                input_filter=self._input_filter,
                event_loop=urwid.AsyncioEventLoop(loop=loop))
        except urwid.AttrSpecError as e:
            # Fail gracefully for invalid colour options.
            sys.exit(e)

        self._urwid_loop.screen.set_terminal_properties(colors=palette_colors)
        self._urwid_loop.start()
        # Enable bracketed paste mode after the terminal has been switched to
        # the alternate screen (after MainLoop.start() to work around bug
        # 729533 in VTE.
        with bracketed_paste_mode():
            try:
                # Returns when the connection is closed.
                loop.run_until_complete(self._client.connect())
            finally:
                # Ensure urwid cleans up properly and doesn't wreck the
                # terminal.
                self._urwid_loop.stop()
                loop.close()
Beispiel #29
0
async def run():
    placeholder = urwid.WidgetPlaceholder(
        urwid.Filler(urwid.Text("Initialize...")))
    with urwid.MainLoop(
            urwid.LineBox(placeholder),
            event_loop=urwid.AsyncioEventLoop(),
            handle_mouse=False,
    ).start():

        def widget_cb(widget):
            placeholder.original_widget = widget

        await main_menu(widget_cb)
Beispiel #30
0
    def create(cls, app, user):
        """Factory method, sets up TUI and an event loop."""

        tui = cls(app, user)
        loop = urwid.MainLoop(
            tui,
            palette=PALETTE,
            event_loop=urwid.AsyncioEventLoop(),
            unhandled_input=tui.unhandled_input,
        )
        tui.loop = loop

        return tui