Exemplo n.º 1
0
    def example_repl(self, text, example, start_index):
        """ REPL for interactive tutorials """
        global EXAMPLE_REPL
        EXAMPLE_REPL = True
        if start_index:
            start_index = start_index + 1
            cmd = ' '.join(text.split()[:start_index])
            example_cli = CommandLineInterface(
                application=self.create_application(
                    all_layout=False),
                eventloop=create_eventloop())
            example_cli.buffers['example_line'].reset(
                initial_document=Document(u'%s\n' %example)
            )
            for i in range(len(text.split()) - start_index):
                example_cli.buffers[DEFAULT_BUFFER].reset(
                    initial_document=Document(u'%s' %cmd,\
                    cursor_position=len(cmd)))
                example_cli.request_redraw()
                answer = example_cli.run()
                if not answer:
                    return ""
                answer = answer.text
                start_index += 1
                if len(answer.split()) > 1:
                    cmd += " " + answer.split()[-1] + " " +\
                    u' '.join(text.split()[start_index:start_index + 1])
            example_cli.exit()
            del example_cli
        else:
            cmd = text

        EXAMPLE_REPL = False
        return cmd
Exemplo n.º 2
0
    def run(self):
        """
        Create an event loop for the application and run it.
        """
        self.eventloop = create_eventloop()

        try:
            self.cli = CommandLineInterface(application=self.application,
                                            eventloop=self.eventloop,
                                            input=StdinInput(sys.stdout))

            # Hide message when a key is pressed.
            def key_pressed(_):
                self.message = None

            self.cli.input_processor.beforeKeyPress += key_pressed

            def pre_run():
                # Set search highlighting.
                if self.search_text:
                    self.cli.search_state.text = self.search_text

            with self.cli.patch_stdout_context():
                self.cli.run(reset_current_buffer=False, pre_run=pre_run)
        finally:
            # Close eventloop.
            self.eventloop.close()
            self.eventloop = None
Exemplo n.º 3
0
    def example_repl(self, text, example, start_index, continue_flag):
        """ REPL for interactive tutorials """
        if start_index:
            start_index = start_index + 1
            cmd = ' '.join(text.split()[:start_index])
            example_cli = CommandLineInterface(
                application=self.create_application(full_layout=False),
                eventloop=create_eventloop())
            example_cli.buffers['example_line'].reset(
                initial_document=Document(u'{}\n'.format(add_new_lines(
                    example))))
            while start_index < len(text.split()):
                if self.default_command:
                    cmd = cmd.replace(self.default_command + ' ', '')
                example_cli.buffers[DEFAULT_BUFFER].reset(
                    initial_document=Document(u'{}'.format(cmd),
                                              cursor_position=len(cmd)))
                example_cli.request_redraw()
                answer = example_cli.run()
                if not answer:
                    return "", True
                answer = answer.text
                if answer.strip('\n') == cmd.strip('\n'):
                    continue
                else:
                    if len(answer.split()) > 1:
                        start_index += 1
                        cmd += " " + answer.split()[-1] + " " +\
                               u' '.join(text.split()[start_index:start_index + 1])
            example_cli.exit()
            del example_cli
        else:
            cmd = text

        return cmd, continue_flag
Exemplo n.º 4
0
    def select_index(self, message=None, clear_before=False):
        if clear_before:
            # for windows
            if os.name == 'nt':
                _ = os.system('cls')
            # for mac and linux(here, os.name is 'posix')
            else:
                _ = os.system('clear')

        if message != None:
            self.prompt_msg = message

        layout = self._get_layout()
        style = self._get_style()
        registry = set_key_binding(self.controller)

        application = Application(layout=layout,
                                  style=style,
                                  key_bindings_registry=registry)

        eventloop = create_eventloop()

        try:
            cli = CommandLineInterface(application=application,
                                       eventloop=eventloop)
            cli.run()

        finally:
            eventloop.close()
            return self.controller.selected_option_index
Exemplo n.º 5
0
    def __init__(self, *a, **kw):
        vi_mode = kw.pop('vi_mode', False)
        history_filename = kw.pop('history_filename', None)
        configure = kw.pop('configure', None)
        title = kw.pop('title', None)

        super(InteractiveShellEmbed, self).__init__(*a, **kw)

        def get_globals():
            return self.user_ns

        self._eventloop = create_eventloop()
        ipython_input = IPythonInput(self,
                                     get_globals=get_globals,
                                     vi_mode=vi_mode,
                                     history_filename=history_filename)

        if title:
            ipython_input.terminal_title = title

        if configure:
            configure(ipython_input)
            ipython_input.prompt_style = 'ipython'  # Don't take from config.

        self._cli = CommandLineInterface(
            application=ipython_input.create_application(),
            eventloop=self._eventloop)
Exemplo n.º 6
0
    def pt_init(self):
        def get_prompt_tokens(cli):
            return [(Token.Prompt, self.prompt)]

        def patch_stdout(**kwargs):
            return self.pt_cli.patch_stdout_context(**kwargs)

        if self._ptcomp is None:
            compl = IPCompleter(
                shell=self.shell,
                namespace={},
                global_namespace={},
                parent=self.shell,
            )
            self._ptcomp = IPythonPTCompleter(compl, patch_stdout=patch_stdout)

        kbmanager = KeyBindingManager.for_prompt()
        supports_suspend = Condition(lambda cli: hasattr(signal, 'SIGTSTP'))
        kbmanager.registry.add_binding(Keys.ControlZ,
                                       filter=supports_suspend)(suspend_to_bg)

        self._pt_app = create_prompt_application(
            editing_mode=getattr(EditingMode, self.shell.editing_mode.upper()),
            key_bindings_registry=kbmanager.registry,
            history=self.shell.debugger_history,
            completer=self._ptcomp,
            enable_history_search=True,
            mouse_support=self.shell.mouse_support,
            get_prompt_tokens=get_prompt_tokens)
        self.pt_cli = CommandLineInterface(self._pt_app,
                                           eventloop=self.shell._eventloop)
Exemplo n.º 7
0
def _feed_cli_with_input(text,
                         editing_mode=EditingMode.EMACS,
                         clipboard=None,
                         history=None):
    """
    Create a CommandLineInterface, feed it with the given user input and return
    the CLI object.

    This returns a (result, CLI) tuple.
    """
    # If the given text doesn't end with a newline, the interface won't finish.
    assert text.endswith('\n')

    from prompt_toolkit.eventloop.posix import PosixEventLoop as EventLoop
    loop = EventLoop()
    try:
        inp = PipeInput()
        inp.send_text(text)
        cli = CommandLineInterface(application=Application(
            buffer=Buffer(accept_action=AcceptAction.RETURN_DOCUMENT,
                          history=history),
            editing_mode=editing_mode,
            clipboard=clipboard or InMemoryClipboard(),
            key_bindings_registry=KeyBindingManager.for_prompt().registry,
        ),
                                   eventloop=loop,
                                   input=inp,
                                   output=DummyOutput())
        result = cli.run()
        return result, cli
    finally:
        loop.close()
        inp.close()
def main():
    eventloop = create_eventloop()
    done = [False]  # Non local

    def on_read_start(cli):
        """
        This function is called when we start reading at the input.
        (Actually the start of the read-input event loop.)
        """

        # Following function should be run in the background.
        # We do it by using an executor thread from the `CommandLineInterface`
        # instance.
        def run():
            # Send every second a redraw request.
            while not done[0]:
                time.sleep(1)
                cli.request_redraw()

        cli.eventloop.run_in_executor(run)

    def on_read_end(cli):
        done[0] = True

    app = Application(layout=Window(
        BufferControl(input_processors=[BeforeInput(_clock_tokens)])),
                      on_start=Callback(on_read_start),
                      on_stop=Callback(on_read_end))

    cli = CommandLineInterface(application=app, eventloop=eventloop)

    code_obj = cli.run()
    print('You said: %s' % code_obj.text)

    eventloop.close()
Exemplo n.º 9
0
    def connected(self):
        # prompt_toolkit internally checks if it's on windows during output rendering but
        # we need to force that we use Vt100_Output not Win32_Output
        from prompt_toolkit import renderer
        renderer.is_windows = lambda: False

        def get_size():
            return self._size

        self._cli = CommandLineInterface(
            application=create_prompt_application(self._shell.prompt),
            eventloop=UnstoppableEventLoop(create_asyncio_eventloop(
                self._loop)),
            input=PatchedStdinInput(sys.stdin),
            output=Vt100_Output(self, get_size))

        self._cb = self._cli.create_eventloop_callbacks()
        self._inputstream = InputStream(self._cb.feed_key)
        # Taken from prompt_toolkit telnet server
        # https://github.com/jonathanslenders/python-prompt-toolkit/blob/99fa7fae61c9b4ed9767ead3b4f9b1318cfa875d/prompt_toolkit/contrib/telnet/server.py#L165
        self._cli._is_running = True

        if self._shell.welcome_message is not None:
            self.send(self._shell.welcome_message.encode())

        self._cli._redraw()
Exemplo n.º 10
0
    def pt_init(self):
        def get_prompt_tokens(cli):
            return [(Token.Prompt, self.prompt)]

        def patch_stdout(**kwargs):
            return self.pt_cli.patch_stdout_context(**kwargs)

        if self._ptcomp is None:
            compl = IPCompleter(
                shell=self.shell,
                namespace={},
                global_namespace={},
                parent=self.shell,
            )
            self._ptcomp = IPythonPTCompleter(compl, patch_stdout=patch_stdout)

        self._pt_app = create_prompt_application(
            editing_mode=getattr(EditingMode, self.shell.editing_mode.upper()),
            history=self.shell.debugger_history,
            completer=self._ptcomp,
            enable_history_search=True,
            mouse_support=self.shell.mouse_support,
            get_prompt_tokens=get_prompt_tokens)
        self.pt_cli = CommandLineInterface(self._pt_app,
                                           eventloop=self.shell._eventloop)
Exemplo n.º 11
0
    def init_prompt_toolkit_cli(self):
        """
        Initializes the Prompt Tookkit CLI.
        """
        self.init_lexer()

        kbmanager = KeyBindingManager.for_prompt()
        style_overrides = {
            Token.Prompt: '#aaddaa',
            Token.OutPrompt: '#ddaaaa',
            Token.Name.Namespace: '#ddaadd',
            Token.Name.Function: '#aadddd',
        }
        style_cls = get_style_by_name('default')
        style = PygmentsStyle.from_defaults(pygments_style_cls=style_cls,
                                            style_dict=style_overrides)
        app = create_prompt_application(
            get_prompt_tokens=self.get_prompt_tokens,
            key_bindings_registry=kbmanager.registry,
            completer=self._completer,
            lexer=self._lexer,
            style=style,
        )

        self._eventloop = create_eventloop()
        self.pt_cli = CommandLineInterface(
            app,
            eventloop=self._eventloop,
            output=create_output(true_color=False),
        )
Exemplo n.º 12
0
 def __init__(self, host):
     self.host = host
     self.socket = None
     self.cli = CommandLineInterface(
         application=create_prompt_application('> '),
         eventloop=create_asyncio_eventloop())
     sys.stdout = self.cli.stdout_proxy()
Exemplo n.º 13
0
def interactive_shell():
    """
    Coroutine that shows the interactive command line.
    """
    # Create an asyncio `EventLoop` object. This is a wrapper around the
    # asyncio loop that can be passed into prompt_toolkit.
    eventloop = create_asyncio_eventloop()

    # Create interface.
    cli = CommandLineInterface(application=create_default_application(
        'Say something inside the event loop: '),
                               eventloop=eventloop)

    # Patch stdout in something that will always print *above* the prompt when
    # something is written to stdout.
    sys.stdout = cli.stdout_proxy()

    # Run echo loop. Read text from stdin, and reply it back.
    while True:
        try:
            result = yield from cli.run_async()
            print('You said: "%s"\n' % result.text)
        except (EOFError, KeyboardInterrupt):
            loop.stop()
            print('Qutting event loop. Bye.')
            return
Exemplo n.º 14
0
    def _build_cli(self):
        

        get_prompt_tokens = lambda cli: \
                            [(Token.Prompt, '\nIn [%d]: ' % cli.current_buffer.return_count)]
        get_continuation_tokens = lambda cli, width: \
                            [(Token.Continuation, '.' * (width - 1) + ' ')]

        buffer = GoBuffer(
            always_multiline=True,
            accept_action=AcceptAction.RETURN_DOCUMENT
        )
        layout = create_prompt_layout(
            lexer=PygmentsLexer(GoLexer),
            get_prompt_tokens=get_prompt_tokens,
            get_continuation_tokens=get_continuation_tokens,
            get_bottom_toolbar_tokens=get_toolbar_tokens,
            multiline=True
        )
        application = Application(
            layout=layout,
            buffer=buffer,
            style=get_style(),
            key_bindings_registry=key_bindings_registry(),
            ignore_case=True
        )
        render_title = lambda text: zip(itertools.repeat(Token), ['\nQuickGo\n', 'Author: Robus Gauli | [email protected]\n',text,'\n\n'])
        print_tokens(render_title('Version: Experimental 0.0.0'))
        cli = CommandLineInterface(application=application, eventloop=self.event_loop)
        return cli



        
Exemplo n.º 15
0
    def init_prompt_toolkit_cli(self):
        if self.simple_prompt:
            # Fall back to plain non-interactive output for tests.
            # This is very limited, and only accepts a single line.
            def prompt():
                isp = self.input_splitter
                prompt_text = "".join(x[1]
                                      for x in self.prompts.in_prompt_tokens())
                prompt_continuation = "".join(
                    x[1] for x in self.prompts.continuation_prompt_tokens())
                while isp.push_accepts_more():
                    line = cast_unicode_py2(input(prompt_text))
                    isp.push(line)
                    prompt_text = prompt_continuation
                return isp.source_reset()

            self.prompt_for_code = prompt
            return

        # Set up keyboard shortcuts
        kbmanager = KeyBindingManager.for_prompt(
            enable_open_in_editor=self.extra_open_editor_shortcuts, )
        register_ipython_shortcuts(kbmanager.registry, self)

        # Pre-populate history from IPython's history database
        history = InMemoryHistory()
        last_cell = u""
        for __, ___, cell in self.history_manager.get_tail(
                self.history_load_length, include_latest=True):
            # Ignore blank lines and consecutive duplicates
            cell = cell.rstrip()
            if cell and (cell != last_cell):
                history.append(cell)
                last_cell = cell

        self._style = self._make_style_from_name_or_cls(
            self.highlighting_style)
        self.style = DynamicStyle(lambda: self._style)

        editing_mode = getattr(EditingMode, self.editing_mode.upper())

        def patch_stdout(**kwargs):
            return self.pt_cli.patch_stdout_context(**kwargs)

        self._pt_app = create_prompt_application(
            editing_mode=editing_mode,
            key_bindings_registry=kbmanager.registry,
            history=history,
            completer=IPythonPTCompleter(shell=self,
                                         patch_stdout=patch_stdout),
            enable_history_search=True,
            style=self.style,
            mouse_support=self.mouse_support,
            **self._layout_options())
        self._eventloop = create_eventloop(self.inputhook)
        self.pt_cli = CommandLineInterface(
            self._pt_app,
            eventloop=self._eventloop,
            output=create_output(true_color=self.true_color))
Exemplo n.º 16
0
    def __init__(self, config_directory='~/.pyvim'):
        # Vi options.
        self.show_line_numbers = True
        self.highlight_search = True
        self.paste_mode = False
        self.show_ruler = True
        self.show_wildmenu = True
        self.expand_tab = True  # Insect spaces instead of tab characters.
        self.tabstop = 4  # Number of spaces that a tab character represents.
        self.incsearch = True  # Show matches while typing search string.
        self.ignore_case = False  # Ignore case while searching.
        self.display_unprintable_characters = True  # ':set list'
        self.enable_jedi = True  # ':set jedi', for Python Jedi completion.
        self.scroll_offset = 0  # ':set scrolloff'

        # Ensure config directory exists.
        self.config_directory = os.path.abspath(
            os.path.expanduser(config_directory))
        if not os.path.exists(self.config_directory):
            os.mkdir(self.config_directory)

        self._reporters_running_for_buffer_names = set()
        self.window_arrangement = WindowArrangement(self)
        self.message = None

        # Load styles. (Mapping from name to Style class.)
        self.styles = generate_built_in_styles()
        self.current_style = get_editor_style_by_name('default')

        # I/O backends.
        self.io_backends = [
            DirectoryIO(),
            HttpIO(),
            GZipFileIO(),  # Should come before FileIO.
            FileIO(),
        ]

        # Create eventloop.
        self.eventloop = create_eventloop()

        # Create key bindings manager
        self.key_bindings_manager = create_key_bindings(self)

        # Create layout and CommandLineInterface instance.
        self.editor_layout = EditorLayout(self, self.key_bindings_manager,
                                          self.window_arrangement)
        self.application = self._create_application()

        self.cli = CommandLineInterface(eventloop=self.eventloop,
                                        application=self.application)

        # Hide message when a key is pressed.
        def key_pressed():
            self.message = None

        self.cli.input_processor.beforeKeyPress += key_pressed

        # Command line previewer.
        self.previewer = CommandPreviewer(self)
Exemplo n.º 17
0
    def _create_cli(self):
        """
        Create CommandLineInterface instance.
        """

        # Create Vi command buffer.
        def handle_action(cli, buffer):
            ' When enter is pressed in the Vi command line. '
            text = buffer.text  # Remember: leave_command_mode resets the buffer.

            # First leave command mode. We want to make sure that the working
            # pane is focussed again before executing the command handlers.
            self.leave_command_mode(append_to_history=True)

            # Execute command.
            handle_command(self, text)

        # Create history and search buffers.
        commands_history = FileHistory(
            os.path.join(self.config_directory, 'commands_history'))
        command_buffer = Buffer(
            accept_action=AcceptAction(handler=handle_action),
            enable_history_search=Always(),
            completer=create_command_completer(self),
            history=commands_history)

        search_buffer_history = FileHistory(
            os.path.join(self.config_directory, 'search_history'))
        search_buffer = Buffer(history=search_buffer_history,
                               enable_history_search=Always(),
                               accept_action=AcceptAction.IGNORE)

        # Create CLI.
        cli = CommandLineInterface(
            eventloop=self.eventloop,
            layout=self.editor_layout.layout,
            key_bindings_registry=self.key_bindings_manager.registry,
            buffers={
                COMMAND_BUFFER: command_buffer,
                SEARCH_BUFFER: search_buffer,
            },
            style=get_editor_style_by_name('default'),
            paste_mode=Condition(lambda cli: self.paste_mode),
            ignore_case=Condition(lambda cli: self.ignore_case),
            use_alternate_screen=True,
            on_abort=AbortAction.IGNORE,
            on_exit=AbortAction.IGNORE)

        # Handle command line previews.
        # (e.g. when typing ':colorscheme blue', it should already show the
        # preview before pressing enter.)
        def preview():
            if cli.current_buffer == command_buffer:
                self.previewer.preview(command_buffer.text)

        command_buffer.onTextChanged += preview

        return cli
Exemplo n.º 18
0
def create_cli(eventloop,
               message='',
               multiline=False,
               is_password=False,
               vi_mode=False,
               lexer=None,
               enable_system_prompt=False,
               enable_open_in_editor=False,
               validator=None,
               completer=None,
               style=None,
               history=None,
               get_prompt_tokens=None,
               get_bottom_toolbar_tokens=None,
               extra_input_processors=None,
               key_bindings_registry=None,
               output=None,
               on_abort=AbortAction.RAISE_EXCEPTION,
               on_exit=AbortAction.RAISE_EXCEPTION,
               on_accept=AcceptAction.RETURN_DOCUMENT):
    """
    Create a `CommandLineInterface` instance.
    """
    assert isinstance(eventloop, EventLoop)

    # Create history instance.
    if history is None:
        history = History()

    # Use default registry from KeyBindingManager if none was given.
    if key_bindings_registry is None:
        key_bindings_registry = KeyBindingManager(
            enable_vi_mode=vi_mode,
            enable_system_prompt=enable_system_prompt,
            enable_open_in_editor=enable_open_in_editor).registry

    # Create interface.
    return CommandLineInterface(
        eventloop=eventloop,
        layout=create_default_layout(
            message=message,
            lexer=lexer,
            is_password=is_password,
            reserve_space_for_menu=(completer is not None),
            get_prompt_tokens=get_prompt_tokens,
            get_bottom_toolbar_tokens=get_bottom_toolbar_tokens,
            extra_input_processors=extra_input_processors),
        buffer=Buffer(
            is_multiline=(Always() if multiline else Never()),
            history=history,
            validator=validator,
            completer=completer,
        ),
        key_bindings_registry=key_bindings_registry,
        style=style,
        output=output,
        on_abort=on_abort,
        on_exit=on_exit)
Exemplo n.º 19
0
def run():
    eventloop = create_eventloop()
    try:
        cli = CommandLineInterface(application=application,
                                   eventloop=eventloop)
        cli.run()

    finally:
        eventloop.close()
Exemplo n.º 20
0
 def create_cli_interface(self, display_completions_in_columns):
     # A CommandLineInterface from prompt_toolkit
     # accepts two things: an application and an
     # event loop.
     loop = create_eventloop()
     app = self.create_application(self.completer, self.file_history,
                                   display_completions_in_columns)
     cli = CommandLineInterface(application=app, eventloop=loop)
     return cli
Exemplo n.º 21
0
    def create_cli(self, *a, **kw):
        """
        Create a `CommandLineInterface` instance. But use a
        renderer that outputs over the telnet connection, and use
        the eventloop of the telnet server.

        All parameters are send to ``CommandLineInterface.__init__``.
        """
        kw['renderer'] = Renderer(output=self.vt100_output)
        return CommandLineInterface(self.eventloop, *a, **kw)
Exemplo n.º 22
0
def repl(parser, interpreter, style_name='default'):
    registry = load_key_bindings()

    @registry.add_binding(Keys.Escape, Keys.Enter)  # meta-enter/alt-enter
    def _(event):
        '''Evaluate the buffer
        '''
        code = buffers[DEFAULT_BUFFER].text
        try:
            ast = parser.parse(code)
        except (UnexpectedToken, UnexpectedInput) as e:
            toolbar_value = str(e)
            return

        try:
            start_eval_time = time.time()
            retval = interpreter.eval(ast)
        except Exception as e:
            toolbar_value = "Error: %s" % e.args
            return
        else:
            buffers['RESULT'].text = str(retval)
            toolbar_value = "Time: {:0.4f}, Value: {}".format(
                time.time() - start_eval_time, str(retval))

    @registry.add_binding(Keys.ControlC, eager=True)
    @registry.add_binding(Keys.ControlQ, eager=True)
    def _(event):
        '''Exit the REPL
        '''
        event.cli.set_return_value(None)

    buffers = {
        DEFAULT_BUFFER: Buffer(is_multiline=True),
        'RESULT': Buffer(is_multiline=True),
    }
    style = style_from_pygments(get_style_by_name(style_name))

    application = Application(layout=layout,
                              buffers=buffers,
                              mouse_support=True,
                              style=style,
                              use_alternate_screen=True,
                              key_bindings_registry=registry)

    eventloop = create_eventloop()

    try:
        cli = CommandLineInterface(application=application,
                                   eventloop=eventloop)
        cli.run()

    finally:
        eventloop.close()
Exemplo n.º 23
0
def select_choices_interactively(choices):
    # choices = [job['name'] for job in job_content]
    app = get_app(choices)

    eventloop = create_eventloop()
    try:
        cli = CommandLineInterface(application=app, eventloop=eventloop)
        selected_choice = cli.run(reset_current_buffer=False)
    finally:
        eventloop.close()

    return selected_choice
Exemplo n.º 24
0
    def create_cli(self):
        ## KeyBindings configuration
        key_binding = KeyBindingManager(enable_search=True,
                                        enable_abort_and_exit_bindings=True,
                                        enable_system_bindings=True,
                                        enable_auto_suggest_bindings=True,
                                        enable_open_in_editor=False)

        ## Buffer configuration
        default_buffer = Buffer(history=self.file_history,
                                auto_suggest=AutoSuggestFromHistory(),
                                enable_history_search=True,
                                completer=self.completer,
                                complete_while_typing=Always(),
                                accept_action=AcceptAction.RETURN_DOCUMENT)

        ## Style configuration
        try:
            style = get_style_by_name(self._config.highlighter_style)
        except ClassNotFound:
            style = get_style_by_name('native')

        styles = {}
        styles.update(style.styles)
        styles.update(default_style_extensions)
        styles.update({
            Token.Menu.Completions.Completion: 'bg:#003fff #ffffff',
            Token.Menu.Completions.Completion.Current: 'bg:#5ab300 #000000',
            Token.Menu.Completions.Meta.Current: 'bg:#5ab300 #ffffff',
            Token.Menu.Completions.Meta: 'bg:#ffffff #000000',
            Token.Scrollbar: 'bg:#003fff',
            Token.Scrollbar.Button: 'bg:#003333',
        })
        prompt_style = style_from_dict(styles)

        ## Application
        application = Application(
            layout=self.create_cli_layout(),
            mouse_support=False,
            style=prompt_style,
            buffer=default_buffer,
            on_abort=AbortAction.RETRY,
            on_exit=AbortAction.RAISE_EXCEPTION,
            on_input_timeout=self.on_input_timeout,
            key_bindings_registry=key_binding.registry,
        )

        cli = CommandLineInterface(application=application,
                                   eventloop=create_eventloop())
        return cli
Exemplo n.º 25
0
async def client_talk(loop, coro):
    usr = await prompt_async("username:"******"password:"******">"
    contacts = []
    history = InMemoryHistory()
    cli = CommandLineInterface(application=create_prompt_application(
        cin,
        history=history,
        completer=cmd_complete,
        get_bottom_toolbar_tokens=toolbar_tokens),
                               eventloop=loop)
    #     cli = create_prompt_application(
    #             cin,history=history,
    #             completer=cmd_complete,
    #             get_bottom_toolbar_tokens=toolbar_tokens,patch_stdout=True)

    sys.stdout = cli.stdout_proxy()
    client[0].send(Login(usr, pwd))
    cin = usr + ">"

    while True:
        try:
            msg = await cli.run_async()
            sys.stdout.flush()
            msg = msg.text
            try:
                if msg.startswith("/"):
                    msg = msg.split(sep="/")
                    if msg[1] == "bye": client[0].close_conn()

                    elif msg[1] == "contacts":
                        client[0].send(Request("contacts", usr))

                    elif msg[1] == "send":
                        client[0].send(Sender(msg[2], msg[3]))
                        print("{0:s} [{1:s}]: {2:s}\n".format(
                            tstamp(), usr, msg[3]))
                    else:
                        raise IndexError
            except IndexError:
                print("Not understood.")
                continue

        except (EOFError, KeyboardInterrupt):
            return