예제 #1
0
    ApplicationState.show_status_bar = not ApplicationState.show_status_bar


#
# The menu container.
#

root_container = MenuContainer(
    body=body,
    menu_items=[
        MenuItem(
            "File",
            children=[
                MenuItem("New...", handler=do_new_file),
                MenuItem("Open...", handler=do_open_file),
                MenuItem("Save"),
                MenuItem("Save as..."),
                MenuItem("-", disabled=True),
                MenuItem("Exit", handler=do_exit),
            ],
        ),
        MenuItem(
            "Edit",
            children=[
                MenuItem("Undo", handler=do_undo),
                MenuItem("Cut", handler=do_cut),
                MenuItem("Copy", handler=do_copy),
                MenuItem("Paste", handler=do_paste),
                MenuItem("Delete", handler=do_delete),
                MenuItem("-", disabled=True),
                MenuItem("Find", handler=do_find),
예제 #2
0
             SPACE,
             QLabel("<F5=Run>"),
             SPACE,
             QLabel("<CTRL+R=Run>"),
         ],
         style="bg:#00AAAA fg:white bold",
         height=1,
     ),
 ]),
 menu_items=[
     MenuItem(
         " File ",
         children=[
             MenuItem("New...", handler=new),
             MenuItem("Open...", handler=open_file),
             MenuItem("Save", handler=save_file),
             MenuItem("Save as...", handler=save_as_file),
             MenuItem("-", disabled=True),
             MenuItem("Exit", handler=exit),
         ],
     ),
     MenuItem(
         " Edit ",
         children=[
             MenuItem("Undo", handler=undo),
             MenuItem("Cut", handler=cut),
             MenuItem("Copy", handler=copy),
             MenuItem("Paste", handler=paste),
             MenuItem("Delete", handler=delete),
             MenuItem("-", disabled=True),
             MenuItem("Go To", handler=goto),
예제 #3
0
        body=Window(
            FormattedTextControl(
                text=get_caller_identity(),
                focusable=False,
            ),
            height=3,
        ),
    ),
])

root_container = MenuContainer(
    body=root_container,
    menu_items=[
        MenuItem(
            "File",
            children=[
                MenuItem("Exit", handler=do_exit),
            ],
        ),
    ],
    floats=[
        Float(
            xcursor=True,
            ycursor=True,
            content=CompletionsMenu(max_height=16, scroll_offset=1),
        ),
    ],
)

# Global key bindings.
bindings = KeyBindings()
bindings.add("tab")(focus_next)
예제 #4
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)),
            ])
예제 #5
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
예제 #6
0
context = Context()

shade_menu = ShadeMenu(context)
context.shade_menu = shade_menu

scene_menu = SceneMenu(context)
context.scene_menu = scene_menu

test_menu = SideBar(context, [], None)

menu_items = [
    MenuItem(
        "file",
        children=[
            MenuItem("shades", shade_menu.show),
            MenuItem("scenes", scene_menu.show),
        ],
    )
]

layout = get_layout(shade_menu, menu_items)

app = Application(
    layout=layout,
    full_screen=True,
    key_bindings=kb,
    style=ui_style,
)

loop.run_until_complete(app.run_async().to_asyncio_future())
예제 #7
0
    def create_content(self):

        # 文本编辑器
        text_editor = self.create_text_editor()

        # 播放列表属性编辑器
        property_editor = self.create_property_editor()

        body = HSplit([
            HSplit(
                [
                    property_editor,
                    Label(' '),
                    Window(height=1, char="-", style="class:line"),
                    text_editor,
                ],
                height=D(),
            ),
            ConditionalContainer(
                content=VSplit(
                    [
                        Window(FormattedTextControl(self.get_statusbar_text),
                               style="class:status"),
                        Window(
                            FormattedTextControl(
                                self.get_statusbar_right_text),
                            style="class:status.right",
                            width=9,
                            align=WindowAlign.RIGHT,
                        ),
                    ],
                    height=1,
                ),
                filter=Condition(lambda: self.is_show_status_bar()),
            ),
        ])

        self.create_key_bindings()

        root_container = MenuContainer(
            body=body,
            menu_items=[
                MenuItem(
                    "File",
                    children=[
                        MenuItem("Exit", handler=self.exit),
                    ],
                ),
            ],
            floats=[
                Float(
                    xcursor=True,
                    ycursor=True,
                    content=CompletionsMenu(max_height=16, scroll_offset=1),
                ),
            ],
            key_bindings=self.key_bindings,
        )

        style = Style.from_dict({
            "status": "reverse",
            "shadow": "bg:#440044",
        })

        self.layout = Layout(root_container, focused_element=self.text_field)

        self.application = Application(
            layout=self.layout,
            enable_page_navigation_bindings=True,
            style=style,
            mouse_support=True,
            full_screen=True,
        )
예제 #8
0

def do_status_bar():
    ApplicationState.show_status_bar = not ApplicationState.show_status_bar


#
# The menu container.
#


root_container = MenuContainer(body=body, menu_items=[
    MenuItem('File', children=[
        MenuItem('New...', handler=do_new_file),
        MenuItem('Open...', handler=do_open_file),
        MenuItem('Save'),
        MenuItem('Save as...'),
        MenuItem('-', disabled=True),
        MenuItem('Exit', handler=do_exit),
        ]),
    MenuItem('Edit', children=[
        MenuItem('Undo', handler=do_undo),
        MenuItem('Cut', handler=do_cut),
        MenuItem('Copy', handler=do_copy),
        MenuItem('Paste', handler=do_paste),
        MenuItem('Delete', handler=do_delete),
        MenuItem('-', disabled=True),
        MenuItem('Find', handler=do_find),
        MenuItem('Find next', handler=do_find_next),
        MenuItem('Replace'),
        MenuItem('Go To', handler=do_go_to),
        MenuItem('Select All', handler=do_select_all),
예제 #9
0
    def __init__(self,
                 ctui,
                 input_field=None,
                 output_field=None,
                 statusbar=None,
                 root_container=None):
        """Stores layout of the app returns root_container"""
        completer = WordCompleter(ctui._commands(),
                                  meta_dict=ctui._meta_dict(),
                                  sentence=True,
                                  ignore_case=True)
        history = FileHistory("{}/.{}_history".format(Path.home(), ctui.name))
        search_field = SearchToolbar()

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

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

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

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

        # Organization of windows
        self.body = FloatContainer(HSplit([
            self.input_field, self.header_field, self.output_field,
            search_field, self.statusbar
        ]),
                                   floats=[
                                       Float(xcursor=True,
                                             ycursor=True,
                                             content=CompletionsMenu(
                                                 max_height=16,
                                                 scroll_offset=1))
                                   ])

        # Adding menus
        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)),
            ])
예제 #10
0
 body=root_container,
 menu_items=[
     MenuItem(
         "File",
         children=[
             MenuItem("New"),
             MenuItem(
                 "Open",
                 children=[
                     MenuItem("From file..."),
                     MenuItem("From URL..."),
                     MenuItem(
                         "Something else..",
                         children=[
                             MenuItem("A"),
                             MenuItem("B"),
                             MenuItem("C"),
                             MenuItem("D"),
                             MenuItem("E"),
                         ],
                     ),
                 ],
             ),
             MenuItem("Save"),
             MenuItem("Save as..."),
             MenuItem("-", disabled=True),
             MenuItem("Exit", handler=do_exit),
         ],
     ),
     MenuItem(
         "Edit",
예제 #11
0
파일: ctserial.py 프로젝트: wguest/ctserial
def start_app(mode, connection):
    """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)

    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=[
            MenuItem('Project ',
                     children=[
                         MenuItem('New'),
                         MenuItem('Open'),
                         MenuItem('Save'),
                         MenuItem('Save as...'),
                         MenuItem('-', disabled=True),
                         MenuItem('Exit', handler=cmd.do_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('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)
        output_text = cmd.execute(input_field.text, output_field.text, event)

        # 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')
    @kb.add('c-q')
    def _(event):
        " Pressing Ctrl-Q or Ctrl-C will exit the user interface. "
        connection.close()
        event.app.exit()

    @kb.add('c-a')
    def _(event):
        event.app.mode = 'cmd'

    @kb.add('c-d')
    def _(event):
        """Press Ctrl-D for debug mode"""
        import pdb
        pdb.set_trace()

    @kb.add('escape')
    def _(event):
        """ Pressing ESC key will enter toggle input mode"""
        input_field.prompt = 'cmd> '

    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.mode = mode
    application.connection = connection
    application.run()
예제 #12
0
             SPACE,
             QLabel("<F5=Run>"),
             SPACE,
             QLabel("<CTRL+R=Run>"),
         ],
         style="bg:#00AAAA fg:white bold",
         height=1,
     ),
 ]),
 menu_items=[
     MenuItem(
         " File ",
         children=[
             MenuItem("New...", handler=new),
             MenuItem("Open...", handler=open_file),
             MenuItem("Save", handler=save_file),
             MenuItem("Save as..."),
             MenuItem("-", disabled=True),
             MenuItem("Exit", handler=exit),
         ],
     ),
     MenuItem(
         " Edit ",
         children=[
             MenuItem("Undo", handler=undo),
             MenuItem("Cut", handler=cut),
             MenuItem("Copy", handler=copy),
             MenuItem("Paste", handler=paste),
             MenuItem("Delete", handler=delete),
             MenuItem("-", disabled=True),
             MenuItem("Find", handler=search),
예제 #13
0
def create_application():
    def get_statusbar_text():
        return "Ctrl-C: Close. Ctrl-E: Execute. Ctrl-S: Stop music. F2: Open Menu. "

    def get_statusbar_right_text():
        return " {}:{}  ".format(
            text_field.document.cursor_position_row + 1,
            text_field.document.cursor_position_col + 1,
        )

    search_toolbar = SearchToolbar()
    text_field = TextArea(
        lexer=PygmentsLexer.from_filename('.mkl', sync_from_start=False),
        completer=VariableCompleter(ApplicationState.context),
        scrollbar=True,
        line_numbers=True,
        search_field=search_toolbar,
    )

    class TextInputDialog:
        def __init__(self, title="", label_text="", completer=None):
            self.future = Future()

            def accept_text(buf):
                get_app().layout.focus(ok_button)
                buf.complete_state = None
                return True

            def accept():
                self.future.set_result(self.text_area.text)

            def cancel():
                self.future.set_result(None)

            self.text_area = TextArea(
                completer=completer,
                multiline=False,
                width=D(preferred=40),
                accept_handler=accept_text,
            )

            ok_button = Button(text="OK", handler=accept)
            cancel_button = Button(text="Cancel", handler=cancel)

            self.dialog = Dialog(
                title=title,
                body=HSplit([Label(text=label_text), self.text_area]),
                buttons=[ok_button, cancel_button],
                width=D(preferred=80),
                modal=True,
            )

        def __pt_container__(self):
            return self.dialog

    class MessageDialog:
        def __init__(self, title, text):
            self.future = Future()

            def set_done():
                self.future.set_result(None)

            ok_button = Button(text="OK", handler=(lambda: set_done()))

            self.dialog = Dialog(
                title=title,
                body=HSplit([
                    Label(text=text),
                ]),
                buttons=[ok_button],
                width=D(preferred=80),
                modal=True,
            )

        def __pt_container__(self):
            return self.dialog

    body = HSplit([
        text_field,
        search_toolbar,
        ConditionalContainer(
            content=VSplit(
                [
                    Window(FormattedTextControl(get_statusbar_text),
                           style="class:status"),
                    Window(
                        FormattedTextControl(get_statusbar_right_text),
                        style="class:status.right",
                        width=9,
                        align=WindowAlign.RIGHT,
                    ),
                ],
                height=1,
            ),
            filter=Condition(lambda: ApplicationState.show_status_bar),
        ),
    ])

    # Global key bindings.
    bindings = KeyBindings()

    @bindings.add("f2")
    def _(event):
        " Focus menu. "
        event.app.layout.focus(root_container.window)

    #
    # Handlers for menu items.
    #

    def do_open_file():
        async def coroutine():
            open_dialog = TextInputDialog(
                title="Open file",
                label_text="Enter the path of a file:",
                completer=PathCompleter(),
            )

            path = await show_dialog_as_float(open_dialog)
            ApplicationState.current_path = path

            if path is not None:
                try:
                    with open(path, "rb") as f:
                        text_field.text = f.read().decode("utf-8",
                                                          errors="ignore")
                except IOError as e:
                    show_message("Error", "{}".format(e))

        ensure_future(coroutine())

    def do_about():
        show_message("About",
                     "Text editor demo.\nCreated by Jonathan Slenders.")

    def show_message(title, text):
        async def coroutine():
            dialog = MessageDialog(title, text)

            await show_dialog_as_float(dialog)

        ensure_future(coroutine())

    async def show_dialog_as_float(dialog):
        " Coroutine. "
        float_ = Float(content=dialog)
        root_container.floats.insert(0, float_)

        app = get_app()

        focused_before = app.layout.current_window
        app.layout.focus(dialog)
        result = await dialog.future
        app.layout.focus(focused_before)

        if float_ in root_container.floats:
            root_container.floats.remove(float_)

        return result

    @bindings.add('c-n')
    def do_new_file(event=None):
        text_field.text = ""

    @bindings.add('c-c')
    def do_exit(event=None):
        get_app().exit()

    def do_time_date():
        text = datetime.datetime.now().isoformat()
        text_field.buffer.insert_text(text)

    def do_go_to():
        async def coroutine():
            dialog = TextInputDialog(title="Go to line",
                                     label_text="Line number:")

            line_number = await show_dialog_as_float(dialog)

            try:
                line_number = int(line_number)
            except ValueError:
                show_message("Invalid line number")
            else:
                text_field.buffer.cursor_position = text_field.buffer.document.translate_row_col_to_index(
                    line_number - 1, 0)

        ensure_future(coroutine())

    def do_undo():
        text_field.buffer.undo()

    def do_cut():
        data = text_field.buffer.cut_selection()
        get_app().clipboard.set_data(data)

    def do_copy():
        data = text_field.buffer.copy_selection()
        get_app().clipboard.set_data(data)

    def do_delete():
        text_field.buffer.cut_selection()

    def do_find():
        start_search(text_field.control)

    def do_find_next():
        search_state = get_app().current_search_state

        cursor_position = text_field.buffer.get_search_position(
            search_state, include_current_position=False)
        text_field.buffer.cursor_position = cursor_position

    def do_paste():
        text_field.buffer.paste_clipboard_data(get_app().clipboard.get_data())

    def do_select_all():
        text_field.buffer.cursor_position = 0
        text_field.buffer.start_selection()
        text_field.buffer.cursor_position = len(text_field.buffer.text)

    @bindings.add("c-e")
    def do_eval(event=None):
        if ApplicationState.context is None or ApplicationState.player is None:
            show_message("Error",
                         "Cannot evaluate because no context is defined")

            return

        code = text_field.buffer.text

        try:
            script = ApplicationState.context.script

            now = ApplicationState.player.get_time()

            ctx = ApplicationState.context.fork(cursor=now)

            val = script.eval(code, context=ctx)

            if val is not None and isinstance(val, Music):
                pl = InteractivePlayer(lambda: val.expand(ctx),
                                       ApplicationState.player,
                                       realtime=True)

                ApplicationState.interactive_players.append(pl)

                create_task(pl.start())
        except BaseException as e:
            if hasattr(e, 'message'):
                show_message("Eval Error", str(cast(Any, e).message))
            else:
                show_message("Eval Error", str(e))

    @bindings.add("c-s")
    def do_mute_players(event=None):
        for p in ApplicationState.interactive_players:
            create_task(p.stop())

        ApplicationState.interactive_players = []

    def do_status_bar():
        ApplicationState.show_status_bar = not ApplicationState.show_status_bar

    #
    # The menu container.
    #

    root_container = MenuContainer(
        body=body,
        menu_items=[
            MenuItem(
                "File",
                children=[
                    MenuItem("New...", handler=do_new_file),
                    MenuItem("Open...", handler=do_open_file),
                    MenuItem("Save"),
                    MenuItem("Save as..."),
                    MenuItem("-", disabled=True),
                    MenuItem("Exit", handler=do_exit),
                ],
            ),
            MenuItem(
                "Edit",
                children=[
                    MenuItem("Undo", handler=do_undo),
                    MenuItem("Cut", handler=do_cut),
                    MenuItem("Copy", handler=do_copy),
                    MenuItem("Paste", handler=do_paste),
                    MenuItem("Delete", handler=do_delete),
                    MenuItem("-", disabled=True),
                    MenuItem("Find", handler=do_find),
                    MenuItem("Find next", handler=do_find_next),
                    MenuItem("Replace"),
                    MenuItem("Go To", handler=do_go_to),
                    MenuItem("Select All", handler=do_select_all),
                    MenuItem("Time/Date", handler=do_time_date),
                ],
            ),
            MenuItem("View",
                     children=[
                         MenuItem("Status Bar", handler=do_status_bar),
                     ]),
            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,
    )

    style = Style.from_dict({
        "status": "reverse",
        "shadow": "bg:#440044",
    })

    layout = Layout(root_container, focused_element=text_field)

    application = Application(
        layout=layout,
        enable_page_navigation_bindings=True,
        style=style,
        mouse_support=True,
        full_screen=True,
    )

    return application, text_field
예제 #14
0
             SPACE,
             QLabel("<F5=Run>"),
             SPACE,
             QLabel("<CTRL+R=Run>"),
         ],
         style="bg:#00AAAA fg:white bold",
         height=1,
     ),
 ]),
 menu_items=[
     MenuItem(
         " File ",
         children=[
             MenuItem("New...", handler=new),
             MenuItem("Open...", handler=open_file),
             MenuItem("Save", handler=save_file),
             MenuItem("Save as...", handler=save_as_file),
             MenuItem("-", disabled=True),
             MenuItem("Exit", handler=exit),
         ],
     ),
     MenuItem(
         " Edit ",
         children=[
             MenuItem("Undo", handler=undo),
             MenuItem("Cut", handler=cut),
             MenuItem("Copy", handler=copy),
             MenuItem("Paste", handler=paste),
             MenuItem("Delete", handler=delete),
             MenuItem("-", disabled=True),
             MenuItem("Go To", handler=goto),
예제 #15
0
파일: main.py 프로젝트: lofyer/lifegame
 MenuItem(
     text="Action",
     children=[
         MenuItem("Rest",
                  children=[
                      MenuItem("Sleep"),
                      MenuItem("Snap"),
                  ]),
         MenuItem("-", disabled=True),
         MenuItem(
             "Learn",
             children=[
                 MenuItem("Professional"),
                 MenuItem("Life"),
                 MenuItem(
                     "Something else..",
                     children=[
                         MenuItem("A"),
                         MenuItem("B"),
                         MenuItem("C"),
                         MenuItem("D"),
                         MenuItem("E"),
                     ],
                 ),
             ],
         ),
         MenuItem("Save"),
         MenuItem("Save as..."),
         MenuItem("-", disabled=True),
         MenuItem("Exit", handler=do_exit),
     ],
 ),
예제 #16
0
        ], align='CENTER', padding=3),
        style='class:button-bar',
        height=3,
    ),
])

root_container = MenuContainer(body=root_container, menu_items=[
    MenuItem('File', children=[
        MenuItem('New'),
        MenuItem('Open', children=[
            MenuItem('From file...'),
            MenuItem('From URL...'),
            MenuItem('Something else..', children=[
                MenuItem('A'),
                MenuItem('B'),
                MenuItem('C'),
                MenuItem('D'),
                MenuItem('E'),
            ]),
        ]),
        MenuItem('Save'),
        MenuItem('Save as...'),
        MenuItem('-', disabled=True),
        MenuItem('Exit', handler=do_exit),
        ]),
    MenuItem('Edit', children=[
        MenuItem('Undo'),
        MenuItem('Cut'),
        MenuItem('Copy'),
        MenuItem('Paste'),
        MenuItem('Delete'),
        MenuItem('-', disabled=True),
예제 #17
0
    def __init__(self):
        self.console = TextArea(
            scrollbar=True,
            focusable=False,
            line_numbers=False,
            lexer=PygmentsLexer(SerTermLexer),
        )

        self.cmd_line = TextArea(
            multiline=False,
            prompt=HTML('<orange>>>> </orange>'),
            style='bg: cyan',
            accept_handler=self.cmd_line_accept_handler,
            history=FileHistory('.ser-term-hist'),
            auto_suggest=AutoSuggestFromHistory(),
        )

        self.root = HSplit([
            self.console,
            self.cmd_line,
        ])

        self.menu = MenuContainer(
            self.root,
            menu_items=[
                MenuItem(text='[F2] Open port', handler=self.key_uart_open),
                MenuItem(text='[F3] Close port', handler=self.key_uart_close),
                MenuItem(
                    text='[F4] Baudrate',
                    children=[
                        MenuItem(
                            str(bd),
                            handler=(lambda bd: lambda: self.baudrate_update(
                                baudrate=int(bd)))(bd)) for bd in BAUDRATE
                    ],
                ),
                MenuItem(
                    text='[F5] End line',
                    children=[
                        MenuItem('LF   \\n',
                                 handler=lambda: self.end_line_update('\n')),
                        MenuItem('CR   \\r',
                                 handler=lambda: self.end_line_update('\r')),
                        MenuItem('CRLF \\r\\n',
                                 handler=lambda: self.end_line_update('\r\n')),
                    ],
                ),
                MenuItem(text='[F10] Quit', handler=self.key_application_quit),
            ],
        )

        if args.end_line == 'LF':
            self.end_line = '\n'
        elif args.end_line == 'CR':
            self.end_line = '\r'
        else:
            self.end_line = '\r\n'
        self.end_line_update()
        self.baudrate_update()

        self.layout = Layout(self.menu)
        self.layout.focus(self.root)

        self.key_bindings.add('s-tab')(focus_previous)
        self.key_bindings.add('tab')(focus_next)

        self.app = Application(
            layout=self.layout,
            key_bindings=self.key_bindings,
            full_screen=True,
            mouse_support=True,
        )
예제 #18
0
def get_column_menu_container(
    table_name,
    all_table_details,
    column_details,
    column_details_labels,
    column_details_container,
    bindings,
):
    # all possible column attributes
    all_column_attributes = {}
    for attr_key, all_attr_vals in column_attributes.items():
        if attr_key == "type":
            for _table_name_, table_details in all_table_details.items():
                if _table_name_ == table_name:
                    continue

                # Add all previous `table_name.table_column` as possible attribute values for columns of this table.
                table_column_attrs = [
                    f"{_table_name_}.{_column_name}"
                    for _column_name in table_details["column_names"]
                ]

                # Update all attr_vals with `table_name.table_column` to the existing default attribute values.
                all_attr_vals += table_column_attrs

        all_column_attributes[attr_key] = all_attr_vals

    # Placeholder Container for the column update menu.
    column_menu_container_body = TextArea(text="", multiline=True, focusable=False, read_only=True)

    class Focus(object):
        def __init__(self):
            self.menu = None

    focus_obj = Focus()

    column_menu_container = Frame(
        body=MenuContainer(
            key_bindings=bindings,
            body=column_menu_container_body,
            menu_items=[
                MenuItem(
                    text="EDIT COLUMN DETAILS",
                    children=[
                        MenuItem(
                            text=column_name,
                            children=[
                                MenuItem(
                                    text=attr_key,
                                    children=[
                                        MenuItem(
                                            text=f"{attr_val}",
                                            handler=partial(
                                                update_label,
                                                column_details=column_details,
                                                column_details_labels=column_details_labels,
                                                column_name=column_name,
                                                attr_key=attr_key,
                                                attr_val=attr_val,
                                                focus_obj=focus_obj,
                                            ),
                                        )
                                        for attr_val in all_column_attributes[attr_key]
                                    ],
                                )
                                for attr_key, attr_label in column_attrs.items()
                            ],
                        )
                        for column_name, column_attrs in column_details_labels.items()
                    ],
                )
            ],
        )
    )

    focus_obj.menu = column_menu_container

    return column_details, column_menu_container_body, column_menu_container
 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,
     )