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
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
Example #3
0
    def client_connected(self, telnet_connection):
        # When a client is connected, erase the screen from the client and say
        # Hello.
        telnet_connection.erase_screen()
        telnet_connection.send('Welcome!\n')

        # Set CommandLineInterface.
        animal_completer = WordCompleter(['alligator', 'ant'])
        telnet_connection.set_application(
            create_default_application(message='Say something: ',
                                       lexer=HtmlLexer,
                                       completer=animal_completer,
                                       on_abort=AbortAction.RETRY),
            self.handle_command)
Example #4
0
def main():
    hy_repl = HyREPL()
    eventloop = create_eventloop()
    validator = HyValidator()
    history = FileHistory(expanduser("~/.pthy_history"))

    def src_is_multiline():
        if app and app.buffer:
            text = app.buffer.document.text
            if '\n' in text:
                return True
        return False

    app = create_default_application(
        "λ: ",
        validator=validator,
        multiline=Condition(src_is_multiline),
        lexer=HyLexer,
        style=HyStyle,
        history=history,
        completer=HyCompleter(hy_repl),
        display_completions_in_columns=True,
        extra_input_processors=[
            ConditionalProcessor(processor=HighlightMatchingBracketProcessor(),
                                 filter=~IsDone())
        ])

    # Somewhat ugly trick to add a margin to the multiline input
    # without needing to define a custom layout
    app.layout.children[0].children[
        1].content.content.margin = ConditionalMargin(NumberredMargin(),
                                                      filter=IsMultiline())

    cli = CommandLineInterface(application=app, eventloop=eventloop)
    load_modified_bindings(app.key_bindings_registry)

    hy_repl.cli = cli

    try:
        while True:
            try:
                code_obj = cli.run()
                hy_repl.evaluate(code_obj.text)
            except KeyboardInterrupt:
                pass
    except EOFError:
        pass
    finally:
        eventloop.close()
Example #5
0
    def client_connected(self, telnet_connection):
        # When a client is connected, erase the screen from the client and say
        # Hello.
        telnet_connection.erase_screen()
        telnet_connection.send('Welcome!\n')

        # Set CommandLineInterface.
        animal_completer = WordCompleter(['alligator', 'ant'])
        telnet_connection.set_application(
            create_default_application(
                       message='Say something: ',
                       lexer=HtmlLexer,
                       completer=animal_completer,
                       on_abort=AbortAction.RETRY),
            self.handle_command)
Example #6
0
def main():
    hy_repl = HyREPL()
    eventloop = create_eventloop()
    validator = HyValidator()
    history = FileHistory(expanduser("~/.pthy_history"))

    def src_is_multiline():
        if app and app.buffer:
            text = app.buffer.document.text
            if '\n' in text:
                return True
        return False

    app = create_default_application("λ: ", validator=validator,
                                     multiline=Condition(src_is_multiline),
                                     lexer=HyLexer,
                                     style=HyStyle,
                                     history=history,
                                     completer=HyCompleter(hy_repl),
                                     display_completions_in_columns=True,
                                     extra_input_processors=[
                                         ConditionalProcessor(
                                             processor=HighlightMatchingBracketProcessor(),
                                             filter=~IsDone())
                                     ])

    # Somewhat ugly trick to add a margin to the multiline input
    # without needing to define a custom layout
    app.layout.children[0].children[1].content.content.margin = ConditionalMargin(
        NumberredMargin(),
        filter=IsMultiline())

    cli = CommandLineInterface(application=app, eventloop=eventloop)
    load_modified_bindings(app.key_bindings_registry)

    hy_repl.cli = cli

    try:
        while True:
            try:
                code_obj = cli.run()
                hy_repl.evaluate(code_obj.text)
            except KeyboardInterrupt:
                pass
    except EOFError:
        pass
    finally:
        eventloop.close()
Example #7
0
    def __init__(self, conn, addr, application, server, encoding):
        assert isinstance(addr, tuple)  # (addr, port) tuple
        assert isinstance(application, TelnetApplication)
        assert isinstance(server, TelnetServer)
        assert isinstance(encoding, text_type)  # e.g. 'utf-8'

        self.conn = conn
        self.addr = addr
        self.application = application
        self.closed = False
        self.handling_command = True
        self.server = server
        self.encoding = encoding
        self.callback = None  # Function that handles the CLI result.

        # Create "Output" object.
        self.size = Size(rows=40, columns=79)

        # Initialize.
        _initialize_telnet(conn)

        # Create output.
        def get_size():
            return self.size

        self.stdout = _ConnectionStdout(conn, encoding=encoding)
        self.vt100_output = Vt100_Output(self.stdout, get_size)

        # Create an eventloop (adaptor) for the CommandLineInterface.
        self.eventloop = _TelnetEventLoopInterface(server)

        # Set default CommandLineInterface.
        self.set_application(create_default_application())

        # Call client_connected
        application.client_connected(self)

        # Draw for the first time.
        self.handling_command = False
        self.cli._redraw()
Example #8
0
    def __init__(self, conn, addr, application, server, encoding):
        assert isinstance(addr, tuple)  # (addr, port) tuple
        assert isinstance(application, TelnetApplication)
        assert isinstance(server, TelnetServer)
        assert isinstance(encoding, text_type)  # e.g. 'utf-8'

        self.conn = conn
        self.addr = addr
        self.application = application
        self.closed = False
        self.handling_command = True
        self.server = server
        self.encoding = encoding
        self.callback = None  # Function that handles the CLI result.

        # Create "Output" object.
        self.size = Size(rows=40, columns=79)

        # Initialize.
        _initialize_telnet(conn)

        # Create output.
        def get_size():
            return self.size
        self.stdout = _ConnectionStdout(conn, encoding=encoding)
        self.vt100_output = Vt100_Output(self.stdout, get_size)

        # Create an eventloop (adaptor) for the CommandLineInterface.
        self.eventloop = _TelnetEventLoopInterface(server)

        # Set default CommandLineInterface.
        self.set_application(create_default_application())

        # Call client_connected
        application.client_connected(self)

        # Draw for the first time.
        self.handling_command = False
        self.cli._redraw()
Example #9
0
        def _process_input(self, reactor):
            self._print_startup_message()
            while self._ready.wait(0.5) != True:
                if not reactor.is_running():
                    return

            while True:
                expression = ""
                line = ""
                while len(expression) == 0 or line.endswith("\\"):
                    if not reactor.is_running():
                        return
                    try:
                        prompt = "[%s]" % self._prompt_string + "-> " if len(expression) == 0 else "... "

                        # We create the prompt manually instead of using get_input,
                        # so we can use the cli in the _on_stop method
                        eventloop = create_eventloop()

                        self._cli = CommandLineInterface(
                            application=create_default_application(prompt, history=self._history, completer=self._completer, lexer=JavascriptLexer),
                            eventloop=eventloop,
                            output=create_default_output())

                        try:
                            line = None

                            document = self._cli.run()

                            if document:
                                line = document.text
                        finally:
                            eventloop.close()
                    except EOFError:
                        # An extra newline after EOF to exit the REPL cleanly
                        print("\nThank you for using Frida!")
                        return
                    except KeyboardInterrupt:
                        line = ""
                        continue
                    if len(line.strip()) > 0:
                        if len(expression) > 0:
                            expression += "\n"
                        expression += line.rstrip("\\")

                if expression.endswith("?"):
                    try:
                        self._print_help(expression)
                    except Exception as ex:
                        error = ex.message
                        sys.stdout.write(Fore.RED + Style.BRIGHT + error['name'] + Style.RESET_ALL + ": " + error['message'] + "\n")
                        sys.stdout.flush()
                elif expression.startswith("%"):
                    self._do_magic(expression[1:].rstrip())
                elif expression in ("exit", "quit", "q"):
                    print("Thank you for using Frida!")
                    return
                elif expression == "help":
                    print("Help: #TODO :)")
                else:
                    try:
                        (t, value) = self._evaluate(expression)
                        if t in ('function', 'undefined', 'null'):
                            output = t
                        elif t == 'binary':
                            output = hexdump(value).rstrip("\n")
                        else:
                            output = json.dumps(value, sort_keys=True, indent=4, separators=(",", ": "))
                    except Exception as ex:
                        error = ex.message
                        output = Fore.RED + Style.BRIGHT + error['name'] + Style.RESET_ALL + ": " + error['message']
                    sys.stdout.write(output + "\n")
                    sys.stdout.flush()