Exemplo n.º 1
0
 def apply_transformation(cli, doc, lineno, source_to_display, tokens):
     if not cli.context_was_set and not doc.text:
         cli.context_was_set = True
         cli.current_buffer.set_document(
             document.Document(cli.config.context))
     return pt_layout.Transformation(
         tokens, display_to_source=lambda i: len(cli.config.context))
Exemplo n.º 2
0
def set_content(app, name=DEFAULT_BUFFER, content=None, scroll_bottom=False):
    if content is None:
        return

    position = 0
    if scroll_bottom:
        position = len(content)
    app.buffers[name].set_document(document.Document(u"%s" % content,
                                                     position),
                                   bypass_readonly=True)
Exemplo n.º 3
0
    def _render_sdl(self, sdl: str) -> None:
        desc_doc = pt_document.Document(sdl)
        lexer = pt_lexers.PygmentsLexer(eql_pygments.EdgeQLLexer)
        formatter = lexer.lex_document(desc_doc)

        for line in range(desc_doc.line_count):
            pt_shortcuts.print_formatted_text(pt_formatted_text.FormattedText(
                formatter(line)),
                                              style=self.style)
        print()
Exemplo n.º 4
0
 def append_text(self, text_to_append: str) -> None:
   """Appends text_to_append to the text area."""
   new_text = self.text + text_to_append
   if not self.document.on_last_line:
     # Do not scroll down to latest log line if user is searching through logs.
     new_cursor_position = self.document.cursor_position
   else:
     new_cursor_position = len(new_text)
   self.document = document.Document(new_text, new_cursor_position)
   self.truncate_text()
Exemplo n.º 5
0
    def test_text_area_append_text(self, move_cursor: bool,
                                   row_after_batch_1: int,
                                   line_after_batch_1: str,
                                   row_after_batch_2: int,
                                   line_after_batch_2: str, max_size: int):
        """Tests appending text and the resulting cursor motion.

    Writes a batch of log lines, optionally moves the cursor to the first line,
    and writes another batch of log lines. Asserts that the line under the
    cursor matches the expectation after each batch.

    Args:
      move_cursor: Whether to move the cursor to the first line after writing
        the first batch of log lines.
      row_after_batch_1: Expected cursor row after the first batch of logs is
        written and (optionally) the cursor is moved.
      line_after_batch_1: Expected line under the cursor after the first batch.
      row_after_batch_2: Expected cursor row after the second batch of logs is
        written.
      line_after_batch_2: Expected line under the cursor after the second batch.
      max_size: Maximum number of lines the text area can contain.
    """
        with mock.patch.object(console, "_MAX_TEXT_AREA_LINES", new=max_size):
            textarea = console._AppendableTextArea(
                text="",
                focusable=True,
                read_only=True,
                line_numbers=True,
                scrollbar=True,
                width=80,  # Wide enough for log lines to fit without wrapping.
                height=
                _WINDOW_HEIGHT,  # Not tall enough to display all log lines.
            )
            line_template = "Line {}\n"

            for i in range(_BATCH_1_NUM_LINES):
                textarea.append_text(line_template.format(i))
            if move_cursor:
                textarea.document = document.Document(textarea.text, 0)
            self.assertEqual(textarea.document.cursor_position_row,
                             row_after_batch_1)
            self.assertEqual(textarea.document.current_line,
                             line_after_batch_1)

            for i in range(_BATCH_1_NUM_LINES, _TOTAL_NUM_LINES):
                textarea.append_text(line_template.format(i))
            self.assertEqual(textarea.document.cursor_position_row,
                             row_after_batch_2)
            self.assertEqual(textarea.document.current_line,
                             line_after_batch_2)

            if max_size < _TOTAL_NUM_LINES:  # Check that lines get truncated.
                for i in range(_TOTAL_NUM_LINES - max_size):
                    self.assertNotIn(line_template.format(i), textarea.text)
Exemplo n.º 6
0
    def _CreatePromptApplication(self):
        """Creates a shell prompt Application."""

        # Make sure that complete_while_typing is disabled when
        # enable_history_search is enabled. (First convert to SimpleFilter, to
        # avoid doing bitwise operations on bool objects.)
        complete_while_typing = shortcuts.to_simple_filter(True)
        enable_history_search = shortcuts.to_simple_filter(False)
        multiline = shortcuts.to_simple_filter(False)

        complete_while_typing &= ~enable_history_search

        return application.Application(
            layout=layout.CreatePromptLayout(
                message=self.prompt,
                lexer=None,
                is_password=False,
                reserve_space_for_menu=self.MENU_RESERVE_SPACE,
                multiline=filters.Condition(lambda cli: multiline()),
                get_prompt_tokens=None,
                get_continuation_tokens=None,
                get_bottom_toolbar_tokens=self._GetBottomToolbarTokens,
                display_completions_in_columns=False,
                extra_input_processors=None,
                wrap_lines=True,
                show_help=filters.Condition(
                    lambda _: self.key_bindings.help_key.toggle)),
            buffer=pt_buffer.Buffer(
                enable_history_search=enable_history_search,
                complete_while_typing=complete_while_typing,
                is_multiline=multiline,
                history=pt_history.InMemoryHistory(),
                validator=None,
                completer=shell_completer.ShellCliCompleter(),
                auto_suggest=None,
                accept_action=pt_buffer.AcceptAction.RETURN_DOCUMENT,
                initial_document=document.Document(''),
            ),
            style=shell_style.GetDocumentStyle(),
            clipboard=None,
            key_bindings_registry=self.key_bindings.MakeRegistry(),
            get_title=None,
            mouse_support=False,
            erase_when_done=False,
            on_abort=application.AbortAction.RAISE_EXCEPTION,
            on_exit=application.AbortAction.RAISE_EXCEPTION)
Exemplo n.º 7
0
def get_buffer_mapping(buffers=None, include_default=True, init_contents=None):
    bm = {}
    if include_default:
        init_doc = None
        if init_contents is not None:
            content = init_contents.get(DEFAULT_BUFFER, None)
            if content:
                init_doc = document.Document(content, 0)
        bm.update({
            DEFAULT_BUFFER:
            pt_buffer.Buffer(is_multiline=True, initial_document=init_doc)
        })
    if bm is not None:
        bm.update(
            dict([(b, pt_buffer.Buffer(is_multiline=True, read_only=True))
                  for b in buffers]))
    return buffer_mapping.BufferMapping(bm)
Exemplo n.º 8
0
    def get_completions(self, doc, event):
        """Yields the completions for doc.

    Args:
      doc: A Document instance containing the interactive command line to
           complete.
      event: The CompleteEvent that triggered this completion.

    Yields:
      Completion instances for doc.
    """
        args = self.parser.ParseCommand(doc.text_before_cursor)
        if not args:
            return
        self.empty = doc.text_before_cursor and doc.text_before_cursor[
            -1].isspace()
        self.event = event

        for completer in (
                self.CommandCompleter,
                self.FlagCompleter,
                self.PositionalCompleter,
                self.InteractiveCompleter,
        ):
            choices, offset = completer(args)
            if choices is not None:
                for choice in sorted(choices):
                    display = choice
                    if choice.endswith('/'):
                        choice = choice[:-1]
                    yield completion.Completion(choice,
                                                display=display,
                                                start_position=offset)
                return

        if event.completion_requested:
            # default to path completions
            choices = self.path_completer.get_completions(
                document.Document('' if self.empty else args[-1].value), event)
            if choices:
                for choice in choices:
                    yield choice
                return
Exemplo n.º 9
0
 def truncate_text(self) -> None:
   """Drops the least recent lines if text size exceeds the maximum limit."""
   if self.document.line_count > _MAX_TEXT_AREA_LINES:
     num_lines_to_drop = self.document.line_count - _MAX_TEXT_AREA_LINES
     new_text = "\n".join(self.document.lines[num_lines_to_drop:])
     cursor_offset = (
         sum(len(line) for line in self.document.lines[:num_lines_to_drop])
         + num_lines_to_drop)  # To account for newline characters.
     if self.document.cursor_position >= cursor_offset:
       new_cursor_position = self.document.cursor_position - cursor_offset
     else:
       # If dropping lines at the current cursor position, imitate cursor
       # motion from pressing "down" several times.
       num_down_presses = num_lines_to_drop - self.document.cursor_position_row
       new_cursor_position = (
           self.document.cursor_position
           + self.document.get_cursor_down_position(num_down_presses)
           - cursor_offset)
     self.document = document.Document(new_text, new_cursor_position)
Exemplo n.º 10
0
  def _add_text_to_window(self, text: str, window_id: int) -> None:
    """Adds text to the specified console window.

    If there's no console window with the given window_id, the text is dropped.

    Args:
      text: Text to add.
      window_id: ID of the window to add the text to.
    """
    if window_id not in self._window_id_to_text_area:
      logger.debug(f"There is no console window with ID {window_id}. "
                   f"Unable to display text: {text!r}.")
      return

    text_area = self._window_id_to_text_area[window_id]
    if isinstance(text_area, _AppendableTextArea):
      text_area.append_text(text)
    else:
      new_text = text_area.text + text
      text_area.document = document.Document(new_text, len(new_text))
Exemplo n.º 11
0
def CreatePromptApplication(
        message='',
        multiline=False,
        wrap_lines=True,
        is_password=False,
        complete_while_typing=True,
        enable_history_search=False,
        lexer=None,
        enable_system_bindings=False,
        enable_open_in_editor=False,
        validator=None,
        completer=None,
        reserve_space_for_menu=5,
        auto_suggest=None,
        style=None,
        history=None,
        clipboard=None,
        get_prompt_tokens=None,
        get_continuation_tokens=None,
        get_bottom_toolbar_tokens=None,
        display_completions_in_columns=False,
        get_title=None,
        mouse_support=False,
        extra_input_processors=None,
        key_bindings_registry=None,
        on_abort=application.AbortAction.RAISE_EXCEPTION,
        on_exit=application.AbortAction.RAISE_EXCEPTION,
        accept_action=pt_buffer.AcceptAction.RETURN_DOCUMENT,
        erase_when_done=False,
        default='',
        get_help_tokens=None):
    """Create the shell prompt Application."""
    if key_bindings_registry is None:
        key_bindings_registry = manager.KeyBindingManager.for_prompt(
            enable_system_bindings=enable_system_bindings,
            enable_open_in_editor=enable_open_in_editor).registry

    # Make sure that complete_while_typing is disabled when enable_history_search
    # is enabled. (First convert to SimpleFilter, to avoid doing bitwise
    # operations on bool objects.)
    complete_while_typing = shortcuts.to_simple_filter(complete_while_typing)
    enable_history_search = shortcuts.to_simple_filter(enable_history_search)
    multiline = shortcuts.to_simple_filter(multiline)

    complete_while_typing &= ~enable_history_search

    # Create application
    return application.Application(
        layout=layout.CreatePromptLayout(
            message=message,
            lexer=lexer,
            is_password=is_password,
            reserve_space_for_menu=(reserve_space_for_menu
                                    if completer is not None else 0),
            multiline=filters.Condition(lambda cli: multiline()),
            get_prompt_tokens=get_prompt_tokens,
            get_continuation_tokens=get_continuation_tokens,
            get_bottom_toolbar_tokens=get_bottom_toolbar_tokens,
            display_completions_in_columns=display_completions_in_columns,
            extra_input_processors=extra_input_processors,
            wrap_lines=wrap_lines,
            get_help_tokens=get_help_tokens,
            show_help=filters.Condition(lambda _: SHOW_HELP_WINDOW)),
        buffer=pt_buffer.Buffer(
            enable_history_search=enable_history_search,
            complete_while_typing=complete_while_typing,
            is_multiline=multiline,
            history=(history or pt_history.InMemoryHistory()),
            validator=validator,
            completer=completer,
            auto_suggest=auto_suggest,
            accept_action=accept_action,
            initial_document=document.Document(default),
        ),
        style=style,
        clipboard=clipboard,
        key_bindings_registry=key_bindings_registry,
        get_title=get_title,
        mouse_support=mouse_support,
        erase_when_done=erase_when_done,
        on_abort=on_abort,
        on_exit=on_exit)
Exemplo n.º 12
0
 def SetInput(self, lines):
     self._input = [document.Document(line) for line in lines]
Exemplo n.º 13
0
def move_cursor_to_end(buffer):
    doc = buffer.document
    buffer.set_document(
        document.Document(
            doc.text,
            doc.cursor_position + doc.get_end_of_document_position()))
Exemplo n.º 14
0
def move_cursor_to_line_start(buffer):
    doc = buffer.document
    buffer.set_document(
        document.Document(
            doc.text, doc.cursor_position + doc.get_start_of_line_position()))