Ejemplo n.º 1
0
    def __init__(self, base_dir, config):
        for module in config.get('modules'):
            import_module(module)

        self.tasks = TaskManager(self)
        self.window = MainWindow(self)
        self.style = ToshStyle(config.get('ui', 'style'))
        self._parser = CommandLineParser(self, base_dir)
        self.config = config
        self.variables = {}

        application = Application(
            layout=self.window,
            buffer=Buffer(
                enable_history_search=True,
                complete_while_typing=False,
                is_multiline=False,
                history=FileHistory(base_dir + "/history"),
                # validator=validator,
                completer=CommandLineCompleter(self),
                auto_suggest=AutoSuggestFromHistory(),
                accept_action=AcceptAction(self.run_command),
            ),
            mouse_support=config.get('ui', 'mouse'),
            style=self.style,
            key_bindings_registry=get_key_bindings(self),
            use_alternate_screen=True)

        self._cli = CommandLineInterface(application=application,
                                         eventloop=create_asyncio_eventloop(),
                                         output=create_output(true_color=True))
Ejemplo n.º 2
0
    def _create_application(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 app.

        # Create CLI.
        application = Application(
            layout=self.editor_layout.layout,
            key_bindings_registry=self.key_bindings_manager.registry,
            buffers={
                COMMAND_BUFFER: command_buffer,
                SEARCH_BUFFER: search_buffer,
            },
            get_style=lambda: self.current_style,
            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,
            on_buffer_changed=Callback(self._current_buffer_changed))

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

        command_buffer.on_text_changed += preview

        return application
Ejemplo n.º 3
0
    def __init__(self,
                 vi_mode=False,
                 style=None,
                 search_text=None,
                 titlebar_tokens=None):
        assert isinstance(vi_mode, bool)
        assert style is None or isinstance(style, Style)

        self.sources = []
        self.current_source = 0  # Index in `self.sources`.
        self.vi_mode = vi_mode
        self.highlight_search = True
        self.in_colon_mode = False
        self.message = None
        self.displaying_help = False
        self.search_text = search_text
        self.display_titlebar = bool(titlebar_tokens)
        self.titlebar_tokens = titlebar_tokens or []

        # When this is True, always make sure that the cursor goes to the
        # bottom of the visible content. This is similar to 'tail -f'.
        self.forward_forever = False

        # Status information for all sources. Source -> _SourceInfo.
        # (Remember this info as long as the Source object exists.)
        self.source_info = weakref.WeakKeyDictionary()

        # Create prompt_toolkit stuff.
        self.buffers = BufferMapping({})

        def open_file(cli, buff):
            # Open file.
            self.open_file(buff.text)

            # Focus main buffer again.
            self.buffers.focus(cli, self.source_info[self.source].buffer_name)
            buff.reset()

        self.buffers['EXAMINE'] = Buffer(
            # Buffer for the 'Examine:' input.
            completer=PathCompleter(expanduser=True),
            accept_action=AcceptAction(open_file))

        self.layout = Layout(self)

        registry = create_key_bindings(self)
        self.application = Application(layout=self.layout.container,
                                       buffers=self.buffers,
                                       key_bindings_registry=registry,
                                       style=style or create_style(),
                                       mouse_support=True,
                                       on_render=self._on_render,
                                       use_alternate_screen=True,
                                       on_initialize=self._on_cli_initialize)

        self.cli = None
        self.eventloop = None
Ejemplo n.º 4
0
 def __init__(self, choices, default=None, validator=None):
     self._cursor = None  # not to be confused with Buffer's cursor_position
     self.init_choices(choices or [])
     self.default = default
     self.fresh = True
     self.validation_error = None
     self.validation_state = ValidationState.UNKNOWN
     super(ListBuffer,
           self).__init__(accept_action=AcceptAction(self.accept_handler),
                          validator=make_validator(validator))
Ejemplo n.º 5
0
    def __init__(self, pymux):
        self.pymux = pymux

        def _handle_command(cli, buffer):
            " When text is accepted in the command line. "
            text = buffer.text

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

            # Execute command.
            pymux.handle_command(cli, text)

        def _handle_prompt_command(cli, buffer):
            " When a command-prompt command is accepted. "
            text = buffer.text
            client_state = pymux.get_client_state(cli)
            prompt_command = client_state.prompt_command

            # Leave command mode and handle command.
            pymux.leave_command_mode(cli, append_to_history=True)
            pymux.handle_command(cli, prompt_command.replace('%%', text))

        super(_BufferMapping, self).__init__({
            COMMAND:
            Buffer(
                complete_while_typing=True,
                completer=create_command_completer(pymux),
                accept_action=AcceptAction(handler=_handle_command),
                auto_suggest=AutoSuggestFromHistory(),
            ),
            PROMPT:
            Buffer(
                accept_action=AcceptAction(handler=_handle_prompt_command),
                auto_suggest=AutoSuggestFromHistory(),
            ),
        })
Ejemplo n.º 6
0
    def _create_accept_action(self):
        """
        Create an AcceptAction for the input buffer that replaces shortcuts
        like 's' with the full command ('step') before returning it.
        """
        def handler(cli, buffer):
            # Get first part.
            parts = buffer.text.strip().split(None, 1)
            if len(parts) == 0:
                first, rest = '', ''
            elif len(parts) == 1:
                first, rest = parts[0], ''
            else:
                first, rest = parts

            # Replace text in buffer and return it.
            buffer.document = Document(
                shortcuts.get(first, first) + ' ' + rest)
            cli.set_return_value(buffer.document)

        return AcceptAction(handler)
Ejemplo n.º 7
0
def create_history_application(python_input, original_document):
    """
    Create an `Application` for the history screen.
    This has to be run as a sub application of `python_input`.

    When this application runs and returns, it retuns the selected lines.
    """
    history_mapping = HistoryMapping(python_input.history, original_document)

    def default_buffer_pos_changed(_):
        """ When the cursor changes in the default buffer. Synchronize with
        history buffer. """
        # Only when this buffer has the focus.
        if buffer_mapping.focus_stack[-1] == DEFAULT_BUFFER:
            try:
                line_no = default_buffer.document.cursor_position_row - \
                    history_mapping.result_line_offset

                if line_no < 0:  # When the cursor is above the inserted region.
                    raise IndexError

                history_lineno = sorted(
                    history_mapping.selected_lines)[line_no]
            except IndexError:
                pass
            else:
                history_buffer.cursor_position = \
                    history_buffer.document.translate_row_col_to_index(history_lineno, 0)

    def history_buffer_pos_changed(_):
        """ When the cursor changes in the history buffer. Synchronize. """
        # Only when this buffer has the focus.
        if buffer_mapping.focus_stack[-1] == HISTORY_BUFFER:
            line_no = history_buffer.document.cursor_position_row

            if line_no in history_mapping.selected_lines:
                default_lineno = sorted(history_mapping.selected_lines).index(line_no) + \
                    history_mapping.result_line_offset

                default_buffer.cursor_position = \
                    default_buffer.document.translate_row_col_to_index(default_lineno, 0)

    history_buffer = Buffer(
        initial_document=Document(history_mapping.concatenated_history),
        on_cursor_position_changed=history_buffer_pos_changed,
        accept_action=AcceptAction(
            lambda cli, buffer: cli.set_return_value(default_buffer.document)),
        read_only=True)

    default_buffer = Buffer(
        initial_document=history_mapping.get_new_document(),
        on_cursor_position_changed=default_buffer_pos_changed,
        read_only=True)

    help_buffer = Buffer(initial_document=Document(HELP_TEXT, 0),
                         accept_action=AcceptAction.IGNORE,
                         read_only=True)

    buffer_mapping = BufferMapping(
        {
            HISTORY_BUFFER: history_buffer,
            DEFAULT_BUFFER: default_buffer,
            HELP_BUFFER: help_buffer,
        },
        initial=HISTORY_BUFFER)

    application = Application(
        layout=create_layout(python_input, history_mapping),
        use_alternate_screen=True,
        buffers=buffer_mapping,
        style=python_input._current_style,
        mouse_support=Condition(lambda cli: python_input.enable_mouse_support),
        key_bindings_registry=create_key_bindings(python_input,
                                                  history_mapping))
    return application
Ejemplo n.º 8
0
    def __init__(self):
        self.command_parser = BrewPiCommandParser(self)

        self.buffers = {
            DEFAULT_BUFFER:
            Buffer(completer=command_completer,
                   enable_history_search=True,
                   history=InMemoryHistory(),
                   accept_action=AcceptAction(self.command_parser.parse)),
            'MESSAGES':
            Buffer(),
            'RESULT':
            Buffer(),
            'STATE':
            Buffer(),
        }

        self.registry = load_key_bindings()
        self.registry.add_binding(Keys.ControlC,
                                  eager=True)(self._on_request_shutdown)
        self.registry.add_binding(Keys.ControlQ,
                                  eager=True)(self._on_request_shutdown)

        self.layout = HSplit([
            # One window that holds the BufferControl with the default buffer on the
            # left.
            VSplit([
                HSplit([
                    Window(content=TokenListControl(get_tokens=lambda cli: [(
                        Token.Title, 'Command Result')]),
                           height=D.exact(1)),
                    Window(content=BufferControl(buffer_name='RESULT'),
                           wrap_lines=True,
                           left_margins=[ScrollbarMargin()]),
                ]),
                Window(width=D.exact(1),
                       content=FillControl('|', token=Token.Line)),
                HSplit([
                    Window(content=TokenListControl(get_tokens=lambda cli: [(
                        Token.Title, 'Raw Protocol Messages')]),
                           height=D.exact(1)),
                    Window(
                        content=BufferControl(buffer_name='MESSAGES',
                                              lexer=PygmentsLexer(JsonLexer)),
                        wrap_lines=True,
                        left_margins=[NumberredMargin()],
                        right_margins=[ScrollbarMargin()])
                ])
            ]),
            VSplit([
                Window(content=TokenListControl(
                    get_tokens=self.get_prompt_tokens),
                       height=D.exact(1),
                       dont_extend_width=True),
                Window(content=BufferControl(buffer_name=DEFAULT_BUFFER),
                       height=D.exact(1),
                       dont_extend_height=True),
            ]),
            Window(content=BufferControl(buffer_name='STATE'),
                   height=D.exact(1),
                   dont_extend_height=True)
        ])

        super().__init__(
            layout=self.layout,
            buffers=self.buffers,
            key_bindings_registry=self.registry,
            mouse_support=True,
            style=style_from_pygments(
                get_style_by_name('emacs'),
                style_dict={
                    Token.Toolbar:
                    '#ffffff bg:#333333',
                    Token.Title:
                    '#ffffff bg:#000088',
                    # User input.
                    Token:
                    '#ff0066',

                    # Prompt.
                    Token.Name:
                    '#884444 italic',
                    Token.At:
                    '#00aa00',
                    Token.Colon:
                    '#00aa00',
                    Token.Pound:
                    '#00aa00',
                    Token.Host:
                    '#000088 bg:#aaaaff',
                    Token.Path:
                    '#884444 underline',
                    # Make a selection reverse/underlined.
                    # (Use Control-Space to select.)
                    Token.SelectedText:
                    'reverse underline',
                }),
            use_alternate_screen=True)

        # BrewPi Stuff
        self.controller_manager = BrewPiControllerManager()
        self.msg_decoder = RawMessageDecoder()

        self.controller = None
Ejemplo n.º 9
0
    editing = True
    buffers[DEFAULT_BUFFER].reset()
    buffers[DEFAULT_BUFFER].text = ':'
    buffers[DEFAULT_BUFFER].cursor_position = 1


def accept(cli, doc):
    global editing
    editing = False
    buffers[DEFAULT_BUFFER].reset()
    buffers[DEFAULT_BUFFER].text = ''


buffers = {
    DEFAULT_BUFFER:
    Buffer(is_multiline=False, accept_action=AcceptAction(handler=accept)),
}

style = style_from_dict({Token.LineNumber: 'bg:#ansiblue'})

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


def run():
    eventloop = create_eventloop()
    try:
        cli = CommandLineInterface(application=application,