Example #1
0
def main():
    layout = Layout(left_margin=LeftMarginWithLineNumbers(),
                    before_input=DefaultPrompt(text='Before input >> '),
                    after_input=Prompt(' << after input'),
                    top_toolbars=[
                        TextToolbar('This is a top toolbar',
                                    token=Token.TopToolbar1),
                        TextToolbar('This is another top toolbar',
                                    token=Token.TopToolbar2),
                    ],
                    bottom_toolbars=[
                        ArgToolbar(),
                        SearchToolbar(),
                        CompletionsToolbar(),
                        TextToolbar('This is a bottom toolbar',
                                    token=Token.BottomToolbar1),
                        TextToolbar('This is another bottom toolbar',
                                    token=Token.BottomToolbar2),
                    ],
                    show_tildes=True,
                    menus=[CompletionsMenu()])

    cli = CommandLineInterface(layout=layout,
                               style=TestStyle,
                               line=Line(is_multiline=True,
                                         completer=TestCompleter()))

    code_obj = cli.read_input(initial_value=lipsum)
    print('You said: ' + code_obj.text)
Example #2
0
def generate_layout(input_field: TextArea, output_field: TextArea,
                    log_field: TextArea):
    root_container = VSplit([
        FloatContainer(
            HSplit([
                output_field,
                Window(height=1, char='-', style='class:line'),
                input_field,
                TextArea(
                    height=1,
                    text=
                    f'Version: {version}    [Ctrl + C] QUIT    Hold down "fn" for selecting and copying text',
                    style='class:label'),
            ]),
            [
                # Completion menus.
                Float(xcursor=True,
                      ycursor=True,
                      transparent=True,
                      content=CompletionsMenu(max_height=16, scroll_offset=1)),
            ]),
        Window(width=1, char='|', style='class:line'),
        log_field,
    ])
    return Layout(root_container, focused_element=input_field)
Example #3
0
def generate_layout(input_field: TextArea, output_field: TextArea,
                    log_field: TextArea, search_field: SearchToolbar):
    root_container = HSplit([
        VSplit([
            Window(FormattedTextControl(get_version), style="class:title"),
            Window(FormattedTextControl(get_paper_trade_status),
                   style="class:title"),
            Window(FormattedTextControl(get_title_bar_right_text),
                   align=WindowAlign.RIGHT,
                   style="class:title"),
        ],
               height=1),
        VSplit([
            FloatContainer(
                HSplit([
                    output_field,
                    Window(height=1, char='-', style='class:primary'),
                    input_field,
                ]),
                [
                    # Completion menus.
                    Float(xcursor=True,
                          ycursor=True,
                          transparent=True,
                          content=CompletionsMenu(max_height=16,
                                                  scroll_offset=1)),
                ]),
            Window(width=1, char='|', style='class:primary'),
            HSplit([
                log_field,
                search_field,
            ]),
        ]),
    ])
    return Layout(root_container, focused_element=input_field)
Example #4
0
def create_tutorial_layout(lex):
    """ layout for example tutorial """
    lexer, _, _ = get_lexers(lex, None, None)
    layout_full = HSplit([
        FloatContainer(
            Window(BufferControl(input_processors=input_processors,
                                 lexer=lexer,
                                 preview_search=Always()),
                   get_height=get_height), [
                       Float(xcursor=True,
                             ycursor=True,
                             content=CompletionsMenu(
                                 max_height=MAX_COMPLETION,
                                 scroll_offset=1,
                                 extra_filter=(HasFocus(DEFAULT_BUFFER))))
                   ]),
        ConditionalContainer(HSplit([
            get_hline(),
            get_param(lexer),
            get_hline(),
            Window(content=BufferControl(buffer_name='example_line',
                                         lexer=lexer), ),
            Window(TokenListControl(get_tutorial_tokens,
                                    default_char=Char(' ', Token.Toolbar)),
                   height=D.exact(1)),
        ]),
                             filter=~IsDone() & RendererHeightIsKnown())
    ])
    return layout_full
Example #5
0
 def create_completion_float(self) -> Float:
     return Float(xcursor=True,
                  ycursor=True,
                  transparent=True,
                  attach_to_window=self.input_window,
                  content=CompletionsMenu(scroll_offset=1,
                                          max_height=16,
                                          extra_filter=has_focus(
                                              self.input_buffer)))
def create_default_layout(message='', lexer=None, is_password=False,
                          reserve_space_for_menu=False, get_bottom_toolbar_tokens=None):
    """
    Generate default layout.
    """
    assert get_bottom_toolbar_tokens is None or callable(get_bottom_toolbar_tokens)

    # Create processors list.
    input_processors = [HighlightSearchProcessor(), HighlightSelectionProcessor()]
    if is_password:
        input_processors.extend([PasswordProcessor(), DefaultPrompt(message)])
    else:
        input_processors.append(DefaultPrompt(message))

    # Create bottom toolbar.
    if get_bottom_toolbar_tokens:
        toolbars = [Window(TokenListControl(get_bottom_toolbar_tokens,
                                            default_char=Char(' ', Token.Toolbar)),
                           height=LayoutDimension.exact(1),
                           filter=~IsDone())]
    else:
        toolbars = []

    def get_height(cli):
        # If there is an autocompletion menu to be shown, make sure that our
        # layout has at least a minimal height in order to display it.
        if reserve_space_for_menu and not cli.is_done:
            return LayoutDimension(min=8)
        else:
            return LayoutDimension()

    # Create and return Layout instance.
    return HSplit([
        FloatContainer(
            Window(
                BufferControl(
                    input_processors=input_processors,
                    lexer=lexer,
                    # Enable preview_search, we want to have immediate feedback
                    # in reverse-i-search mode.
                    preview_search=Always()),
                get_height=get_height,
            ),
            [
                Float(xcursor=True,
                      ycursor=True,
                      content=CompletionsMenu(max_height=16,
                                              extra_filter=HasFocus(DEFAULT_BUFFER)))
            ]
        ),
        ValidationToolbar(),
        SystemToolbar(),
    ] + toolbars)
Example #7
0
def main():
    cli = CommandLineInterface(
        style=AnimalStyle,
        layout=Layout(before_input=DefaultPrompt('Give some animals: '),
                      menus=[CompletionsMenu()]),
        line=Line(completer=AnimalCompleter()),
        create_async_autocompleters=True,
    )

    print('Press tab to complete')
    code_obj = cli.read_input()
    print('You said: ' + code_obj.text)
Example #8
0
    def __init__(self, use_theme):
        self.statusbar = Window(height=1,
                                char='/',
                                style='class:line',
                                content=FormattedTextControl(text='druid////'),
                                align=WindowAlign.RIGHT)

        self.content = HSplit([
            Window(),
            self.statusbar,
            Window(height=1),
        ])
        self.container = FloatContainer(
            content=self.content,
            floats=[
                Float(
                    xcursor=True,
                    ycursor=True,
                    content=CompletionsMenu(max_height=16, scroll_offset=1),
                ),
            ],
        )
        self.key_bindings = KeyBindings()

        @self.key_bindings.add('c-c', eager=True)
        @self.key_bindings.add('c-q', eager=True)
        def quit_druid(event):
            event.app.exit()

        if use_theme:
            self.style = Style([
                ('capture-field', '#747369'),
                ('output-field', '#d3d0c8'),
                ('input-field', '#f2f0ec'),
                ('line', '#747369'),
                ('scrollbar.background', 'bg:#000000'),
                ('scrollbar.button', 'bg:#747369'),
            ])
        else:
            self.style = Style([])

        self.layout = Layout(self.container)

        self.app = Application(
            layout=self.layout,
            key_bindings=self.key_bindings,
            style=self.style,
            mouse_support=True,
            full_screen=True,
        )

        self.pages = dict()
        self.current_page = None
 def __build_root_container(body, do_save_file, do_share_file,
                            do_file_info, do_exit, do_cut, do_copy,
                            do_paste, do_delete, do_about, bindings) -> \
         MenuContainer:
     """
     Build a container that holds all components inside.
     :type body: HSplit
     :type do_save_file: function
     :type do_share_file: function
     :type do_file_info: function
     :type do_exit: function
     :type do_cut: function
     :type do_copy: function
     :type do_paste: function
     :type do_delete: function
     :type do_about: function
     :type bindings: KeyBindings
     :return: MenuContainer component
     """
     return MenuContainer(
         body=body,
         menu_items=[
             MenuItem(
                 "File",
                 children=[
                     MenuItem("Save", handler=do_save_file),
                     MenuItem("Share", handler=do_share_file),
                     MenuItem("Info", handler=do_file_info),
                     MenuItem("-", disabled=True),
                     MenuItem("Exit", handler=do_exit),
                 ],
             ),
             MenuItem(
                 "Edit",
                 children=[
                     MenuItem("Cut", handler=do_cut),
                     MenuItem("Copy", handler=do_copy),
                     MenuItem("Paste", handler=do_paste),
                     MenuItem("Delete", handler=do_delete)
                 ],
             ),
             MenuItem("Info",
                      children=[MenuItem("About", handler=do_about)]),
         ],
         floats=[
             Float(
                 xcursor=True,
                 ycursor=True,
                 content=CompletionsMenu(max_height=16, scroll_offset=1),
             ),
         ],
         key_bindings=bindings,
     )
Example #10
0
    def __init__(self, editor, manager, window_arrangement):
        self.editor = editor  # Back reference to editor.
        self.manager = manager
        self.window_arrangement = window_arrangement

        # Mapping from (`window_arrangement.Window`, `EditorBuffer`) to a frame
        # (Layout instance).
        # We keep this as a cache in order to easily reuse the same frames when
        # the layout is updated. (We don't want to create new frames on every
        # update call, because that way, we would loose some state, like the
        # vertical scroll offset.)
        self._frames = {}

        self._fc = FloatContainer(
            content=VSplit([
                Window(BufferControl())  # Dummy window
            ]),
            floats=[
                Float(xcursor=True, ycursor=True,
                      content=CompletionsMenu(max_height=12,
                                              scroll_offset=2,
                                              extra_filter=~HasFocus(COMMAND_BUFFER))),
                Float(content=BufferListOverlay(editor), bottom=1, left=0),
                Float(bottom=1, left=0, right=0, height=1,
                      content=CompletionsToolbar(
                          extra_filter=HasFocus(COMMAND_BUFFER) &
                                       ~bufferlist_overlay_visible_filter &
                                       Condition(lambda cli: editor.show_wildmenu))),
                Float(bottom=1, left=0, right=0, height=1,
                      content=ValidationToolbar()),
                Float(bottom=1, left=0, right=0, height=1,
                      content=MessageToolbarBar(editor)),
                Float(content=WelcomeMessageWindow(editor),
                      height=WELCOME_MESSAGE_HEIGHT,
                      width=WELCOME_MESSAGE_WIDTH),
            ]
        )

        self.layout = FloatContainer(
            content=HSplit([
                TabsToolbar(editor),
                self._fc,
                CommandLine(),
                ReportMessageToolbar(editor),
                SystemToolbar(),
                SearchToolbar(vi_mode=True),
            ]),
            floats=[
                Float(right=0, height=1, bottom=0, width=5,
                      content=SimpleArgToolbar()),
            ]
        )
Example #11
0
    def create_layout(self, exam_lex, toolbar_lex):
        """ creates the layout """
        lexer, exam_lex, toolbar_lex = get_lexers(self.shell_ctx.lexer,
                                                  exam_lex, toolbar_lex)

        if not any(
                isinstance(processor, DefaultPrompt)
                for processor in self.input_processors):
            self.input_processors.append(DefaultPrompt(self.get_prompt_tokens))

        layout_lower = ConditionalContainer(HSplit([
            get_anyhline(self.shell_ctx.config),
            get_descriptions(self.shell_ctx.config, exam_lex, lexer),
            get_examplehline(self.shell_ctx.config),
            get_example(self.shell_ctx.config, exam_lex),
            ConditionalContainer(get_hline(),
                                 filter=self.show_default | self.show_symbol),
            ConditionalContainer(Window(content=BufferControl(
                buffer_name='default_values', lexer=lexer)),
                                 filter=self.show_default),
            ConditionalContainer(get_hline(),
                                 filter=self.show_default & self.show_symbol),
            ConditionalContainer(Window(
                content=BufferControl(buffer_name='symbols', lexer=exam_lex)),
                                 filter=self.show_symbol),
            ConditionalContainer(Window(
                content=BufferControl(buffer_name='progress', lexer=lexer)),
                                 filter=self.show_progress),
            Window(content=BufferControl(buffer_name='bottom_toolbar',
                                         lexer=toolbar_lex), ),
        ]),
                                            filter=~IsDone()
                                            & RendererHeightIsKnown())

        layout_full = HSplit([
            FloatContainer(
                Window(
                    BufferControl(input_processors=self.input_processors,
                                  lexer=lexer,
                                  preview_search=Always()),
                    get_height=get_height,
                ), [
                    Float(xcursor=True,
                          ycursor=True,
                          content=CompletionsMenu(
                              max_height=MAX_COMPLETION,
                              scroll_offset=1,
                              extra_filter=(HasFocus(DEFAULT_BUFFER))))
                ]), layout_lower
        ])

        return layout_full
Example #12
0
def create_default_layout(message='', lexer=None, is_password=False,
                          reserve_space_for_menu=False, get_bottom_toolbar_tokens=None):
    """
    Generate default layout.
    """
    assert get_bottom_toolbar_tokens is None or callable(get_bottom_toolbar_tokens)

    # Create processors list.
    if is_password:
        input_processors = [PasswordProcessor(), DefaultPrompt(message)]
    else:
        input_processors = [DefaultPrompt(message)]

    # Create bottom toolbar.
    if get_bottom_toolbar_tokens:
        toolbars = [Window(TokenListControl(get_bottom_toolbar_tokens,
                                            default_char=Char(' ', Token.Toolbar)),
                           height=LayoutDimension.exact(1),
                           filter=~IsDone())]
    else:
        toolbars = []

    def get_height(cli):
        # If there is an autocompletion menu to be shown, make sure that our
        # layout has at least a minimal height in order to display it.
        if reserve_space_for_menu and not cli.is_done:
            return LayoutDimension(min=8)
        else:
            return LayoutDimension()

    # Create and return Layout instance.
    return HSplit([
        FloatContainer(
            Window(
                BufferControl(
                    input_processors=input_processors,
                    lexer=lexer),
                get_height=get_height,
            ),
            [
                Float(xcursor=True,
                      ycursor=True,
                      content=CompletionsMenu(max_height=16,
                                              extra_filter=HasFocus('default')))
            ]
        ),
        ValidationToolbar(),
        SystemToolbar(),
    ] + toolbars)
Example #13
0
def generate_layout(
    input_field: TextArea,
    output_field: TextArea,
    log_field: TextArea,
    search_log_field: SearchToolbar,
    search_out_field: SearchToolbar,
    timer: TextArea,
    process_monitor: TextArea,
    # trade_monitor: TextArea):
):
    root_container = HSplit([
        # VSplit([
        #     Window(FormattedTextControl(get_version), style="class:title"),
        #     # Window(FormattedTextControl(get_paper_trade_status), style="class:title"),
        #     # Window(FormattedTextControl(get_active_strategy), style="class:title"),
        #     # Window(FormattedTextControl(get_active_markets), style="class:title"),
        #     # Window(FormattedTextControl(get_script_file), style="class:title"),
        #     # Window(FormattedTextControl(get_strategy_file), style="class:title"),
        # ], height=1),
        VSplit([
            FloatContainer(
                HSplit([
                    output_field,
                    Window(height=1, char='-', style='class:primary'),
                    Window(FormattedTextControl(get_partial_args),
                           style="class:title"),
                    Window(height=1, char='-', style='class:primary'),
                    input_field,
                ]),
                [
                    # Completion menus.
                    Float(xcursor=True,
                          ycursor=True,
                          transparent=True,
                          content=CompletionsMenu(max_height=16,
                                                  scroll_offset=1)),
                ]),
            Window(width=1, char='|', style='class:primary'),
            HSplit([log_field, search_log_field, search_out_field]),
        ]),
        VSplit(
            [
                # trade_monitor,
                process_monitor,
                timer,
            ],
            height=1),
    ])
    return Layout(root_container, focused_element=input_field)
Example #14
0
def main(database):
    connection = sqlite3.connect(database)
    layout = Layout(before_input=DefaultPrompt('> '),
                    lexer=SqlLexer,
                    menus=[CompletionsMenu()])
    line = Line(completer=SqlCompleter())
    cli = CommandLineInterface(style=DocumentStyle, layout=layout, line=line)
    try:
        while True:
            document = cli.read_input(on_exit=AbortAction.RAISE_EXCEPTION)
            with connection:
                messages = connection.execute(document.text)
                for message in messages:
                    print message
    except Exit:
        print 'GoodBye!'
Example #15
0
def create_layout(lex, exam_lex, toolbar_lex):
    """ creates the layout """
    config = azclishell.configuration.CONFIGURATION
    lexer, exam_lex, toolbar_lex = get_lexers(lex, exam_lex, toolbar_lex)

    input_processors.append(DefaultPrompt(get_prompt_tokens))

    layout_lower = ConditionalContainer(HSplit([
        get_anyhline(config),
        get_descriptions(config, exam_lex, lexer),
        get_examplehline(config),
        get_example(config, exam_lex),
        ConditionalContainer(get_hline(), filter=ShowDefault() | ShowSymbol()),
        ConditionalContainer(Window(
            content=BufferControl(buffer_name='default_values', lexer=lexer)),
                             filter=ShowDefault()),
        ConditionalContainer(get_hline(), filter=ShowDefault() & ShowSymbol()),
        ConditionalContainer(Window(
            content=BufferControl(buffer_name='symbols', lexer=exam_lex)),
                             filter=ShowSymbol()),
        ConditionalContainer(
            Window(content=BufferControl(buffer_name='progress', lexer=lexer)),
            filter=ShowProgress()),
        Window(content=BufferControl(buffer_name='bottom_toolbar',
                                     lexer=toolbar_lex), ),
    ]),
                                        filter=~IsDone()
                                        & RendererHeightIsKnown())

    layout_full = HSplit([
        FloatContainer(
            Window(
                BufferControl(input_processors=input_processors,
                              lexer=lexer,
                              preview_search=Always()),
                get_height=get_height,
            ), [
                Float(xcursor=True,
                      ycursor=True,
                      content=CompletionsMenu(
                          max_height=MAX_COMPLETION,
                          scroll_offset=1,
                          extra_filter=(HasFocus(DEFAULT_BUFFER))))
            ]), layout_lower
    ])

    return layout_full
    def _create_windows(self):
        """Create all the windows of the display (input, output, debugger,
        text completer)"""
        module_names = [m.name for m in self.model.modules]
        search_field = SearchToolbar()
        # Generate the input text area
        input_field = TextArea(prompt='> ',
                               style='class:arrow',
                               completer=ModuleCompleter(module_names),
                               search_field=search_field,
                               height=1,
                               multiline=False,
                               wrap_lines=True)

        # Field to show current time
        end_time = str(self.model.get_end_time())
        time_field = TextArea(text="",
                              style='class:rprompt',
                              height=1,
                              width=len(end_time) * 2 + 7,
                              multiline=False)

        output = Label(text="")
        self.display.update()

        # Create container with display window and input text area
        container = pt_containers.HSplit([
            self.display.get_top_view(),
            pt_containers.Window(height=1, char='-'), output,
            pt_containers.VSplit([input_field, time_field]), search_field
        ])

        # Floating menu for text completion
        completion_menu = CompletionsMenu(max_height=5, scroll_offset=1)
        body = pt_containers.FloatContainer(content=container,
                                            floats=[
                                                pt_containers.Float(
                                                    xcursor=True,
                                                    ycursor=True,
                                                    content=completion_menu)
                                            ])

        return body, input_field, time_field, output
Example #17
0
def generate_layout(input_field: TextArea, output_field: TextArea,
                    log_field: TextArea, log_toggle: Button,
                    search_field: SearchToolbar, timer: TextArea,
                    process_monitor: TextArea, trade_monitor: TextArea):
    components = {}
    components["item_top_version"] = Window(FormattedTextControl(get_version),
                                            style="class:header")
    components["item_top_paper"] = Window(
        FormattedTextControl(get_paper_trade_status), style="class:header")
    components["item_top_active"] = Window(
        FormattedTextControl(get_active_strategy), style="class:header")
    # Window(FormattedTextControl(get_active_markets), style="class:header"),
    # Window(FormattedTextControl(get_script_file), style="class:header"),
    components["item_top_file"] = Window(
        FormattedTextControl(get_strategy_file), style="class:header")
    components["item_top_toggle"] = log_toggle
    components["pane_top"] = VSplit([
        components["item_top_version"], components["item_top_paper"],
        components["item_top_active"], components["item_top_file"],
        components["item_top_toggle"]
    ],
                                    height=1)
    components["pane_bottom"] = VSplit([trade_monitor, process_monitor, timer],
                                       height=1)
    components["pane_left"] = HSplit([output_field, input_field])
    components["pane_right"] = HSplit([log_field, search_field])
    components["hint_menus"] = [
        Float(xcursor=True,
              ycursor=True,
              transparent=True,
              content=CompletionsMenu(max_height=16, scroll_offset=1))
    ]

    root_container = HSplit([
        components["pane_top"],
        VSplit([
            FloatContainer(components["pane_left"], components["hint_menus"]),
            components["pane_right"],
        ]),
        components["pane_bottom"],
    ])
    return Layout(root_container, focused_element=input_field), components
Example #18
0
    def create(self):

        sort_by = SortOrder.sort_by
        order = SortOrder.order

        self.body = titled_body.create(sort_by=sort_by, order=order)

        self.container = HSplit([self.body])

        completions = Float(xcursor=True,
                            ycursor=True,
                            content=CompletionsMenu(max_height=16,
                                                    scroll_offset=1))

        self.float_container = FloatContainer(content=self.container,
                                              floats=[completions])

        self.floats = self.float_container.floats

        return self.float_container
Example #19
0
def cli(database, user, password, host, port):

    from pgcli import __file__ as package_root
    package_root = os.path.dirname(package_root)

    default_config = os.path.join(package_root, 'pgclirc')
    # Write default config.
    write_default_config(default_config, '~/.pgclirc')

    # Load config.
    config = load_config('~/.pgclirc')

    # Connect to the database.
    try:
        pgexecute = PGExecute(database, user, password, host, port)
    except Exception as e:
        click.secho(e.message, err=True, fg='red')
        exit(1)
    layout = Layout(before_input=DefaultPrompt('%s> ' % database),
            menus=[CompletionsMenu()],
            lexer=SqlLexer)
    completer = PGCompleter(config.getboolean('main', 'smart_completion'))
    completer.extend_special_commands(pgexecute.special_commands.keys())
    completer.extend_table_names(pgexecute.tables())
    completer.extend_column_names(pgexecute.all_columns())
    line = Line(completer=completer,
            history=FileHistory(os.path.expanduser('~/.pgcli-history')))
    cli = CommandLineInterface(style=PGStyle, layout=layout, line=line)

    try:
        while True:
            document = cli.read_input(on_exit=AbortAction.RAISE_EXCEPTION)
            try:
                rows, headers, status = pgexecute.run(document.text)
                if rows:
                    print(tabulate(rows, headers, tablefmt='psql'))
                print(status)
            except Exception as e:
                click.secho(e.message, err=True, fg='red')
    except Exit:
        print ('GoodBye!')
Example #20
0
    def run_cli(self):
        pgexecute = self.pgexecute
        prompt = '%s> ' % pgexecute.dbname
        logger = self.logger
        original_less_opts = self.adjust_less_opts()

        completer = self.completer
        self.refresh_completions()
        key_binding_manager = pgcli_bindings(self.vi_mode)
        print('Version:', __version__)
        print('Chat: https://gitter.im/amjith/pgcli')
        print('Mail: https://groups.google.com/forum/#!forum/pgcli')
        print('Home: http://pgcli.com')

        layout = Layout(before_input=DefaultPrompt(prompt),
                        menus=[CompletionsMenu(max_height=10)],
                        lexer=PostgresLexer,
                        bottom_toolbars=[PGToolbar(key_binding_manager)])
        buf = PGBuffer(always_multiline=self.multi_line,
                       completer=completer,
                       history=FileHistory(
                           os.path.expanduser('~/.pgcli-history')))
        cli = CommandLineInterface(
            style=style_factory(self.syntax_style),
            layout=layout,
            buffer=buf,
            key_bindings_registry=key_binding_manager.registry)

        try:
            while True:
                cli.layout.before_input = DefaultPrompt(prompt)
                document = cli.read_input(on_exit=AbortAction.RAISE_EXCEPTION)

                # The reason we check here instead of inside the pgexecute is
                # because we want to raise the Exit exception which will be
                # caught by the try/except block that wraps the pgexecute.run()
                # statement.
                if quit_command(document.text):
                    raise Exit

                # Keep track of whether or not the query is mutating. In case
                # of a multi-statement query, the overall query is considered
                # mutating if any one of the component statements is mutating
                mutating = False

                try:
                    logger.debug('sql: %r', document.text)
                    successful = False
                    # Initialized to [] because res might never get initialized
                    # if an exception occurs in pgexecute.run(). Which causes
                    # finally clause to fail.
                    res = []
                    start = time()
                    # Run the query.
                    res = pgexecute.run(document.text)
                    duration = time() - start
                    successful = True
                    output = []
                    total = 0
                    for title, cur, headers, status in res:
                        logger.debug("headers: %r", headers)
                        logger.debug("rows: %r", cur)
                        logger.debug("status: %r", status)
                        start = time()
                        threshold = 1000
                        if (is_select(status) and cur
                                and cur.rowcount > threshold):
                            click.secho(
                                'The result set has more than %s rows.' %
                                threshold,
                                fg='red')
                            if not click.confirm('Do you want to continue?'):
                                click.secho("Aborted!", err=True, fg='red')
                                break
                        output.extend(
                            format_output(title, cur, headers, status,
                                          self.table_format))
                        end = time()
                        total += end - start
                        mutating = mutating or is_mutating(status)

                except KeyboardInterrupt:
                    # Restart connection to the database
                    pgexecute.connect()
                    logger.debug("cancelled query, sql: %r", document.text)
                    click.secho("cancelled query", err=True, fg='red')
                except Exception as e:
                    logger.error("sql: %r, error: %r", document.text, e)
                    logger.error("traceback: %r", traceback.format_exc())
                    click.secho(str(e), err=True, fg='red')
                else:
                    click.echo_via_pager('\n'.join(output))
                    if pgspecial.TIMING_ENABLED:
                        print('Command Time:', duration)
                        print('Format Time:', total)
                finally:
                    for cur, _, _ in res:
                        if hasattr(cur, 'close'):
                            cur.close()

                # Refresh the table names and column names if necessary.
                if need_completion_refresh(document.text):
                    prompt = '%s> ' % pgexecute.dbname
                    self.refresh_completions()

                # Refresh search_path to set default schema.
                if need_search_path_refresh(document.text):
                    logger.debug('Refreshing search path')
                    completer.set_search_path(pgexecute.search_path())
                    logger.debug('Search path: %r', completer.search_path)

                query = Query(document.text, successful, mutating)
                self.query_history.append(query)

        except Exit:
            print('Goodbye!')
        finally:  # Reset the less opts back to original.
            logger.debug('Restoring env var LESS to %r.', original_less_opts)
            os.environ['LESS'] = original_less_opts
Example #21
0
def create_layout(buffers,
                  settings,
                  key_bindings_manager,
                  python_prompt_control=None,
                  lexer=PythonLexer,
                  extra_sidebars=None,
                  extra_buffer_processors=None):
    D = LayoutDimension
    show_all_buffers = Condition(lambda cli: settings.show_all_buffers)
    extra_sidebars = extra_sidebars or []
    extra_buffer_processors = extra_buffer_processors or []

    def create_buffer_window(buffer_name):
        def menu_position(cli):
            """
            When there is no autocompletion menu to be shown, and we have a signature,
            set the pop-up position at `bracket_start`.
            """
            b = cli.buffers[buffer_name]

            if b.complete_state is None and b.signatures:
                row, col = b.signatures[0].bracket_start
                index = b.document.translate_row_col_to_index(row - 1, col)
                return index

        return Window(
            BufferControl(
                buffer_name=buffer_name,
                lexer=lexer,
                show_line_numbers=ShowLineNumbersFilter(settings, buffer_name),
                input_processors=[BracketsMismatchProcessor()] +
                extra_buffer_processors,
                menu_position=menu_position,
            ),
            # As long as we're editing, prefer a minimal height of 8.
            get_height=(lambda cli: (None if cli.is_done else D(min=6))),

            # When done, show only if this was focussed.
            filter=(~IsDone() & show_all_buffers)
            | PythonBufferFocussed(buffer_name, settings))

    def create_buffer_window_separator(buffer_name):
        return Window(width=D.exact(1),
                      content=FillControl('\u2502', token=Token.Separator),
                      filter=~IsDone() & show_all_buffers)

    buffer_windows = []
    for b in sorted(buffers):
        if b.startswith('python-'):
            buffer_windows.append(create_buffer_window_separator(b))
            buffer_windows.append(create_buffer_window(b))

    return HSplit([
        VSplit([
            HSplit([
                TabsToolbar(settings),
                FloatContainer(content=HSplit([
                    VSplit([
                        Window(
                            python_prompt_control,
                            dont_extend_width=True,
                        ),
                        VSplit(buffer_windows),
                    ]),
                ]),
                               floats=[
                                   Float(xcursor=True,
                                         ycursor=True,
                                         content=CompletionsMenu(
                                             max_height=12,
                                             extra_filter=ShowCompletionsMenu(
                                                 settings))),
                                   Float(xcursor=True,
                                         ycursor=True,
                                         content=SignatureToolbar(settings))
                               ]),
                ArgToolbar(),
                SearchToolbar(),
                SystemToolbar(),
                ValidationToolbar(),
                CompletionsToolbar(
                    extra_filter=ShowCompletionsToolbar(settings)),

                # Docstring region.
                Window(height=D.exact(1),
                       content=FillControl('\u2500', token=Token.Separator),
                       filter=HasSignature(settings) & ShowDocstring(settings)
                       & ~IsDone()),
                Window(
                    BufferControl(
                        buffer_name='docstring',
                        default_token=Token.Docstring,
                        #lexer=PythonLexer,
                    ),
                    filter=HasSignature(settings) & ShowDocstring(settings)
                    & ~IsDone(),
                    height=D(max=12),
                ),
            ]),
        ] + extra_sidebars + [
            PythonSidebar(settings, key_bindings_manager),
        ]),
        VSplit([
            PythonToolbar(key_bindings_manager, settings),
            ShowSidebarButtonInfo(),
        ])
    ])
Example #22
0
    def __init__(self,
                 ctui=None,
                 input_field=None,
                 output_field=None,
                 statusbar=None,
                 root_container=None):
        self.ctui = ctui

        self._completer = CommandCompleter(ctui.commands)

        self._history = FileHistory("{}/.{}_history".format(
            Path.home(), self.ctui.name))

        self._input_field = TextArea(height=1,
                                     prompt=self.ctui.prompt,
                                     style='class:input_field',
                                     completer=self.completer,
                                     history=self.history)

        self._header_field = Window(height=1, char='-', style='class:line')

        self._output_field = TextArea(text='',
                                      style='class:output_field',
                                      wrap_lines=self.ctui.wrap_lines,
                                      scrollbar=True)

        self._statusbar = Window(content=FormattedTextControl(
            self.statusbar_text),
                                 height=1,
                                 style='class:statusbar')

        self._body = FloatContainer(HSplit([
            self.input_field, self.header_field, self.output_field,
            self.statusbar
        ]),
                                    floats=[
                                        Float(xcursor=True,
                                              ycursor=True,
                                              content=CompletionsMenu(
                                                  max_height=16,
                                                  scroll_offset=1))
                                    ])

        self._root_container = MenuContainer(
            body=self.body,
            menu_items=[
                MenuItem(
                    'Session ',
                    children=[
                        MenuItem('Connect'),
                        MenuItem('Disconnect'),
                        #         MenuItem('Save'),
                        #         MenuItem('Save as...'),
                        #         MenuItem('-', disabled=True),
                        MenuItem('Exit'),
                    ]),
                MenuItem('Edit ',
                         children=[
                             MenuItem('Copy'),
                             MenuItem('Paste'),
                         ]),
                MenuItem('Help ',
                         children=[
                             MenuItem('Help', handler=show_help),
                             MenuItem('About'),
                         ]),
            ],
            floats=[
                Float(xcursor=True,
                      ycursor=True,
                      content=CompletionsMenu(max_height=16, scroll_offset=1)),
            ])
Example #23
0
def generate_layout(input_field: TextArea,
                    output_field: TextArea,
                    log_field: TextArea,
                    right_pane_toggle: Button,
                    log_field_button: Button,
                    search_field: SearchToolbar,
                    timer: TextArea,
                    process_monitor: TextArea,
                    trade_monitor: TextArea,
                    command_tabs: Dict[str, CommandTab],
                    ):
    components = {}

    components["item_top_version"] = Window(FormattedTextControl(get_version), style="class:header")
    components["item_top_active"] = Window(FormattedTextControl(get_active_strategy), style="class:header")
    components["item_top_file"] = Window(FormattedTextControl(get_strategy_file), style="class:header")
    components["item_top_gateway"] = Window(FormattedTextControl(get_gateway_status), style="class:header")
    components["item_top_toggle"] = right_pane_toggle
    components["pane_top"] = VSplit([components["item_top_version"],
                                     components["item_top_active"],
                                     components["item_top_file"],
                                     components["item_top_gateway"],
                                     components["item_top_toggle"]], height=1)
    components["pane_bottom"] = VSplit([trade_monitor,
                                        process_monitor,
                                        timer], height=1)
    output_pane = Box(body=output_field, padding=0, padding_left=2, style="class:output-field")
    input_pane = Box(body=input_field, padding=0, padding_left=2, padding_top=1, style="class:input-field")
    components["pane_left"] = HSplit([output_pane, input_pane], width=Dimension(weight=1))
    if all(not t.is_selected for t in command_tabs.values()):
        log_field_button.window.style = "class:tab_button.focused"
    else:
        log_field_button.window.style = "class:tab_button"
    tab_buttons = [log_field_button]
    for tab in sorted(command_tabs.values(), key=lambda x: x.tab_index):
        if tab.button is not None:
            if tab.is_selected:
                tab.button.window.style = "class:tab_button.focused"
            else:
                tab.button.window.style = "class:tab_button"
            tab.close_button.window.style = tab.button.window.style
            tab_buttons.append(VSplit([tab.button, tab.close_button]))
    pane_right_field = log_field
    focused_right_field = [tab.output_field for tab in command_tabs.values() if tab.is_selected]
    if focused_right_field:
        pane_right_field = focused_right_field[0]
    components["pane_right_top"] = VSplit(tab_buttons, height=1, style="class:log-field", padding_char=" ", padding=2)
    components["pane_right"] = ConditionalContainer(
        Box(body=HSplit([components["pane_right_top"], pane_right_field, search_field], width=Dimension(weight=1)),
            padding=0, padding_left=2, style="class:log-field"),
        filter=True
    )
    components["hint_menus"] = [Float(xcursor=True,
                                      ycursor=True,
                                      transparent=True,
                                      content=CompletionsMenu(max_height=16,
                                                              scroll_offset=1))]

    root_container = HSplit([
        components["pane_top"],
        VSplit(
            [FloatContainer(components["pane_left"], components["hint_menus"]),
             components["pane_right"]]),
        components["pane_bottom"],
    ])
    return Layout(root_container, focused_element=input_field), components
Example #24
0
],
                                 ignore_case=True)

# The layout
buff = Buffer(completer=animal_completer, complete_while_typing=True)

body = FloatContainer(content=HSplit([
    Window(FormattedTextControl('Press "q" to quit.'),
           height=1,
           style='reverse'),
    Window(BufferControl(buffer=buff)),
]),
                      floats=[
                          Float(xcursor=True,
                                ycursor=True,
                                content=CompletionsMenu(max_height=16,
                                                        scroll_offset=1))
                      ])

# Key bindings
kb = KeyBindings()


@kb.add('q')
@kb.add('c-c')
def _(event):
    " Quit application. "
    event.app.exit()


# The `Application`
application = Application(layout=Layout(body),
Example #25
0
def start_app(args):
    """Text-based GUI application"""
    cmd = Commands()
    completer = WordCompleter(cmd.commands(),
                              meta_dict=cmd.meta_dict(),
                              ignore_case=True)
    history = InMemoryHistory()

    # Individual windows
    input_field = TextArea(height=1,
                           prompt='ctserial> ',
                           style='class:input-field',
                           completer=completer,
                           history=history)

    output_field = TextArea(scrollbar=True,
                            style='class:output-field',
                            text='')

    statusbar = Window(content=FormattedTextControl(get_statusbar_text),
                       height=1,
                       style='class:statusbar')

    # Organization of windows
    body = FloatContainer(HSplit([
        input_field,
        Window(height=1, char='-', style='class:line'), output_field, statusbar
    ]),
                          floats=[
                              Float(xcursor=True,
                                    ycursor=True,
                                    content=CompletionsMenu(max_height=16,
                                                            scroll_offset=1))
                          ])

    # Adding menus
    root_container = MenuContainer(
        body=body,
        menu_items=[],
        # menu_items=[
        #     MenuItem('Project ', children=[
        #         MenuItem('New'),
        #         MenuItem('Open'),
        #         MenuItem('Save'),
        #         MenuItem('Save as...'),
        #         MenuItem('-', disabled=True),
        #         MenuItem('Exit'),  ]),
        #     MenuItem('View ', children=[
        #         MenuItem('Split'),  ]),
        #     MenuItem('Info ', children=[
        #         MenuItem('Help'),
        #         MenuItem('About'),  ]),  ],
        floats=[
            Float(xcursor=True,
                  ycursor=True,
                  content=CompletionsMenu(max_height=16, scroll_offset=1)),
        ])

    # The key bindings.
    kb = KeyBindings()

    @kb.add('space')
    def _(event):
        input_text = input_field.text
        cursor = len(input_text)
        input_updated = input_text[:cursor] + ' ' + input_text[cursor + 1:]
        cursor += 1
        input_field.buffer.document = Document(text=input_updated,
                                               cursor_position=cursor)
        input_field.buffer.completer = WordCompleter([], ignore_case=True)

    @kb.add('enter', filter=has_focus(input_field))
    def _(event):
        # Process commands on prompt after hitting enter key
        # tx_bytes = parse_command(input_field.text, event=event)
        input_field.buffer.completer = WordCompleter(cmd.commands(),
                                                     meta_dict=cmd.meta_dict(),
                                                     ignore_case=True)
        if len(input_field.text) == 0:
            return
        output_text = cmd.execute(input_field.text, output_field.text, event)
        input_field.buffer.reset(append_to_history=True)

        # For commands that do not send data to serial device
        if output_text == None:
            input_field.text = ''
            return
        # For invalid commands forcing users to correct them
        elif output_text == False:
            return
        # For invalid commands forcing users to correct them
        else:
            output_field.buffer.document = Document(
                text=output_text, cursor_position=len(output_text))
            input_field.text = ''

    @kb.add('c-c')
    def _(event):
        """Pressing Control-C will copy highlighted text to clipboard"""
        data = output_field.buffer.copy_selection()
        get_app().clipboard.set_data(data)

    @kb.add('c-p')
    def _(event):
        """Pressing Control-P will paste text from clipboard"""
        input_field.buffer.paste_clipboard_data(get_app().clipboard.get_data())

    @kb.add('c-q')
    def _(event):
        " Pressing Ctrl-Q will exit the user interface. "
        cmd.do_exit(input_field.text, output_field.text, event)

    @kb.add('c-d')
    def _(event):
        """Press Ctrl-D to start the python debugger"""
        import pdb
        pdb.set_trace()

    style = Style([
        # ('output-field', 'bg:#000000 #ffffff'),
        # ('input-field', 'bg:#000000 #ffffff'),
        ('line', '#004400'),
        ('statusbar', 'bg:#AAAAAA')
    ])

    # Run application.
    application = MyApplication(layout=Layout(root_container,
                                              focused_element=input_field),
                                key_bindings=kb,
                                style=style,
                                mouse_support=True,
                                full_screen=True)
    application.run()
Example #26
0
    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)),
            ]
        )
Example #27
0
def create_layout(python_input,
                  lexer=PythonLexer,
                  extra_body=None,
                  extra_toolbars=None,
                  extra_buffer_processors=None,
                  input_buffer_height=None):
    D = Dimension
    extra_body = [extra_body] if extra_body else []
    extra_toolbars = extra_toolbars or []
    extra_buffer_processors = extra_buffer_processors or []
    input_buffer_height = input_buffer_height or D(min=6)

    search_toolbar = SearchToolbar(python_input.search_buffer)

    def create_python_input_window():
        def menu_position():
            """
            When there is no autocompletion menu to be shown, and we have a signature,
            set the pop-up position at `bracket_start`.
            """
            b = python_input.default_buffer

            if b.complete_state is None and python_input.signatures:
                row, col = python_input.signatures[0].bracket_start
                index = b.document.translate_row_col_to_index(row - 1, col)
                return index

        return Window(
            BufferControl(
                buffer=python_input.default_buffer,
                search_buffer_control=search_toolbar.control,
                lexer=lexer,
                include_default_input_processors=False,
                input_processors=[
                    ConditionalProcessor(
                        processor=HighlightIncrementalSearchProcessor(),
                        filter=has_focus(SEARCH_BUFFER)
                        | has_focus(search_toolbar.control),
                    ),
                    HighlightSelectionProcessor(),
                    DisplayMultipleCursors(),
                    # Show matching parentheses, but only while editing.
                    ConditionalProcessor(
                        processor=HighlightMatchingBracketProcessor(
                            chars='[](){}'),
                        filter=has_focus(DEFAULT_BUFFER) & ~is_done
                        & Condition(lambda: python_input.
                                    highlight_matching_parenthesis)),
                    ConditionalProcessor(processor=AppendAutoSuggestion(),
                                         filter=~is_done)
                ] + extra_buffer_processors,
                menu_position=menu_position,

                # Make sure that we always see the result of an reverse-i-search:
                preview_search=True,
            ),
            left_margins=[PythonPromptMargin(python_input)],
            # Scroll offsets. The 1 at the bottom is important to make sure the
            # cursor is never below the "Press [Meta+Enter]" message which is a float.
            scroll_offsets=ScrollOffsets(bottom=1, left=4, right=4),
            # As long as we're editing, prefer a minimal height of 6.
            height=(lambda: (None if get_app().is_done or python_input.
                             show_exit_confirmation else input_buffer_height)),
            wrap_lines=Condition(lambda: python_input.wrap_lines),
        )

    root_container = HSplit([
        VSplit([
            HSplit([
                FloatContainer(
                    content=HSplit([create_python_input_window()] +
                                   extra_body),
                    floats=[
                        Float(xcursor=True,
                              ycursor=True,
                              content=ConditionalContainer(
                                  content=CompletionsMenu(scroll_offset=(
                                      lambda: python_input.
                                      completion_menu_scroll_offset),
                                                          max_height=12),
                                  filter=show_completions_menu(python_input))),
                        Float(xcursor=True,
                              ycursor=True,
                              content=ConditionalContainer(
                                  content=MultiColumnCompletionsMenu(),
                                  filter=show_multi_column_completions_menu(
                                      python_input))),
                        Float(xcursor=True,
                              ycursor=True,
                              content=signature_toolbar(python_input)),
                        Float(left=2,
                              bottom=1,
                              content=exit_confirmation(python_input)),
                        Float(bottom=0,
                              right=0,
                              height=1,
                              content=meta_enter_message(python_input),
                              hide_when_covering_content=True),
                        Float(bottom=1,
                              left=1,
                              right=0,
                              content=python_sidebar_help(python_input)),
                    ]),
                ArgToolbar(),
                search_toolbar,
                SystemToolbar(),
                ValidationToolbar(),
                ConditionalContainer(content=CompletionsToolbar(),
                                     filter=show_completions_toolbar(
                                         python_input)),

                # Docstring region.
                ConditionalContainer(content=Window(
                    height=D.exact(1), char='\u2500', style='class:separator'),
                                     filter=HasSignature(python_input)
                                     & ShowDocstring(python_input) & ~is_done),
                ConditionalContainer(
                    content=Window(
                        BufferControl(
                            buffer=python_input.docstring_buffer,
                            lexer=SimpleLexer(style='class:docstring'),
                            #lexer=PythonLexer,
                        ),
                        height=D(max=12)),
                    filter=HasSignature(python_input)
                    & ShowDocstring(python_input) & ~is_done),
            ]),
            ConditionalContainer(content=HSplit([
                python_sidebar(python_input),
                Window(style='class:sidebar,separator', height=1),
                python_sidebar_navigation(python_input),
            ]),
                                 filter=ShowSidebar(python_input) & ~is_done)
        ]),
    ] + extra_toolbars + [
        VSplit([
            status_bar(python_input),
            show_sidebar_button_info(python_input),
        ])
    ])

    return Layout(root_container)
Example #28
0
        Comment: '#0000dd',
        Error: '#000000 bg:#ff8888',

        # Completion Menu
        Token.Menu.Completions.Completion.Current: 'bg:#00aaaa #000000',
        Token.Menu.Completions.Completion: 'bg:#008888 #ffffff',
        Token.Menu.Completions.ProgressButton: 'bg:#003333',
        Token.Menu.Completions.ProgressBar: 'bg:#00aaaa',
    }


if __name__ == '__main__':
    cli = CommandLineInterface(layout=Layout(
        before_input=DefaultPrompt('(pdb) '),
        after_input=CompletionHint(grammar),
        menus=[CompletionsMenu()]),
                               line=Line(completer=ShellCompleter(grammar)),
                               style=PdbStyle)

    try:
        while True:
            document = cli.read_input(on_exit=AbortAction.RAISE_EXCEPTION)

            try:
                parse_info = get_parse_info(grammar, document)
            except InvalidCommandException:
                print('Invalid command\n')
                continue
            else:
                print(parse_info.get_variables())
Example #29
0
    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)
Example #30
0
def main():
    manager = KeyBindingManager(enable_system_bindings=Always())

    D = LayoutDimension
    layout = HSplit([
        VSplit([
            Window(width=D(min=15, max=30, preferred=30),
                   content=FillControl('a', token=Token.A)),
            Window(width=D.exact(1),
                   content=FillControl('|', token=Token.Line)),
            Window(content=TokenListControl.static([(Token.HelloWorld,
                                                     lipsum)])),
            Window(width=D.exact(1),
                   content=FillControl('|', token=Token.Line)),
            Window(content=BufferControl(
                lexer=PygmentsLexer(PythonLexer),
                margin=NumberredMargin(),
                input_processors=[
                    DefaultPrompt.from_message('python> '),
                    AfterInput.static(' <python', token=Token.AfterInput),
                ]), ),
            Window(width=D.exact(1),
                   content=FillControl('|', token=Token.Line)),
            HSplit([
                Window(width=D(max=40),
                       height=D.exact(4),
                       content=FillControl('b', token=Token.B)),
                Window(width=D(max=40),
                       content=FillControl('f', token=Token.F)),
                Window(width=D.exact(30),
                       height=D.exact(2),
                       content=FillControl('c', token=Token.C)),
            ]),
            #CompletionsMenu(),
        ]),
        Window(height=D.exact(1), content=FillControl('-', token=Token.Line)),
        Window(height=D.exact(3), content=FillControl('d', token=Token.D)),
        SystemToolbar(),
        ArgToolbar(),
        CompletionsToolbar(),
        SearchToolbar(),
    ])

    layout = FloatContainer(content=layout,
                            floats=[
                                Float(xcursor=True,
                                      ycursor=True,
                                      content=VSplit([
                                          Window(width=D.exact(5),
                                                 content=FillControl(
                                                     'f', token=Token.F)),
                                          CompletionsMenu(),
                                      ])),
                            ])

    eventloop = create_eventloop()
    application = Application(layout=layout,
                              style=TestStyle,
                              key_bindings_registry=manager.registry,
                              buffer=Buffer(is_multiline=Always(),
                                            completer=TestCompleter()))

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

    cli.run()
    eventloop.close()