コード例 #1
0
ファイル: layout.py プロジェクト: andythigpen/chromeconsole
 def __init__(self):
     super(CommandPrompt, self).__init__(
         BufferControl(
             buffer_name=COMMAND_BUFFER,
             input_processors=[BeforeInput.static(self.PROMPT)],
         ),
         height=D.exact(1)
     )
コード例 #2
0
ファイル: layout.py プロジェクト: AxEofBone7/pyvim
 def __init__(self):
     super(CommandLine, self).__init__(
         BufferControl(
             buffer_name=COMMAND_BUFFER,
             input_processors=[BeforeInput.static(':')],
             lexer=create_command_lexer()),
         height=LayoutDimension.exact(1),
         filter=HasFocus(COMMAND_BUFFER))
コード例 #3
0
    def __init__(self, prompt='Shell command: ', enable_global_bindings=True):
        self.prompt = prompt
        self.enable_global_bindings = to_filter(enable_global_bindings)

        self.system_buffer = Buffer(name=SYSTEM_BUFFER)

        self._bindings = self._build_key_bindings()

        self.buffer_control = BufferControl(
            buffer=self.system_buffer,
            lexer=SimpleLexer(style='class:system-toolbar.text'),
            input_processors=[
                BeforeInput(lambda: self.prompt, style='class:system-toolbar')
            ],
            key_bindings=self._bindings)

        self.window = Window(self.buffer_control,
                             height=1,
                             style='class:system-toolbar')

        self.container = ConditionalContainer(content=self.window,
                                              filter=has_focus(
                                                  self.system_buffer))
コード例 #4
0
ファイル: base.py プロジェクト: e7dal/python-prompt-toolkit
    def __init__(self,
                 text: str = '',
                 multiline: FilterOrBool = True,
                 password: FilterOrBool = False,
                 lexer: Optional[Lexer] = None,
                 auto_suggest: Optional[AutoSuggest] = None,
                 completer: Optional[Completer] = None,
                 complete_while_typing: FilterOrBool = True,
                 accept_handler: Optional[BufferAcceptHandler] = None,
                 history: Optional[History] = None,
                 focusable: FilterOrBool = True,
                 focus_on_click: FilterOrBool = False,
                 wrap_lines: FilterOrBool = True,
                 read_only: FilterOrBool = False,
                 width: AnyDimension = None,
                 height: AnyDimension = None,
                 dont_extend_height: FilterOrBool = False,
                 dont_extend_width: FilterOrBool = False,
                 line_numbers: bool = False,
                 get_line_prefix: Optional[GetLinePrefixCallable] = None,
                 scrollbar: bool = False,
                 style: str = '',
                 search_field: Optional[SearchToolbar] = None,
                 preview_search: FilterOrBool = True,
                 prompt: AnyFormattedText = '',
                 input_processors: Optional[List[Processor]] = None) -> None:

        if search_field is None:
            search_control = None
        elif isinstance(search_field, SearchToolbar):
            search_control = search_field.control

        if input_processors is None:
            input_processors = []

        # Writeable attributes.
        self.completer = completer
        self.complete_while_typing = complete_while_typing
        self.lexer = lexer
        self.auto_suggest = auto_suggest
        self.read_only = read_only
        self.wrap_lines = wrap_lines

        self.buffer = Buffer(
            document=Document(text, 0),
            multiline=multiline,
            read_only=Condition(lambda: is_true(self.read_only)),
            completer=DynamicCompleter(lambda: self.completer),
            complete_while_typing=Condition(
                lambda: is_true(self.complete_while_typing)),
            auto_suggest=DynamicAutoSuggest(lambda: self.auto_suggest),
            accept_handler=accept_handler,
            history=history)

        self.control = BufferControl(
            buffer=self.buffer,
            lexer=DynamicLexer(lambda: self.lexer),
            input_processors=[
                ConditionalProcessor(AppendAutoSuggestion(),
                                     has_focus(self.buffer) & ~is_done),
                ConditionalProcessor(processor=PasswordProcessor(),
                                     filter=to_filter(password)),
                BeforeInput(prompt, style='class:text-area.prompt'),
            ] + input_processors,
            search_buffer_control=search_control,
            preview_search=preview_search,
            focusable=focusable,
            focus_on_click=focus_on_click)

        if multiline:
            if scrollbar:
                right_margins = [ScrollbarMargin(display_arrows=True)]
            else:
                right_margins = []
            if line_numbers:
                left_margins = [NumberedMargin()]
            else:
                left_margins = []
        else:
            height = D.exact(1)
            left_margins = []
            right_margins = []

        style = 'class:text-area ' + style

        self.window = Window(
            height=height,
            width=width,
            dont_extend_height=dont_extend_height,
            dont_extend_width=dont_extend_width,
            content=self.control,
            style=style,
            wrap_lines=Condition(lambda: is_true(self.wrap_lines)),
            left_margins=left_margins,
            right_margins=right_margins,
            get_line_prefix=get_line_prefix)
コード例 #5
0
    def __init__(self,
                 text='',
                 multiline=True,
                 password=False,
                 lexer=None,
                 completer=None,
                 accept_handler=None,
                 focusable=True,
                 wrap_lines=True,
                 read_only=False,
                 width=None,
                 height=None,
                 dont_extend_height=False,
                 dont_extend_width=False,
                 line_numbers=False,
                 scrollbar=False,
                 style='',
                 input_processor=None,
                 search_field=None,
                 preview_search=True,
                 prompt=''):
        assert isinstance(text, six.text_type)
        assert search_field is None or isinstance(search_field, SearchToolbar)

        if search_field is None:
            search_control = None
        elif isinstance(search_field, SearchToolbar):
            search_control = search_field.control

        self.buffer = Buffer(
            document=Document(text, 0),
            multiline=multiline,
            read_only=read_only,
            completer=completer,
            complete_while_typing=True,
            accept_handler=lambda buff: accept_handler and accept_handler())

        self.control = BufferControl(
            buffer=self.buffer,
            lexer=lexer,
            input_processor=merge_processors([
                ConditionalProcessor(processor=PasswordProcessor(),
                                     filter=to_filter(password)),
                HighlightSearchProcessor(preview_search=preview_search),
                HighlightSelectionProcessor(),
                DisplayMultipleCursors(),
                BeforeInput(prompt, style='class:text-area.prompt'),
            ]),
            search_buffer_control=search_control,
            preview_search=preview_search,
            focusable=focusable)

        if multiline:
            if scrollbar:
                right_margins = [ScrollbarMargin(display_arrows=True)]
            else:
                right_margins = []
            if line_numbers:
                left_margins = [NumberedMargin()]
            else:
                left_margins = []
        else:
            wrap_lines = False  # Never wrap for single line input.
            height = D.exact(1)
            left_margins = []
            right_margins = []

        style = 'class:text-area ' + style

        self.window = Window(height=height,
                             width=width,
                             dont_extend_height=dont_extend_height,
                             dont_extend_width=dont_extend_width,
                             content=self.control,
                             style=style,
                             wrap_lines=wrap_lines,
                             left_margins=left_margins,
                             right_margins=right_margins)
コード例 #6
0
ファイル: app.py プロジェクト: wavefrontshaping/papis
    def __init__(self,
                 options: Sequence[Option],
                 default_index: int = 0,
                 header_filter: Callable[[Option], str] = str,
                 match_filter: Callable[[Option], str] = str):

        self.info_window = InfoWindow()
        self.help_window = HelpWindow()
        self.message_toolbar = MessageToolbar(style="class:message_toolbar")
        self.error_toolbar = MessageToolbar(style="class:error_toolbar")
        self.status_line = MessageToolbar(style="class:status_line")
        self.status_line_format = config.getstring('status_line_format',
                                                   section="tui")

        self.options_list = OptionsList(
            options,
            default_index,
            header_filter=header_filter,
            match_filter=match_filter,
            custom_filter=~has_focus(
                self.help_window))  # type: OptionsList[Option]
        self.options_list.search_buffer.on_text_changed += self.update

        commands, commands_kb = get_commands(self)
        self.command_line_prompt = CommandLinePrompt(commands=commands)
        kb = merge_key_bindings([create_keybindings(self), commands_kb])

        _root_container = HSplit([
            HSplit([
                Window(content=BufferControl(
                    input_processors=[BeforeInput('> ')],
                    buffer=self.options_list.search_buffer)),
                self.options_list,
                self.info_window,
            ]),
            self.help_window,
            self.error_toolbar,
            self.message_toolbar,
            self.status_line,
            self.command_line_prompt.window,
        ])

        help_text = ""  # type: str
        keys_info = get_keys_info()
        for k in keys_info:
            help_text += ("<ansired>{k[key]}</ansired>: {k[help]}\n".format(
                k=keys_info[k]))
        self.help_window.text = HTML(help_text)

        self.layout = Layout(_root_container)

        super(Picker, self).__init__(
            input=None,
            output=None,
            editing_mode=EditingMode.EMACS if config.get(
                'editmode', section='tui') == 'emacs' else EditingMode.VI,
            layout=self.layout,
            style=Style.from_dict({
                'options_list.selected_margin':
                config.get('options_list.selected_margin_style',
                           section='tui'),
                'options_list.unselected_margin':
                config.get('options_list.unselected_margin_style',
                           section='tui'),
                'error_toolbar':
                config.get('error_toolbar_style', section='tui'),
                'message_toolbar':
                config.get('message_toolbar_style', section='tui'),
                'status_line':
                config.get('status_line_style', section='tui'),
            }),
            key_bindings=kb,
            include_default_pygments_style=False,
            full_screen=True,
            enable_page_navigation_bindings=True)
        self.update()
コード例 #7
0
ファイル: layout.py プロジェクト: ABaldwinHunter/pymux-clone
    def _create_layout(self):
        """
        Generate the main prompt_toolkit layout.
        """
        waits_for_confirmation = WaitsForConfirmation(self.pymux)
        waits_for_prompt = WaitsForPrompt(self.pymux)
        in_command_mode = InCommandMode(self.pymux)

        return FloatContainer(
            content=HSplit([
                # The main window.
                HighlightBorders(self, self.pymux, FloatContainer(
                    Background(),
                    floats=[
                        Float(get_width=lambda cli: self.pymux.get_window_size(cli).columns,
                              get_height=lambda cli: self.pymux.get_window_size(cli).rows,
                              content=TraceBodyWritePosition(self.pymux, DynamicBody(self.pymux)))
                    ])),
                # Status bar.
                ConditionalContainer(
                    content=VSplit([
                        # Left.
                        Window(
                            height=D.exact(1),
                            get_width=(lambda cli: D(max=self.pymux.status_left_length)),
                            dont_extend_width=True,
                            content=TokenListControl(
                                self._get_status_left_tokens,
                                default_char=Char(' ', Token.StatusBar))),
                        # List of windows in the middle.
                        Window(
                            height=D.exact(1),
                            content=TokenListControl(
                                self._get_status_tokens,
                                align_right=Condition(self._status_align_right),
                                align_center=Condition(self._status_align_center),
                                default_char=Char(' ', Token.StatusBar))),
                        # Right.
                        Window(
                            height=D.exact(1),
                            get_width=(lambda cli: D(max=self.pymux.status_right_length)),
                            dont_extend_width=True,
                            content=TokenListControl(
                                self._get_status_right_tokens,
                                align_right=True,
                                default_char=Char(' ', Token.StatusBar)))
                    ]),
                    filter=Condition(lambda cli: self.pymux.enable_status),
                )
            ]),
            floats=[
                Float(bottom=1, left=0, content=MessageToolbar(self.pymux)),
                Float(left=0, right=0, bottom=0, content=HSplit([
                    # Wait for confirmation toolbar.
                    ConditionalContainer(
                        content=Window(
                            height=D.exact(1),
                            content=ConfirmationToolbar(self.pymux),
                        ),
                        filter=waits_for_confirmation,
                    ),
                    # ':' prompt toolbar.
                    ConditionalContainer(
                        content=Window(
                            height=D(min=1),  # Can be more if the command is multiline.
                            dont_extend_height=True,
                            content=BufferControl(
                                buffer_name=COMMAND,
                                default_char=Char(' ', Token.CommandLine),
                                lexer=SimpleLexer(Token.CommandLine),
                                preview_search=True,
                                highlighters=[SelectionHighlighter()],
                                input_processors=[
                                    AppendAutoSuggestion(),
                                    DefaultPrompt(lambda cli:[(Token.CommandLine.Prompt, ':')]),
                                ])
                        ),
                        filter=in_command_mode,
                    ),
                    # Other command-prompt commands toolbar.
                    ConditionalContainer(
                        content=Window(
                            height=D.exact(1),
                            content=BufferControl(
                                buffer_name=PROMPT,
                                default_char=Char(' ', Token.CommandLine),
                                lexer=SimpleLexer(Token.CommandLine),
                                highlighters=[SelectionHighlighter()],
                                input_processors=[
                                    BeforeInput(self._before_prompt_command_tokens),
                                    AppendAutoSuggestion(),
                                ])
                        ),
                        filter=waits_for_prompt,
                    ),
                ])),
                Float(xcursor=True, ycursor=True, content=CompletionsMenu(max_height=12)),
            ]
        )
コード例 #8
0
    def _create_application(self, editing_mode, erase_when_done):
        def dyncond(attr_name):
            """
            Dynamically take this setting from this 'Prompt' class.
            `attr_name` represents an attribute name of this class. Its value
            can either be a boolean or a `Filter`.

            This returns something that can be used as either a `Filter`
            or `Filter`.
            """
            @Condition
            def dynamic():
                value = getattr(self, attr_name)
                return to_filter(value)()

            return dynamic

        # Create functions that will dynamically split the prompt. (If we have
        # a multiline prompt.)
        has_before_fragments, get_prompt_text_1, get_prompt_text_2 = \
            _split_multiline_prompt(self._get_prompt)

        # Create buffers list.
        def accept(buff):
            """ Accept the content of the default buffer. This is called when
            the validation succeeds. """
            self.app.set_result(buff.document.text)

            # Reset content before running again.
            self.app.pre_run_callables.append(buff.reset)

        default_buffer = Buffer(
            name=DEFAULT_BUFFER,
            # Make sure that complete_while_typing is disabled when
            # enable_history_search is enabled. (First convert to Filter,
            # to avoid doing bitwise operations on bool objects.)
            complete_while_typing=Condition(
                lambda: _true(self.complete_while_typing) and not _true(
                    self.enable_history_search) and not self.complete_style ==
                CompleteStyle.READLINE_LIKE),
            validate_while_typing=dyncond('validate_while_typing'),
            enable_history_search=dyncond('enable_history_search'),
            validator=DynamicValidator(lambda: self.validator),
            completer=ThreadedCompleter(
                completer=DynamicCompleter(lambda: self.completer),
                in_thread=dyncond('complete_in_thread'),
            ),
            history=DynamicHistory(lambda: self.history),
            auto_suggest=DynamicAutoSuggest(lambda: self.auto_suggest),
            accept_handler=accept,
            get_tempfile_suffix=lambda: self.tempfile_suffix)

        search_buffer = Buffer(name=SEARCH_BUFFER)

        # Create processors list.
        input_processor = merge_processors([
            ConditionalProcessor(
                # By default, only highlight search when the search
                # input has the focus. (Note that this doesn't mean
                # there is no search: the Vi 'n' binding for instance
                # still allows to jump to the next match in
                # navigation mode.)
                HighlightSearchProcessor(preview_search=True),
                has_focus(search_buffer)),
            HighlightSelectionProcessor(),
            ConditionalProcessor(AppendAutoSuggestion(),
                                 has_focus(default_buffer) & ~is_done),
            ConditionalProcessor(PasswordProcessor(), dyncond('is_password')),
            DisplayMultipleCursors(),

            # Users can insert processors here.
            DynamicProcessor(lambda: self.extra_input_processor),

            # For single line mode, show the prompt before the input.
            ConditionalProcessor(
                merge_processors([
                    BeforeInput(get_prompt_text_2),
                    ShowArg(),
                ]), ~dyncond('multiline'))
        ])

        # Create bottom toolbars.
        bottom_toolbar = ConditionalContainer(
            Window(FormattedTextControl(lambda: self.bottom_toolbar,
                                        style='class:bottom-toolbar.text'),
                   style='class:bottom-toolbar',
                   dont_extend_height=True,
                   height=Dimension(min=1)),
            filter=~is_done & renderer_height_is_known
            & Condition(lambda: self.bottom_toolbar is not None))

        search_toolbar = SearchToolbar(
            search_buffer,
            get_search_state=lambda: default_buffer_control.get_search_state())
        search_buffer_control = BufferControl(buffer=search_buffer,
                                              input_processor=merge_processors(
                                                  [
                                                      ReverseSearchProcessor(),
                                                      ShowArg(),
                                                  ]))

        system_toolbar = SystemToolbar()

        def get_search_buffer_control():
            " Return the UIControl to be focused when searching start. "
            if _true(self.multiline):
                return search_toolbar.control
            else:
                return search_buffer_control

        default_buffer_control = BufferControl(
            buffer=default_buffer,
            get_search_buffer_control=get_search_buffer_control,
            input_processor=input_processor,
            lexer=DynamicLexer(lambda: self.lexer),
            preview_search=True)

        default_buffer_window = Window(
            default_buffer_control,
            height=self._get_default_buffer_control_height,
            left_margins=[
                # In multiline mode, use the window margin to display
                # the prompt and continuation fragments.
                ConditionalMargin(
                    PromptMargin(get_prompt_text_2, self._get_continuation),
                    filter=dyncond('multiline'),
                )
            ],
            wrap_lines=dyncond('wrap_lines'))

        @Condition
        def multi_column_complete_style():
            return self.complete_style == CompleteStyle.MULTI_COLUMN

        # Build the layout.
        layout = HSplit([
            # The main input, with completion menus floating on top of it.
            FloatContainer(
                HSplit([
                    ConditionalContainer(
                        Window(FormattedTextControl(get_prompt_text_1),
                               dont_extend_height=True),
                        Condition(has_before_fragments)),
                    ConditionalContainer(
                        default_buffer_window,
                        Condition(lambda: get_app().layout.current_control !=
                                  search_buffer_control),
                    ),
                    ConditionalContainer(
                        Window(search_buffer_control),
                        Condition(lambda: get_app().layout.current_control ==
                                  search_buffer_control),
                    ),
                ]),
                [
                    # Completion menus.
                    Float(xcursor=True,
                          ycursor=True,
                          content=CompletionsMenu(
                              max_height=16,
                              scroll_offset=1,
                              extra_filter=has_focus(default_buffer)
                              & ~multi_column_complete_style)),
                    Float(xcursor=True,
                          ycursor=True,
                          content=MultiColumnCompletionsMenu(
                              show_meta=True,
                              extra_filter=has_focus(default_buffer)
                              & multi_column_complete_style)),
                    # The right prompt.
                    Float(right=0,
                          top=0,
                          hide_when_covering_content=True,
                          content=_RPrompt(lambda: self.rprompt)),
                ]),
            ConditionalContainer(ValidationToolbar(), filter=~is_done),
            ConditionalContainer(system_toolbar,
                                 dyncond('enable_system_prompt') & ~is_done),

            # In multiline mode, we use two toolbars for 'arg' and 'search'.
            ConditionalContainer(
                Window(FormattedTextControl(self._get_arg_text), height=1),
                dyncond('multiline') & has_arg),
            ConditionalContainer(search_toolbar,
                                 dyncond('multiline') & ~is_done),
            bottom_toolbar,
        ])

        # Default key bindings.
        auto_suggest_bindings = load_auto_suggest_bindings()
        open_in_editor_bindings = load_open_in_editor_bindings()
        prompt_bindings = self._create_prompt_bindings()

        # Create application
        application = Application(
            layout=Layout(layout, default_buffer_window),
            style=DynamicStyle(lambda: self.style),
            include_default_pygments_style=dyncond(
                'include_default_pygments_style'),
            clipboard=DynamicClipboard(lambda: self.clipboard),
            key_bindings=merge_key_bindings([
                merge_key_bindings([
                    auto_suggest_bindings,
                    ConditionalKeyBindings(
                        open_in_editor_bindings,
                        dyncond('enable_open_in_editor')
                        & has_focus(DEFAULT_BUFFER)), prompt_bindings
                ]),
                ConditionalKeyBindings(
                    system_toolbar.get_global_key_bindings(),
                    dyncond('enable_system_prompt')),
                DynamicKeyBindings(lambda: self.extra_key_bindings),
            ]),
            mouse_support=dyncond('mouse_support'),
            editing_mode=editing_mode,
            erase_when_done=erase_when_done,
            reverse_vi_search_direction=True,

            # I/O.
            input=self.input,
            output=self.output)

        # During render time, make sure that we focus the right search control
        # (if we are searching). - This could be useful if people make the
        # 'multiline' property dynamic.
        '''
        def on_render(app):
            multiline = _true(self.multiline)
            current_control = app.layout.current_control

            if multiline:
                if current_control == search_buffer_control:
                    app.layout.current_control = search_toolbar.control
                    app.invalidate()
            else:
                if current_control == search_toolbar.control:
                    app.layout.current_control = search_buffer_control
                    app.invalidate()

        app.on_render += on_render
        '''

        return application, default_buffer, default_buffer_control
コード例 #9
0
    def _create_layout(self):
        """
        Generate the main prompt_toolkit layout.
        """
        waits_for_confirmation = WaitsForConfirmation(self.pymux)

        return FloatContainer(
            content=HSplit([
                # The main window.
                FloatContainer(
                    Background(),
                    floats=[
                        Float(
                            width=lambda: self.pymux.get_window_size().columns,
                            height=lambda: self.pymux.get_window_size().rows,
                            content=DynamicBody(self.pymux))
                    ]),
                # Status bar.
                ConditionalContainer(
                    content=VSplit(
                        [
                            # Left.
                            Window(height=1,
                                   width=(lambda: D(max=self.pymux.
                                                    status_left_length)),
                                   dont_extend_width=True,
                                   content=FormattedTextControl(
                                       self._get_status_left_tokens)),
                            # List of windows in the middle.
                            Window(height=1,
                                   char=' ',
                                   align=self._get_align,
                                   content=FormattedTextControl(
                                       self._get_status_tokens)),
                            # Right.
                            Window(height=1,
                                   width=(lambda: D(max=self.pymux.
                                                    status_right_length)),
                                   dont_extend_width=True,
                                   align=WindowAlign.RIGHT,
                                   content=FormattedTextControl(
                                       self._get_status_right_tokens))
                        ],
                        z_index=Z_INDEX.STATUS_BAR,
                        style='class:statusbar'),
                    filter=Condition(lambda: self.pymux.enable_status),
                )
            ]),
            floats=[
                Float(bottom=1,
                      left=0,
                      z_index=Z_INDEX.MESSAGE_TOOLBAR,
                      content=MessageToolbar(self.client_state)),
                Float(
                    left=0,
                    right=0,
                    bottom=0,
                    content=HSplit([
                        # Wait for confirmation toolbar.
                        ConditionalContainer(
                            content=Window(
                                height=1,
                                content=ConfirmationToolbar(
                                    self.pymux, self.client_state),
                                z_index=Z_INDEX.COMMAND_LINE,
                            ),
                            filter=waits_for_confirmation,
                        ),
                        # ':' prompt toolbar.
                        ConditionalContainer(
                            content=Window(
                                height=D(
                                    min=1
                                ),  # Can be more if the command is multiline.
                                style='class:commandline',
                                dont_extend_height=True,
                                content=BufferControl(
                                    buffer=self.client_state.command_buffer,
                                    preview_search=True,
                                    input_processors=[
                                        AppendAutoSuggestion(),
                                        BeforeInput(
                                            ':',
                                            style='class:commandline-prompt'),
                                        ShowArg(),
                                        HighlightSelectionProcessor(),
                                    ]),
                                z_index=Z_INDEX.COMMAND_LINE,
                            ),
                            filter=has_focus(self.client_state.command_buffer),
                        ),
                        # Other command-prompt commands toolbar.
                        ConditionalContainer(
                            content=Window(
                                height=1,
                                style='class:commandline',
                                content=BufferControl(
                                    buffer=self.client_state.prompt_buffer,
                                    input_processors=[
                                        BeforeInput(
                                            self._before_prompt_command_tokens
                                        ),
                                        AppendAutoSuggestion(),
                                        HighlightSelectionProcessor(),
                                    ]),
                                z_index=Z_INDEX.COMMAND_LINE,
                            ),
                            filter=has_focus(self.client_state.prompt_buffer),
                        ),
                    ])),
                # Keys pop-up.
                Float(
                    content=ConditionalContainer(
                        content=self.popup_dialog,
                        filter=Condition(
                            lambda: self.client_state.display_popup),
                    ),
                    left=3,
                    right=3,
                    top=5,
                    bottom=5,
                    z_index=Z_INDEX.POPUP,
                ),
                Float(xcursor=True,
                      ycursor=True,
                      content=CompletionsMenu(max_height=12)),
            ])
コード例 #10
0
ファイル: terminalModule.py プロジェクト: stephendade/PaGS
 def changePrompt(self, prompt: str):
     """
     Change the prompt (mode)
     """
     self.prompt = BeforeInput(prompt + ">")
コード例 #11
0
 def create_cmd_control(self, buffer, prompt='>>>> '):
     return BufferControl(buffer,
                          input_processors=[
                              BeforeInput(prompt,
                                          style='class:text-area.prompt')
                          ])
コード例 #12
0
ファイル: layout.py プロジェクト: mm4nn/pypager
    def __init__(self, pager):
        self.pager = pager
        self.dynamic_body = _DynamicBody(pager)

        # Build an interface.
        has_colon = HasColon(pager)

        self.container = FloatContainer(content=HSplit([
            Titlebar(pager),
            self.dynamic_body,
            SearchToolbar(vi_mode=True),
            SystemToolbar(),
            ConditionalContainer(content=VSplit([
                Window(height=D.exact(1),
                       content=TokenListControl(
                           self._get_statusbar_left_tokens,
                           default_char=Char(' ', Token.Statusbar))),
                Window(height=D.exact(1),
                       content=TokenListControl(
                           self._get_statusbar_right_tokens,
                           align_right=True,
                           default_char=Char(' ', Token.Statusbar))),
            ]),
                                 filter=~HasSearch() & ~HasFocus(SYSTEM_BUFFER)
                                 & ~has_colon & ~HasFocus('EXAMINE')),
            ConditionalContainer(content=TokenListToolbar(
                lambda cli: [(Token.Statusbar, ' :')],
                default_char=Char(token=Token.Statusbar)),
                                 filter=has_colon),
            ConditionalContainer(content=Window(BufferControl(
                buffer_name='EXAMINE',
                default_char=Char(token=Token.Toolbar.Examine),
                lexer=SimpleLexer(default_token=Token.Toolbar.Examine.Text),
                input_processors=[
                    BeforeInput(
                        lambda cli: [(Token.Toolbar.Examine, ' Examine: ')]),
                ]),
                                                height=D.exact(1)),
                                 filter=HasFocus('EXAMINE')),
            ConditionalContainer(content=Window(BufferControl(
                buffer_name='PATTERN_FILTER',
                default_char=Char(token=Token.Toolbar.Search),
                lexer=SimpleLexer(default_token=Token.Toolbar.Search.Text),
                input_processors=[
                    BeforeInput(lambda cli: [(Token.Toolbar.Search, '&/')]),
                ]),
                                                height=D.exact(1)),
                                 filter=HasFocus('PATTERN_FILTER')),
        ]),
                                        floats=[
                                            Float(right=0,
                                                  height=1,
                                                  bottom=1,
                                                  content=_Arg()),
                                            Float(bottom=1,
                                                  left=0,
                                                  right=0,
                                                  height=1,
                                                  content=MessageToolbarBar(
                                                      pager)),
                                            Float(
                                                right=0,
                                                height=1,
                                                bottom=1,
                                                content=ConditionalContainer(
                                                    content=TokenListToolbar(
                                                        lambda cli: [
                                                            (Token.Loading,
                                                             ' Loading... ')
                                                        ],
                                                        default_char=Char(
                                                            token=Token.
                                                            Statusbar)),
                                                    filter=Condition(
                                                        lambda cli: pager.
                                                        waiting_for_input_stream
                                                    ))),
                                            Float(
                                                xcursor=True,
                                                ycursor=True,
                                                content=
                                                MultiColumnCompletionsMenu()),
                                        ])
コード例 #13
0
    def __init__(
        self,
        message: InquirerPyMessage,
        choices: InquirerPyListChoices,
        default: InquirerPyDefault = "",
        pointer: str = INQUIRERPY_POINTER_SEQUENCE,
        style: InquirerPyStyle = None,
        vi_mode: bool = False,
        qmark: str = "?",
        amark: str = "?",
        transformer: Callable[[Any], Any] = None,
        filter: Callable[[Any], Any] = None,
        instruction: str = "",
        long_instruction: str = "",
        multiselect: bool = False,
        prompt: str = INQUIRERPY_POINTER_SEQUENCE,
        marker: str = INQUIRERPY_POINTER_SEQUENCE,
        marker_pl: str = " ",
        border: bool = False,
        info: bool = True,
        match_exact: bool = False,
        exact_symbol: str = " E",
        height: Union[str, int] = None,
        max_height: Union[str, int] = None,
        validate: InquirerPyValidate = None,
        invalid_message: str = "Invalid input",
        keybindings: InquirerPyKeybindings = None,
        cycle: bool = True,
        wrap_lines: bool = True,
        raise_keyboard_interrupt: bool = True,
        mandatory: bool = True,
        mandatory_message: str = "Mandatory prompt",
        session_result: InquirerPySessionResult = None,
    ) -> None:
        if not keybindings:
            keybindings = {}
        self._prompt = prompt
        self._info = info
        self._task = None
        self._rendered = False
        self._exact_symbol = exact_symbol

        keybindings = {
            "up": [{"key": "up"}, {"key": "c-p"}],
            "down": [{"key": "down"}, {"key": "c-n"}],
            "toggle": [],
            "toggle-exact": [],
            **keybindings,
        }
        super().__init__(
            message=message,
            style=style,
            border=border,
            vi_mode=vi_mode,
            qmark=qmark,
            amark=amark,
            transformer=transformer,
            filter=filter,
            validate=validate,
            invalid_message=invalid_message,
            multiselect=multiselect,
            instruction=instruction,
            long_instruction=long_instruction,
            keybindings=keybindings,
            cycle=cycle,
            wrap_lines=wrap_lines,
            raise_keyboard_interrupt=raise_keyboard_interrupt,
            mandatory=mandatory,
            mandatory_message=mandatory_message,
            session_result=session_result,
        )
        self.kb_func_lookup = {"toggle-exact": [{"func": self._toggle_exact}]}
        self._default = (
            default
            if not isinstance(default, Callable)
            else cast(Callable, default)(self._result)
        )
        self._height_offset += 1  # search input
        self._dimmension_height, self._dimmension_max_height = calculate_height(
            height, max_height, height_offset=self.height_offset
        )

        self._content_control: InquirerPyFuzzyControl = InquirerPyFuzzyControl(
            choices=choices,
            pointer=pointer,
            marker=marker,
            current_text=self._get_current_text,
            max_lines=self._dimmension_max_height,
            session_result=session_result,
            multiselect=multiselect,
            marker_pl=marker_pl,
            match_exact=match_exact,
        )

        self._buffer = Buffer(on_text_changed=self._on_text_changed)
        input_window = Window(
            height=LayoutDimension.exact(1),
            content=BufferControl(
                self._buffer,
                [
                    AfterInput(self._generate_after_input),
                    BeforeInput(self._generate_before_input),
                ],
                lexer=SimpleLexer("class:input"),
            ),
        )

        choice_height_dimmension = lambda: Dimension(
            max=self._dimmension_max_height,
            preferred=self._dimmension_height,
            min=self.content_control._height if self.content_control._height > 0 else 1,
        )
        self.choice_window = Window(
            content=self.content_control,
            height=choice_height_dimmension,
            dont_extend_height=True,
        )

        main_content_window = HSplit([input_window, self.choice_window])
        if self._border:
            main_content_window = Frame(main_content_window)
        self._layout = Layout(
            FloatContainer(
                content=HSplit(
                    [
                        MessageWindow(
                            message=self._get_prompt_message,
                            filter=True,
                            wrap_lines=self._wrap_lines,
                            show_cursor=True,
                        ),
                        ConditionalContainer(
                            main_content_window,
                            filter=~IsDone(),
                        ),
                        ConditionalContainer(
                            Window(content=DummyControl()),
                            filter=~IsDone() & self._is_displaying_long_instruction,
                        ),
                        InstructionWindow(
                            message=self._long_instruction,
                            filter=~IsDone() & self._is_displaying_long_instruction,
                            wrap_lines=self._wrap_lines,
                        ),
                    ],
                ),
                floats=[
                    ValidationFloat(
                        invalid_message=self._get_error_message,
                        filter=self._is_invalid & ~IsDone(),
                        wrap_lines=self._wrap_lines,
                        left=0,
                        bottom=self._validation_window_bottom_offset,
                    ),
                ],
            )
        )
        self._layout.focus(input_window)

        self._application = Application(
            layout=self._layout,
            style=self._style,
            key_bindings=self._kb,
            editing_mode=self._editing_mode,
            after_render=self._after_render,
        )
コード例 #14
0
    def __init__(self, multiline: FilterOrBool = True,
                 password: FilterOrBool = False,
                 focusable: FilterOrBool = True,
                 focus_on_click: FilterOrBool = False,
                 width: AnyDimension = None,
                 height: AnyDimension = None,
                 dont_extend_height: FilterOrBool = False,
                 dont_extend_width: FilterOrBool = False,
                 line_numbers: bool = False,
                 get_line_prefix: Optional[GetLinePrefixCallable] = None,
                 scrollbar: bool = False, style: str = "",
                 search_field: Optional[SearchToolbar] = None,
                 preview_search: FilterOrBool = True,
                 prompt: AnyFormattedText = "",
                 input_processors: Optional[List[Processor]] = None,
                 key_bindings: KeyBindings = None, **kwargs) -> None:

        super().__init__(multiline=multiline, password=password,
                         focusable=focusable, focus_on_click=focus_on_click,
                         width=width, height=height,
                         dont_extend_height=dont_extend_height,
                         dont_extend_width=dont_extend_width,
                         line_numbers=line_numbers,
                         get_line_prefix=get_line_prefix,
                         scrollbar=scrollbar, style=style,
                         search_field=search_field,
                         preview_search=preview_search, prompt=prompt,
                         input_processors=input_processors, **kwargs)

        if search_field is None:
            search_control = None
        elif isinstance(search_field, SearchToolbar):
            search_control = search_field.control

        if input_processors is None:
            input_processors = []

        self.control = BufferControl(
            buffer=self.buffer,
            lexer=DynamicLexer(lambda: self.lexer),
            input_processors=[
                                 ConditionalProcessor(
                                     AppendAutoSuggestion(),
                                     has_focus(self.buffer) & ~is_done
                                 ),
                                 ConditionalProcessor(
                                     processor=PasswordProcessor(),
                                     filter=to_filter(password)
                                 ),
                                 BeforeInput(prompt,
                                             style="class:text-area.prompt"),
                             ] + input_processors,
            search_buffer_control=search_control,
            preview_search=preview_search,
            focusable=focusable,
            focus_on_click=focus_on_click,
            key_bindings=key_bindings
        )

        if multiline:
            right_margins = [ScrollbarMargin(display_arrows=True)] \
                if scrollbar else []

            left_margins = [NumberedMargin()] if line_numbers else []

        else:
            height = D.exact(1)
            left_margins = []
            right_margins = []

        style = "class:text-area " + style

        self.window = Window(
            height=height,
            width=width,
            dont_extend_height=dont_extend_height,
            dont_extend_width=dont_extend_width,
            content=self.control,
            style=style,
            wrap_lines=Condition(lambda: is_true(self.wrap_lines)),
            left_margins=left_margins,
            right_margins=right_margins,
            get_line_prefix=get_line_prefix
        )
コード例 #15
0
    def __init__(self, text='', multiline=True, password=False,
                 lexer=None, auto_suggest=None, completer=None,
                 complete_while_typing=True, accept_handler=None, history=None,
                 focusable=True, focus_on_click=False, wrap_lines=True,
                 read_only=False, width=None, height=None,
                 dont_extend_height=False, dont_extend_width=False,
                 line_numbers=False, get_line_prefix=None, scrollbar=False,
                 style='', search_field=None, preview_search=True, prompt='',
                 input_processors=None, max_line_count=1000, initial_text="", align=WindowAlign.LEFT):
        assert isinstance(text, six.text_type)
        assert search_field is None or isinstance(search_field, SearchToolbar)

        if search_field is None:
            search_control = None
        elif isinstance(search_field, SearchToolbar):
            search_control = search_field.control

        if input_processors is None:
            input_processors = []

        # Writeable attributes.
        self.completer = completer
        self.complete_while_typing = complete_while_typing
        self.lexer = lexer
        self.auto_suggest = auto_suggest
        self.read_only = read_only
        self.wrap_lines = wrap_lines
        self.max_line_count = max_line_count

        self.buffer = CustomBuffer(
            document=Document(text, 0),
            multiline=multiline,
            read_only=Condition(lambda: is_true(self.read_only)),
            completer=DynamicCompleter(lambda: self.completer),
            complete_while_typing=Condition(
                lambda: is_true(self.complete_while_typing)),
            auto_suggest=DynamicAutoSuggest(lambda: self.auto_suggest),
            accept_handler=accept_handler,
            history=history)

        self.control = BufferControl(
            buffer=self.buffer,
            lexer=DynamicLexer(lambda: self.lexer),
            input_processors=[
                ConditionalProcessor(
                    AppendAutoSuggestion(),
                    has_focus(self.buffer) & ~is_done),
                ConditionalProcessor(
                    processor=PasswordProcessor(),
                    filter=to_filter(password)
                ),
                BeforeInput(prompt, style='class:text-area.prompt'),
            ] + input_processors,
            search_buffer_control=search_control,
            preview_search=preview_search,
            focusable=focusable,
            focus_on_click=focus_on_click)

        if multiline:
            if scrollbar:
                right_margins = [ScrollbarMargin(display_arrows=True)]
            else:
                right_margins = []
            if line_numbers:
                left_margins = [NumberedMargin()]
            else:
                left_margins = []
        else:
            left_margins = []
            right_margins = []

        style = 'class:text-area ' + style

        self.window = Window(
            height=height,
            width=width,
            dont_extend_height=dont_extend_height,
            dont_extend_width=dont_extend_width,
            content=self.control,
            style=style,
            wrap_lines=Condition(lambda: is_true(self.wrap_lines)),
            left_margins=left_margins,
            right_margins=right_margins,
            get_line_prefix=get_line_prefix,
            align=align)

        self.log_lines: Deque[str] = deque()
        self.log(initial_text)
コード例 #16
0
    def __init__(self, pager: "Pager") -> None:
        self.pager = pager
        self.dynamic_body = _DynamicBody(pager)

        # Build an interface.
        has_colon = HasColon(pager)

        self.examine_control: BufferControl = BufferControl(
            buffer=pager.examine_buffer,
            lexer=SimpleLexer(style="class:examine,examine-text"),
            input_processors=[
                BeforeInput(lambda: [("class:examine", " Examine: ")])
            ],
        )

        self.search_toolbar = SearchToolbar(vi_mode=True,
                                            search_buffer=pager.search_buffer)

        self.container = FloatContainer(
            content=HSplit([
                ConditionalContainer(
                    content=Titlebar(pager),
                    filter=Condition(lambda: pager.display_titlebar),
                ),
                self.dynamic_body,
                self.search_toolbar,
                SystemToolbar(),
                ConditionalContainer(
                    content=VSplit([
                        Window(
                            height=1,
                            content=FormattedTextControl(
                                self._get_statusbar_left_tokens),
                            style="class:statusbar",
                        ),
                        Window(
                            height=1,
                            content=FormattedTextControl(
                                self._get_statusbar_right_tokens),
                            style="class:statusbar.cursorposition",
                            align=WindowAlign.RIGHT,
                        ),
                    ]),
                    filter=~HasSearch()
                    & ~has_focus(SYSTEM_BUFFER)
                    & ~has_colon
                    & ~has_focus("EXAMINE"),
                ),
                ConditionalContainer(
                    content=Window(FormattedTextControl(" :"),
                                   height=1,
                                   style="class:examine"),
                    filter=has_colon,
                ),
                ConditionalContainer(
                    content=Window(self.examine_control,
                                   height=1,
                                   style="class:examine"),
                    filter=has_focus(pager.examine_buffer),
                ),
            ]),
            floats=[
                Float(right=0, height=1, bottom=1, content=_Arg()),
                Float(
                    bottom=1,
                    left=0,
                    right=0,
                    height=1,
                    content=ConditionalContainer(
                        content=MessageToolbarBar(pager),
                        filter=Condition(lambda: bool(pager.message)),
                    ),
                ),
                Float(
                    right=0,
                    height=1,
                    bottom=1,
                    content=ConditionalContainer(
                        content=FormattedTextToolbar(
                            lambda: [("class:loading", " Loading... ")], ),
                        filter=Condition(lambda: pager.current_source_info.
                                         waiting_for_input_stream),
                    ),
                ),
                Float(xcursor=True,
                      ycursor=True,
                      content=MultiColumnCompletionsMenu()),
            ],
        )
コード例 #17
0
ファイル: prompt.py プロジェクト: rokn/python-prompt-toolkit
    def _create_layout(self):
        """
        Create `Layout` for this prompt.
        """
        dyncond = self._dyncond

        # Create functions that will dynamically split the prompt. (If we have
        # a multiline prompt.)
        has_before_fragments, get_prompt_text_1, get_prompt_text_2 = \
            _split_multiline_prompt(self._get_prompt)

        default_buffer = self.default_buffer
        search_buffer = self.search_buffer

        # Create processors list.
        all_input_processors = [
            HighlightIncrementalSearchProcessor(),
            HighlightSelectionProcessor(),
            ConditionalProcessor(AppendAutoSuggestion(),
                                 has_focus(default_buffer) & ~is_done),
            ConditionalProcessor(PasswordProcessor(), dyncond('is_password')),
            DisplayMultipleCursors(),

            # Users can insert processors here.
            DynamicProcessor(
                lambda: merge_processors(self.input_processors or [])),

            # For single line mode, show the prompt before the input.
            ConditionalProcessor(
                merge_processors([
                    BeforeInput(get_prompt_text_2),
                    ShowArg(),
                ]), ~dyncond('multiline'))
        ]

        # Create bottom toolbars.
        bottom_toolbar = ConditionalContainer(
            Window(FormattedTextControl(lambda: self.bottom_toolbar,
                                        style='class:bottom-toolbar.text'),
                   style='class:bottom-toolbar',
                   dont_extend_height=True,
                   height=Dimension(min=1)),
            filter=~is_done & renderer_height_is_known
            & Condition(lambda: self.bottom_toolbar is not None))

        search_toolbar = SearchToolbar(
            search_buffer, ignore_case=dyncond('search_ignore_case'))

        search_buffer_control = SearchBufferControl(
            buffer=search_buffer,
            input_processors=[
                ReverseSearchProcessor(),
                ShowArg(),
            ],
            ignore_case=dyncond('search_ignore_case'))

        system_toolbar = SystemToolbar(
            enable_global_bindings=dyncond('enable_system_prompt'))

        def get_search_buffer_control():
            " Return the UIControl to be focused when searching start. "
            if _true(self.multiline):
                return search_toolbar.control
            else:
                return search_buffer_control

        default_buffer_control = BufferControl(
            buffer=default_buffer,
            search_buffer_control=get_search_buffer_control,
            input_processors=all_input_processors,
            include_default_input_processors=False,
            lexer=DynamicLexer(lambda: self.lexer),
            preview_search=True)

        default_buffer_window = Window(
            default_buffer_control,
            height=self._get_default_buffer_control_height,
            left_margins=[
                # In multiline mode, use the window margin to display
                # the prompt and continuation fragments.
                ConditionalMargin(
                    PromptMargin(get_prompt_text_2, self._get_continuation),
                    filter=dyncond('multiline'),
                )
            ],
            wrap_lines=dyncond('wrap_lines'))

        @Condition
        def multi_column_complete_style():
            return self.complete_style == CompleteStyle.MULTI_COLUMN

        # Build the layout.
        layout = HSplit([
            # The main input, with completion menus floating on top of it.
            FloatContainer(
                HSplit([
                    ConditionalContainer(
                        Window(FormattedTextControl(get_prompt_text_1),
                               dont_extend_height=True),
                        Condition(has_before_fragments)),
                    ConditionalContainer(
                        default_buffer_window,
                        Condition(lambda: get_app().layout.current_control !=
                                  search_buffer_control),
                    ),
                    ConditionalContainer(
                        Window(search_buffer_control),
                        Condition(lambda: get_app().layout.current_control ==
                                  search_buffer_control),
                    ),
                ]),
                [
                    # Completion menus.
                    Float(xcursor=True,
                          ycursor=True,
                          content=CompletionsMenu(
                              max_height=16,
                              scroll_offset=1,
                              extra_filter=has_focus(default_buffer)
                              & ~multi_column_complete_style)),
                    Float(xcursor=True,
                          ycursor=True,
                          content=MultiColumnCompletionsMenu(
                              show_meta=True,
                              extra_filter=has_focus(default_buffer)
                              & multi_column_complete_style)),
                    # The right prompt.
                    Float(right=0,
                          top=0,
                          hide_when_covering_content=True,
                          content=_RPrompt(lambda: self.rprompt)),
                ]),
            ConditionalContainer(ValidationToolbar(), filter=~is_done),
            ConditionalContainer(system_toolbar,
                                 dyncond('enable_system_prompt') & ~is_done),

            # In multiline mode, we use two toolbars for 'arg' and 'search'.
            ConditionalContainer(
                Window(FormattedTextControl(self._get_arg_text), height=1),
                dyncond('multiline') & has_arg),
            ConditionalContainer(search_toolbar,
                                 dyncond('multiline') & ~is_done),
            bottom_toolbar,
        ])

        return Layout(layout, default_buffer_window)
コード例 #18
0
    def __init__(self,
                 text='',
                 multiline=True,
                 password=False,
                 lexer=None,
                 completer=None,
                 accept_handler=None,
                 focusable=True,
                 wrap_lines=True,
                 read_only=False,
                 width=None,
                 height=None,
                 dont_extend_height=False,
                 dont_extend_width=False,
                 line_numbers=False,
                 scrollbar=False,
                 style='',
                 search_field=None,
                 preview_search=True,
                 history=InMemoryHistory(),
                 prompt=''):
        assert isinstance(text, six.text_type)
        assert search_field is None or isinstance(search_field, SearchToolbar)

        if search_field is None:
            search_control = None
        elif isinstance(search_field, SearchToolbar):
            search_control = search_field.control

        self.history = history

        self.buffer = Buffer(
            document=Document(text, 0),
            multiline=multiline,
            read_only=read_only,
            completer=completer,
            history=self.history,
            auto_suggest=AutoSuggestFromHistory(),
            enable_history_search=True,
            accept_handler=lambda buff: accept_handler and accept_handler())

        self.control = BufferControl(buffer=self.buffer,
                                     lexer=lexer,
                                     input_processors=[
                                         BeforeInput(
                                             prompt,
                                             style='class:text-area.prompt'),
                                     ],
                                     search_buffer_control=search_control,
                                     preview_search=preview_search,
                                     focusable=focusable)

        if multiline:
            if scrollbar:
                right_margins = [ScrollbarMargin(display_arrows=True)]
            else:
                right_margins = []
            if line_numbers:
                left_margins = [NumberedMargin()]
            else:
                left_margins = []
        else:
            wrap_lines = False  # Never wrap for single line input.
            height = D.exact(1)
            left_margins = []
            right_margins = []

        style = 'class:text-area ' + style

        self.window = Window(height=height,
                             width=width,
                             dont_extend_height=dont_extend_height,
                             dont_extend_width=dont_extend_width,
                             content=self.control,
                             style=style,
                             wrap_lines=wrap_lines,
                             left_margins=left_margins,
                             right_margins=right_margins)