示例#1
0
 def _create_application(self):
     """
     Create an `Application` instance.
     """
     return Application(
         input=self.input,
         output=self.output,
         layout=self.ptpython_layout.layout,
         key_bindings=merge_key_bindings([
             load_python_bindings(self),
             load_auto_suggest_bindings(),
             load_sidebar_bindings(self),
             load_confirm_exit_bindings(self),
             # Extra key bindings should not be active when the sidebar is visible.
             ConditionalKeyBindings(
                 self.extra_key_bindings,
                 Condition(lambda: not self.show_sidebar))
         ]),
         color_depth=lambda: self.color_depth,
         paste_mode=Condition(lambda: self.paste_mode),
         mouse_support=Condition(lambda: self.enable_mouse_support),
         style=DynamicStyle(lambda: self._current_style),
         style_transformation=self.style_transformation,
         include_default_pygments_style=False,
         reverse_vi_search_direction=True)
示例#2
0
 def _create_application(self, color_depth):
     """
     Create an `Application` instance.
     """
     return Application(
         input=self.input,
         output=self.output,
         layout=create_layout(
             self,
             lexer=DynamicLexer(
                 lambda: self._lexer
                 if self.enable_syntax_highlighting else SimpleLexer()),
             input_buffer_height=self._input_buffer_height,
             extra_buffer_processors=self._extra_buffer_processors,
             extra_body=self._extra_layout_body,
             extra_toolbars=self._extra_toolbars),
         key_bindings=merge_key_bindings([
             load_python_bindings(self),
             load_sidebar_bindings(self),
             load_confirm_exit_bindings(self),
             # Extra key bindings should not be active when the sidebar is visible.
             ConditionalKeyBindings(
                 self.extra_key_bindings,
                 Condition(lambda: not self.show_sidebar))
         ]),
         color_depth=color_depth,
         paste_mode=Condition(lambda: self.paste_mode),
         mouse_support=Condition(lambda: self.enable_mouse_support),
         style=DynamicStyle(lambda: self._current_style),
         include_default_pygments_style=False,
         reverse_vi_search_direction=True)
示例#3
0
 def _create_application(self):
     """
     Create an `Application` instance.
     """
     return Application(
         input=self.input,
         output=self.output,
         layout=self.ptpython_layout.layout,
         key_bindings=merge_key_bindings([
             load_python_bindings(self),
             load_auto_suggest_bindings(),
             load_sidebar_bindings(self),
             load_confirm_exit_bindings(self),
             ConditionalKeyBindings(
                 load_open_in_editor_bindings(),
                 Condition(lambda: self.enable_open_in_editor)),
             # Extra key bindings should not be active when the sidebar is visible.
             ConditionalKeyBindings(
                 self.extra_key_bindings,
                 Condition(lambda: not self.show_sidebar))
         ]),
         color_depth=lambda: self.color_depth,
         paste_mode=Condition(lambda: self.paste_mode),
         mouse_support=Condition(lambda: self.enable_mouse_support),
         style=DynamicStyle(lambda: self._current_style),
         style_transformation=self.style_transformation,
         include_default_pygments_style=False,
         reverse_vi_search_direction=True)
示例#4
0
文件: app.py 项目: tcrensink/tsar
    def __init__(self):

        collections = {
            coll_id: Collection.load(coll_id)
            for coll_id in Collection.registered_collections()
        }
        if collections:
            active_collection = collections[list(collections.keys())[0]]
        else:
            active_collection = Collection.new(collection_id="temp_colleciton",
                                               doc_types=list(
                                                   DOCTYPES.values()))

        self.global_kb = return_global_keybindings(self)

        # global state dict that objects (e.g. screens) register themselves to and can access.
        self.state = {
            "app": Application(full_screen=True),
            "collections": collections,
            "active_collection": active_collection,
            "views": {},
        }

        # add screens; self.state must exist before adding but all objects share state ref.
        self.state["views"]["search"] = SearchView(state=self.state)
        self.state["views"]["collections"] = CollectionsView(state=self.state)

        self.state["active_view"] = self.state["views"]["search"]
        self.state["app"].layout = self.state["active_view"].layout
        self.state["app"].key_bindings = merge_key_bindings(
            [self.global_kb, self.state["active_view"].kb])
示例#5
0
    def key_bindings(self):
        kb = KeyBindings()

        @kb.add("c-c")
        @kb.add("c-q")
        def terminate(event):
            event.app.exit(None)

        return merge_key_bindings([self.container.key_bindings, kb])
示例#6
0
    def __init__(self,
                 options,
                 default_index=0,
                 header_filter=lambda x: x,
                 match_filter=lambda x: x):

        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 = user._tui_status_line_format

        self.options_list = OptionsList(
            options,
            default_index,
            header_filter,
            match_filter,
            custom_filter=~has_focus(self.help_window))
        self.options_list.search_buffer.on_text_changed += self.update

        cmd, cmd_key_bindings = command_key_bindings(self)
        self.command_line_prompt = CommandLinePrompt(commands=cmd)
        key_bindings = merge_key_bindings(
            [general_key_bindings(self), cmd_key_bindings])

        _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,
        ])

        self.set_help_text()
        self.layout = Layout(_root_container)

        super(Picker, self).__init__(
            input=None,
            output=None,
            editing_mode=EditingMode.EMACS
            if user._tui_edit_mode == 'emacs' else EditingMode.VI,
            layout=self.layout,
            style=Style.from_dict(user_styles.get_user_styles()),
            key_bindings=key_bindings,
            include_default_pygments_style=False,
            full_screen=True,
            enable_page_navigation_bindings=True)
        self.update()
示例#7
0
def loop(cmd, history_file):
    buf = create_buffer(cmd, history_file)
    key_bindings = KeyBindings()
    bind_keys(buf, key_bindings)
    layout = create_layout(
        buffer=buf,
        multiline=True,
        lexer=SqlLexer,
        extra_input_processors=[
            ConditionalProcessor(
                processor=HighlightMatchingBracketProcessor(chars='[](){}'),
                filter=HasFocus(DEFAULT_BUFFER) & ~IsDone())
        ],
        get_bottom_toolbar_tokens=lambda: get_toolbar_tokens(cmd),
        get_prompt_tokens=lambda: [('class:prompt', 'cr> ')])
    output = get_default_output()
    app = Application(layout=layout,
                      style=style_from_pygments_cls(CrateStyle),
                      key_bindings=merge_key_bindings(
                          [key_bindings,
                           load_open_in_editor_bindings()]),
                      editing_mode=_get_editing_mode(),
                      output=output)
    cmd.get_num_columns = lambda: output.get_size().columns

    while True:
        try:
            text = app.run()
            if text:
                cmd.process(text)
            buf.reset()
        except ProgrammingError as e:
            if '401' in e.message:
                username = cmd.username
                password = cmd.password
                cmd.username = input('Username: '******'Bye!')
            return
示例#8
0
    def get_all_kb(self):
        kb = KeyBindings()

        @kb.add('c-c')
        def exit_app(_):
            self.quit_app()

        @kb.add('q')
        def exit_app(_):
            self.quit_app()

        extra_kb = self.get_kb() or KeyBindings()
        return merge_key_bindings([kb, extra_kb])
示例#9
0
def main():
    style = Style([
        ('terminal focused', 'bg:#aaaaaa'),
        ('title', 'bg:#000044 #ffffff underline'),
    ])

    term1 = Terminal()

    text_area = TextArea(text='Press Control-W to switch focus.\n'
                         'Then you can edit this text area.\n'
                         'Press Control-X to exit')

    kb = KeyBindings()

    @kb.add('c-w')
    def _(event):
        switch_focus()

    @kb.add('c-x', eager=True)
    def _(event):
        event.app.exit()

    def switch_focus():
        " Change focus when Control-W is pressed."
        if application.layout.has_focus(term1):
            application.layout.focus(text_area)
        else:
            application.layout.focus(term1)

    application = Application(
        layout=Layout(container=HSplit([
            Window(height=1,
                   style='class:title',
                   content=FormattedTextControl(
                       ' Press Control-W to switch focus.')),
            VSplit([
                term1,
                Window(style='bg:#aaaaff', width=1),
                text_area,
            ]),
        ]),
                      focused_element=term1),
        style=style,
        key_bindings=merge_key_bindings([
            load_key_bindings(),
            kb,
        ]),
        full_screen=True,
        mouse_support=True,
    )
    application.run()
示例#10
0
    def get_app(self):
        bindings = KeyBindings()

        @bindings.add(Keys.ControlC)
        def _ctrl_c(event):
            get_app().exit(exception=KeyboardInterrupt)

        @bindings.add(Keys.Enter)
        def _enter(event):
            get_app().exit(result=self.get_answer())

        return Application(layout=Layout(self.get_layout()),
                           key_bindings=merge_key_bindings(
                               [load_key_bindings(), bindings]),
                           style=get_theme_manager().get_current_style())
示例#11
0
    def mount(self, screen):
        """
        Mount a screen into the view.

        The screen must have a `main_container` attribute and,
        optionally, a `bindings` attribute.
        """
        if self._current_screen is not None:
            self._current_screen.stop()
        self._current_screen = screen
        if screen.bindings is not None:
            if screen.use_default_bindings:
                merged_key_bindings = merge_key_bindings(
                    [self.bindings, screen.bindings])
                self.application.key_bindings = merged_key_bindings
            else:
                self.application.key_bindings = screen.bindings
        else:
            # Screen does not define additional keybindings
            self.application.key_bindings = self.bindings
        self._render()
        screen.on_mount(self.application)
示例#12
0
    def __init__(self, pymux):
        self.pymux = pymux

        def get_search_state():
            " Return the currently active SearchState. (The one for the focused pane.) "
            return pymux.arrangement.get_active_pane().search_state

        self.custom_key_bindings = KeyBindings()

        self.key_bindings = merge_key_bindings([
            self._load_builtins(),
            self.custom_key_bindings,
        ])

        self._prefix = ('c-b', )
        self._prefix_binding = None

        # Load initial bindings.
        self._load_prefix_binding()

        # Custom user configured key bindings.
        # { (needs_prefix, key) -> (command, handler) }
        self.custom_bindings = {}
示例#13
0
    def __init__(self, pymux):
        self.pymux = pymux

        def get_search_state():
            " Return the currently active SearchState. (The one for the focused pane.) "
            return pymux.arrangement.get_active_pane().search_state

        self.custom_key_bindings = KeyBindings()

        self.key_bindings = merge_key_bindings([
            self._load_builtins(),
            self.custom_key_bindings,
        ])

        self._prefix = ('c-b', )
        self._prefix_binding = None

        # Load initial bindings.
        self._load_prefix_binding()

        # Custom user configured key bindings.
        # { (needs_prefix, key) -> (command, handler) }
        self.custom_bindings = {}
示例#14
0
def setup_app(gdb):
    def codeview_line_prefix(line_number, wrap_count):
        try:
            if False: pass
            elif line_number + 1 == get_app().my.gdb.lineno:
                return [('class:text-area.pfx,selected', '>')]
            elif get_app().my.gdb.sourcefile in get_app(
            ).my.gdb.breakpoints and line_number + 1 in get_app(
            ).my.gdb.breakpoints[get_app().my.gdb.sourcefile]:
                return [('class:text-area.pfx.bp', 'o')]
        except:
            pass
        return [('class:text-area.pfx', ' ')]

    controls = {}

    controls['header'] = Label(
        text=u'',
        style=u'class:header_label',
    )
    controls['codeview'] = TextArea(
        text=u'',
        read_only=True,
        scrollbar=True,
        line_numbers=True,
        wrap_lines=True,
        get_line_prefix=codeview_line_prefix,
        lexer=PygmentsLexer(CLexer),
        style=u'class:codeview',
        focusable=True,
        focus_on_click=True,
    )
    controls['gdbout'] = TextArea(
        text=u'',
        read_only=True,
        scrollbar=True,
        wrap_lines=True,
        style=u'class:gdbout',
        height=LayoutDimension(4, 16, preferred=8),
        focusable=True,
        focus_on_click=True,
    )
    controls['inferiorout'] = TextArea(
        text=u'',
        read_only=True,
        scrollbar=True,
        wrap_lines=False,
        style=u'class:inferiorout',
        height=LayoutDimension(1, 16, preferred=1),
        focusable=True,
        focus_on_click=True,
    )
    controls['locals'] = sidebar('locals', lambda: get_app().my.locals)
    controls['exprs'] = sidebar('exprs', lambda: get_app().my.exprs)
    controls['args'] = sidebar('args', lambda: get_app().my.args)
    controls['input_label'] = Label(
        text=u'(gdb) ',
        style=u'class:input_label',
        width=LayoutDimension.exact(6),
    )
    controls['input'] = Window(
        content=BufferControl(
            buffer=Buffer(
                read_only=False,
                multiline=False,
                history=InMemoryHistory(),
            ),
            focusable=True,
            focus_on_click=True,
        ),
        height=LayoutDimension.exact(1),
        dont_extend_height=True,
        style=u'class:input',
    )
    controls['vardetails'] = TextArea(
        height=LayoutDimension(1, 4),
        wrap_lines=True,
        read_only=True,
        style=u'class:vardetails',
    )

    def up_():
        val = get_app().my.locals.get_value_by_index( \
         get_app().my.controls['locals'].selected_option_index)
        text = get_app().my.controls['vardetails'].text
        if val is None and text != '':
            get_app().my.controls['vardetails'].text = '<out of scope>'
        elif text != '':
            get_app().my.controls['vardetails'].text = val[1]

    controls['vardetails'].update = up_

    def need_vardetails():
        return get_app().my.controls['vardetails'].text != ''

    controls['sidebar'] = HSplit([
        controls['exprs'],
        controls['args'],
        controls['locals'],
    ])
    controls['sidebar']._remaining_space_window.style = 'class:sidebar'

    controls['root_container'] = HSplit([
        controls['header'],
        ConditionalContainer(controls['vardetails'],
                             Condition(need_vardetails)),
        VSplit([
            HSplit([
                controls['codeview'],
                controls['inferiorout'],
                controls['gdbout'],
                VSplit([
                    controls['input_label'],
                    controls['input'],
                ]),
            ]),
            controls['sidebar'],
        ]),
    ])

    def do_exit():
        get_app().exit(result=True)

    def do_cont():
        run_gdb_cmd(get_app(), 'c')

    def do_step_into():
        run_gdb_cmd(get_app(), 's')

    def do_step_over():
        run_gdb_cmd(get_app(), 'n')

    def do_set_bp():
        if get_app().my.focused_control == 'codeview':
            c = get_app().my.controls['codeview']
            line, col = c.document.translate_index_to_position(
                c.document.cursor_position)
            line += 1
            run_gdb_cmd(get_app(),
                        'b %s:%d' % (get_app().my.gdb.sourcefile, line))

    def do_toggle_prompt():
        get_app().my.input_gdb = not get_app().my.input_gdb
        get_app().my.controls['input_label'].text = '(gdb) ' if get_app(
        ).my.input_gdb else '>>> '

    def do_toggle_mouse():
        # we need to have the ability to turn mouse off to use the X11
        # clipboard (selection needs to be handled by X11, not the app)
        get_app().my.mouse_enabled = not get_app().my.mouse_enabled

    controls['root_container'] = MenuContainer(
        body=controls['root_container'],
        menu_items=[
            MenuItem('File',
                     children=[
                         MenuItem('Load config', handler=load_config),
                         MenuItem('Save config', handler=save_config),
                         MenuItem('-', disabled=True),
                         MenuItem('Exit', handler=do_exit),
                     ]),
            MenuItem('Debug',
                     children=[
                         MenuItem('Continue  (F5)', handler=do_cont),
                         MenuItem('Step Into (F7)', handler=do_step_into),
                         MenuItem('Step Over (F8)', handler=do_step_over),
                         MenuItem('Set Breakpoint (CTRL-b)',
                                  handler=do_set_bp),
                     ]),
            MenuItem('Extra',
                     children=[
                         MenuItem('Toggle python prompt  (F1)',
                                  handler=do_toggle_prompt),
                         MenuItem('Toggle mouse support  (F2)',
                                  handler=do_toggle_mouse),
                     ]),
        ],
        floats=[])

    kb = KeyBindings()

    @kb.add(u'escape', 'f')
    def _focus_menu(event):
        get_app().layout.focus(get_app().my.controls['root_container'].window)

    @kb.add(u'c-q')
    def exit_(event):
        do_exit()

    @kb.add(u'f1')
    def eff_one_(event):
        do_toggle_prompt()

    @kb.add(u'enter')
    def enter_(event):
        def add_expr(name, expr):
            get_app().my.exprs_dict[name] = expr

        def del_expr(name):
            if name in get_app().my.exprs_dict:
                del get_app().my.exprs_dict[name]

        if event.app.my.focused_control != 'input':
            event.app.my.set_focus('input')
            return
        text = event.app.my.controls['input'].content.buffer.text
        if len(text) and text[0] == ':':
            # direct command
            command, rest = text.split(' ', 1)
            if command == ':expr':
                command, rest = rest.split(' ', 1)
                if command == 'add':
                    name, expr = rest.split(' ', 1)
                    add_expr(name, expr)
                elif command == 'del':
                    del_expr(rest)
        elif event.app.my.input_gdb:
            cmd = text
            if not len(cmd): cmd = event.app.my.last_gdb_cmd
            else: event.app.my.last_gdb_cmd = cmd
            run_gdb_cmd(event.app, cmd)
            if text == 'q':
                event.app.exit()
        else:
            try:
                app.my.console.runsource(text)
            except Exception as e:
                import traceback
                add_gdbview_text(event.app, traceback.format_exc())
        event.app.my.controls['input'].content.buffer.reset(
            append_to_history=True)

    @kb.add(u'tab')
    def enter_(event):
        for i in xrange(len(event.app.my.focus_list)):
            if event.app.my.focus_list[i] == event.app.my.focused_control:
                next_focus = i + 1
                if next_focus >= len(event.app.my.focus_list):
                    next_focus = 0
                event.app.my.set_focus(event.app.my.focus_list[next_focus])
                break

    @kb.add(u'c-b')
    def cb_(event):
        do_set_bp()

    @kb.add(u'f5')
    def eff_five_(event):
        do_cont()

    @kb.add(u'f7')
    def _(event):
        do_step_into()

    @kb.add(u'f8')
    def _(event):
        do_step_over()

    @kb.add(u'f2')
    def _(event):
        do_toggle_mouse()

    styledict = {
        'gdbout': 'bg:#000000 #888888',
        'inferiorout': 'bg:#330000 #888888',
        'input': 'bg:#000000 #8888ff underline',
        'input_label': 'bg:#000000 #8888ff underline',
        'header_label': 'bg:#9999ff #000000 underline',
        'vardetails': 'bg:#000000 #8888ff',
        'text-area.pfx': 'bg:#aaaaaa #ff0000',
        'text-area.pfx.selected': 'bg:#ff0000 #ffffff',
        'sidebar': 'bg:#bbbbbb #000000',
        'sidebar.title': 'bg:#668866 #ffffff',
        'sidebar.title focused': 'bg:#000000 #ffffff bold',
        'sidebar.label': 'bg:#bbbbbb #222222',
        'sidebar.status': 'bg:#dddddd #000011',
        'sidebar.labelodd': 'bg:#bbbb00 #222222',
        'sidebar.statusodd': 'bg:#dddd00 #000011',
        'sidebar.label selected': 'bg:#222222 #eeeeee',
        'sidebar.status selected': 'bg:#444444 #ffffff bold',
        'sidebar.status changed': 'bg:#dddddd #ff0000 bold',
        'sidebar.statusodd changed': 'bg:#dddd00 #ff0000 bold',
    }

    pyg_style = style_from_pygments_cls(CodeviewStyle)

    style = merge_styles([
        Style.from_dict(styledict),
        pyg_style,
    ])

    @Condition
    def _is_mouse_active():
        return get_app().my.mouse_enabled

    app = Application(
        layout=Layout(
            controls['root_container'],
            focused_element=controls['input'],
        ),
        style=style,
        full_screen=True,
        key_bindings=merge_key_bindings([
            kb,
            load_sidebar_bindings('locals'),
            load_inputbar_bindings(),
        ]),
        mouse_support=_is_mouse_active,
    )

    class My():
        pass

    app.my = My()
    app.my.saved_config = {}
    app.my.mouse_enabled = True
    app.my.controls = controls
    app.my.control_to_name_mapping = {}
    for name in controls:
        app.my.control_to_name_mapping[controls[name]] = name
        if isinstance(controls[name], TextArea) or 'control' in vars(
                controls[name]):
            app.my.control_to_name_mapping[controls[name].control] = name
        elif 'content' in vars(controls[name]):
            app.my.control_to_name_mapping[controls[name].content] = name

    app.my.locals = OrderedDict()
    app.my.args = OrderedDict()
    app.my.exprs = OrderedDict()
    app.my.exprs_dict = dict()
    app.my.gdb = gdb
    app.my.last_gdb_cmd = ''
    app.my.input_gdb = True
    app.my.focus_list = [
        'input', 'codeview', 'inferiorout', 'gdbout', 'args', 'locals', 'exprs'
    ]
    app.my.focused_control = 'input'

    def _set_focus(ctrl_or_name):
        if isinstance(ctrl_or_name, six.text_type):
            ctrl = get_app().my.controls[ctrl_or_name]
            name = ctrl_or_name
        else:
            ctrl = ctrl_or_name
            name = get_app().my.control_to_name_mapping[ctrl]
        get_app().layout.focus(ctrl)
        get_app().my.focused_control = name

    app.my.set_focus = _set_focus

    def _has_focus(ctrl_or_name):
        ctrl = get_app().my.controls[ctrl_or_name] if isinstance(
            ctrl_or_name, str) else ctrl_or_name
        return get_app().layout.has_focus(ctrl)

    app.my.has_focus = _has_focus
    app_console_writefunc = lambda x: add_gdbview_text(get_app(), x)
    app.my.console = py_console.Shell(locals=globals(),
                                      writefunc=app_console_writefunc)

    def my_mouse_handler(self, mouse_event):
        # loosely based on prompt_toolkit/layout/controls.py:716
        #if self.focus_on_click() and mouse_event.event_type == MouseEventType.MOUSE_DOWN:
        if mouse_event.event_type == MouseEventType.MOUSE_DOWN:
            get_app().my.set_focus(self)
            processed_line = self._last_get_processed_line(
                mouse_event.position.y)
            xpos = processed_line.display_to_source(mouse_event.position.x)
            index = self.buffer.document.translate_row_col_to_index(
                mouse_event.position.y, xpos)
            self.buffer.cursor_position = index
        else:
            return NotImplemented

    for x in app.my.focus_list:
        if isinstance(app.my.controls[x], Window) and isinstance(
                app.my.controls[x].content, SidebarControl):
            continue  #don't override custom mouse handler
        if isinstance(app.my.controls[x], TextArea):
            app.my.controls[
                x].control.mouse_handler = my_mouse_handler.__get__(
                    app.my.controls[x].control)
        else:
            app.my.controls[
                x].content.mouse_handler = my_mouse_handler.__get__(
                    app.my.controls[x].content)

    return app
示例#15
0
文件: app.py 项目: tcrensink/tsar
 def update_active_view(self, view):
     self.state["app"].layout = view.layout
     self.state["active_view"] = view
     self.state["app"].key_bindings = merge_key_bindings(
         [self.global_kb, view.kb])
     view.reset_view()
示例#16
0
    def _create_application(self) -> Application:
        self.sql_layout = sqlAppLayout(my_app=self)
        kb = KeyBindings()

        confirmation_visible = Condition(lambda: self.show_exit_confirmation)

        @kb.add("c-q")
        def _(event):
            " Pressing Ctrl-Q or Ctrl-C will exit the user interface. "
            self.show_exit_confirmation = True

        @kb.add("y", filter=confirmation_visible)
        @kb.add("Y", filter=confirmation_visible)
        @kb.add("enter", filter=confirmation_visible)
        @kb.add("c-q", filter=confirmation_visible)
        def _(event):
            """
            Really quit.
            """
            event.app.exit(exception=ExitEX(), style="class:exiting")

        @kb.add(Keys.Any, filter=confirmation_visible)
        def _(event):
            """
            Cancel exit.
            """
            self.show_exit_confirmation = False

        # Global key bindings.
        @kb.add("tab",
                filter=Condition(
                    lambda: self.show_preview or self.show_login_prompt))
        def _(event):
            event.app.layout.focus_next()

        @kb.add("f4")
        def _(event):
            " Toggle between Emacs and Vi mode. "
            self.vi_mode = not self.vi_mode

        # apparently ctrls does this
        @kb.add("c-t", filter=Condition(lambda: not self.show_preview))
        def _(event):
            """
            Show/hide sidebar.
            """
            self.show_sidebar = not self.show_sidebar
            if self.show_sidebar:
                event.app.layout.focus("sidebarbuffer")
            else:
                event.app.layout.focus_previous()

        sidebar_visible = Condition(lambda: self.show_sidebar and not self.show_expanding_object and not self.show_login_prompt and not self.show_preview) \
                        & ~has_focus("sidebarsearchbuffer")

        @kb.add("up", filter=sidebar_visible)
        @kb.add("c-p", filter=sidebar_visible)
        @kb.add("k", filter=sidebar_visible)
        def _(event):
            " Go to previous option. "
            obj = self._selected_object
            self.select_previous()
            inc = len(self.selected_object.name) + 1  # newline character
            if obj is self.obj_list[0]:
                idx = 0
                cursor = 0
                while obj is not self._selected_object:
                    if not obj.next_object:
                        raise IndexError
                    cursor += len(obj.name) + 1
                    idx += 1
                    obj = obj.next_object
                self._selected_obj_idx = [idx, cursor]
            else:
                self._selected_obj_idx[0] -= 1
                self._selected_obj_idx[1] -= inc

        @kb.add("down", filter=sidebar_visible)
        @kb.add("c-n", filter=sidebar_visible)
        @kb.add("j", filter=sidebar_visible)
        def _(event):
            " Go to next option. "
            inc = len(self.selected_object.name) + 1  # newline character
            self.select_next()
            if self.selected_object is self.obj_list[0]:
                self._selected_obj_idx = [0, 0]
            else:
                self._selected_obj_idx[0] += 1
                self._selected_obj_idx[1] += inc

        @kb.add("enter", filter=sidebar_visible)
        def _(event):
            " If connection, connect.  If table preview"
            obj = self.selected_object
            if type(obj).__name__ == "myDBConn" and not obj.conn.connected():
                self.show_login_prompt = True
                event.app.layout.focus(self.sql_layout.lprompt)
            if type(obj).__name__ == "myDBConn" and obj.conn.connected():
                # OG: some thread locking may be needed here
                self._active_conn = obj.conn
            elif obj.otype in ["table", "view", "function"]:
                self.show_preview = True
                self.show_sidebar = False
                event.app.layout.focus(self.sql_layout.preview)

        @kb.add("right", filter=sidebar_visible)
        @kb.add("l", filter=sidebar_visible)
        @kb.add(" ", filter=sidebar_visible)
        def _(event):
            " Select next value for current option. "
            obj = self.selected_object
            obj.expand()
            if type(obj).__name__ == "myDBConn" and not obj.conn.connected():
                self.show_login_prompt = True
                event.app.layout.focus(self.sql_layout.lprompt)

        @kb.add("left", filter=sidebar_visible)
        @kb.add("h", filter=sidebar_visible)
        def _(event):
            " Select next value for current option. "
            obj = self.selected_object
            if type(obj).__name__ == "myDBConn" and obj.conn.connected(
            ) and obj.children is None:
                self.show_disconnect_dialog = True
                event.app.layout.focus(self.sql_layout.disconnect_dialog)
            else:
                obj.collapse()

        auto_suggest_bindings = load_auto_suggest_bindings()

        return Application(
            layout=self.sql_layout.layout,
            key_bindings=merge_key_bindings([kb, auto_suggest_bindings]),
            enable_page_navigation_bindings=True,
            style=style_factory(self.syntax_style, self.cli_style),
            include_default_pygments_style=False,
            mouse_support=self.mouse_support,
            full_screen=False,
            editing_mode=EditingMode.VI
            if self.config["main"].as_bool("vi") else EditingMode.EMACS)
示例#17
0
    def _get_key_bindings(self):
        kb = KeyBindings()

        @kb.add('c-up')
        def _(event):
            self.console.enter_copy_mode()

        @kb.add('c-x', 'a', eager=True)
        def _(event):
            self._hide_tui()
            self.app.invalidate()

        @kb.add('c-x', '1', eager=True)
        def _(event):
            self._hide_tui()
            self.source.show = True
            self.app.invalidate()

        @kb.add('c-x', '2', eager=True)
        def _(event):
            self._hide_tui()
            self.source.show = True
            self.disassembly.show = True

        @kb.add('c-x', 's', eager=True)
        def _(event):
            self.source.toggle_show()
            self.app.invalidate()

        @kb.add('c-x', 'd', eager=True)
        def _(event):
            self.disassembly.toggle_show()
            self.app.invalidate()

        @kb.add('c-x', 'c', eager=True)
        def _(event):
            self.callstack.toggle_show()
            self.app.invalidate()

        @kb.add('c-x', 'v', eager=True)
        def _(event):
            self.argsnlocals.toggle_show()
            self.app.invalidate()

        @kb.add('c-x', 'b', eager=True)
        def _(event):
            self.breakpoints.toggle_show()
            self.app.invalidate()

        @kb.add('c-x', 'r', eager=True)
        def _(event):
            self.registers.toggle_show()
            self.app.invalidate()

        @kb.add('c-x', 't', eager=True)
        def _(event):
            self.threads.toggle_show()

        @kb.add('c-s', eager=True)
        def _(event):
            self._next_style()

        @kb.add('c-l')
        def _(event):
            pass

        @kb.add('c-x')
        def _(event):
            pass

        @kb.add('s-right')
        def _(event):
            self.layout.focus_next()

        @kb.add('s-left')
        def _(event):
            self.layout.focus_previous()

        kb = merge_key_bindings([load_key_bindings(), kb])
        return kb
示例#18
0
    def __init__(self, username: str, password: str):
        super().__init__(username, password, handle_data=DataFormat.ANSI)

        self.commands = []

        self.output_buffer = Buffer_()
        self.cursor_pos = 0

        self.chat_buffer = Buffer_()

        self.output = BufferControl(self.output_buffer,
                                    input_processors=[FormatText()],
                                    include_default_input_processors=True)

        self.chat = BufferControl(self.chat_buffer,
                                  input_processors=[FormatText()],
                                  include_default_input_processors=True)

        self.hide_ip = "--hide-ip" in sys.argv

        self.suggest = AutoSuggestFromLogs([
            CommandSuggest(),
        ])

        self.input = TextArea(height=1,
                              prompt=" >> ",
                              multiline=False,
                              wrap_lines=False,
                              accept_handler=self.accept,
                              auto_suggest=self.suggest,
                              dont_extend_width=True)

        self.host_ip = FormattedTextControl(ANSI(""))

        self.chat_float = Float(Frame(Window(self.chat, wrap_lines=True)),
                                right=1,
                                top=0,
                                width=40,
                                height=12,
                                hide_when_covering_content=True)

        self.text = ""
        self.chat_text = ""

        def set_frame_size(fn):
            def inner(*args):
                size = self.app.output.get_size()
                self.chat_float.width = size.columns // 3
                self.chat_float.height = size.rows // 2
                return fn(*args)

            return inner

        self.out_window = Window(self.output, wrap_lines=True)

        kb = KeyBindings()

        @kb.add('c-c')
        @kb.add('c-q')
        def _(_):
            self.app.exit()
            self._loop = False
            self.run_again = False

        @kb.add('c-i', filter=has_focus(self.input))
        def __(_):
            fut = self.suggest.get_suggestion_future(self.input.buffer,
                                                     self.input.document)
            text = self.input.text

            def set_input(fut_2):
                res = fut_2.result()
                if res is not None:
                    self.input.text = text + res.text
                    self.input.document = Document(self.input.text,
                                                   cursor_position=len(
                                                       self.input.text))

            fut.add_done_callback(set_input)

        @kb.add(Keys.ScrollUp)
        def sup(_):
            self.output_buffer.cursor_up(1)
            self.out_window._scroll_up()  # pylint: disable=protected-access

        @kb.add(Keys.ScrollDown)
        def sdown(_):
            self.output_buffer.cursor_down(1)
            self.out_window._scroll_down()  # pylint: disable=protected-access

        self.app = Application(
            layout=Layout(
                container=HSplit([
                    Frame(
                        FloatContainer(self.out_window,
                                       floats=[self.chat_float])),
                    Frame(
                        VSplit([
                            self.input,
                            Window(self.host_ip,
                                   align=WindowAlign.RIGHT,
                                   dont_extend_width=True)
                        ]))
                ]),
                focused_element=self.input,
            ),
            full_screen=True,
            mouse_support=True,
            enable_page_navigation_bindings=True,
            key_bindings=merge_key_bindings([kb]),
            paste_mode=True,
        )

        self.app._on_resize = set_frame_size(self.app._on_resize)  # pylint: disable=protected-access

        self.run_again = True
        self.loop = get_event_loop()
        self._loop = False

        self.own_pass = ""
        self.own_ip = ""
        self.current_ip = ""
示例#19
0
def interrogatio(questions, theme='default'):
    """
    Prompts user for inputs as defined in the questions parameter and returns
    a dictionary with the answers.

    :param questions: a list of questions.
    :type questions: list
    :param theme: the name of the theme to use.
    :type theme: string

    :return: a dictionary with the answers.
    :rtype: dict

    :raise InvalidQuestionError: if there is an error in the question
                                 definition.
    :raise ThemeNotFoundError: if the specified theme does not exists.

    Usage:

    .. code-block:: python

        from interrogatio import interrogatio
        questions = [
            {
                'name': 'name',
                'type': 'input',
                'message': 'What is your name'
            },
            {
                'name': 'favorite_pet',
                'type': 'input',
                'message': 'What is your favorite pet'
            }
        ]
        answers = interrogatio(questions, theme='purple')
    """
    set_theme(theme)
    answers = {}
    validate_questions(questions)
    for q in questions:
        handler = get_instance(q)
        handler.set_context(answers)
        layout = handler.get_layout()
        layout.align = HorizontalAlign.LEFT

        bindings = [load_key_bindings()]

        handler_bindings = handler.get_keybindings()

        if handler_bindings:  # pragma: no branch
            bindings.append(handler_bindings)

        app = Application(
            layout=Layout(layout),
            key_bindings=merge_key_bindings(bindings),
            style=for_prompt(),
        )

        while True:
            result = app.run()
            if not result:
                return
            if handler.is_valid(answers):
                answers.update(handler.get_answer())
                break
            else:
                print_formatted_text(
                    FormattedText([('class:error', handler.errors[0])]),
                    style=for_prompt(),
                )
    return answers
示例#20
0
文件: interface.py 项目: kiblee/tod0
    # Add empty container if task list is empty
    if not tasks:
        right_window.children = [
            Window(FormattedTextControl("-- No Tasks --"))
        ]
    else:
        right_window.children = tasks
        focus_index_task = 0
        tasks[focus_index_task].style = color_task
    focus_folder = False


# Creating an `Application` instance
# ----------------------------------
application = Application(
    layout=Layout(root_container),
    key_bindings=merge_key_bindings([kb, kb_exit, kb_escape]),
    mouse_support=False,
    full_screen=False,
)


# Run the application
# -------------------
def run():
    application.run()


if __name__ == "__main__":
    run()
示例#21
0
    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()
示例#22
0
文件: list.py 项目: jarvis394/notty
    ],
    height=1,
    style="class:topbar",
)
root_container = FloatContainer(HSplit([
    titlebar,
    body,
]), floats=[])
application = Application(
    layout=Layout(root_container, focused_element=sidebar),
    key_bindings=merge_key_bindings([
        kb,
        ConditionalKeyBindings(
            key_bindings=focus_bindings,
            filter=Condition(lambda: not state.is_float_displaying),
        ),
        ConditionalKeyBindings(
            key_bindings=sidebar_bindings,
            filter=Condition(lambda: state.focused_window == sidebar),
        ),
    ]),
    mouse_support=True,
    full_screen=True,
    style=style,
    refresh_interval=0.5,
)


def execute():
    async def main():
        update_text_window(0)