Esempio n. 1
0
def edit_multiline(default_text=""):
    kb = KeyBindings()

    @kb.add('c-q')
    @kb.add('escape', 'enter')
    def exit_(event):
        """
        Pressing Ctrl-Q, Alt+Enter or Esc + Enter will exit the editor.
        """
        event.app.exit(textf.text)

    @kb.add('c-c')
    def do_copy(event):
        data = textf.buffer.copy_selection()
        get_app().clipboard.set_data(data)

    @kb.add('c-x', eager=True)
    def do_cut(event):
        data = textf.buffer.cut_selection()
        get_app().clipboard.set_data(data)

    @kb.add('c-z')
    def do_undo(event):
        textf.buffer.undo()

    @kb.add('c-y')
    def do_redo(event):
        textf.buffer.redo()

    @kb.add('c-a')
    def do_select_all(event):
        textf.buffer.cursor_position = 0
        textf.buffer.start_selection()
        textf.buffer.cursor_position = len(textf.buffer.text)
        update_stored_pos(None)

    @kb.add('c-v')
    def do_paste(event):
        textf.buffer.paste_clipboard_data(get_app().clipboard.get_data())

    @kb.add('left')
    def kb_left(event):
        textf.buffer.selection_state = None
        if textf.buffer.cursor_position != 0 and textf.text[
                textf.buffer.cursor_position - 1] == '\n':
            textf.buffer.cursor_up()
            textf.buffer.cursor_right(len(textf.text))
        else:
            textf.buffer.cursor_left()
        update_stored_pos(None)

    @kb.add('right')
    def kb_right(event):
        textf.buffer.selection_state = None
        if textf.buffer.cursor_position < len(textf.text) and textf.text[
                textf.buffer.cursor_position] == '\n':
            textf.buffer.cursor_down()
            textf.buffer.cursor_left(len(textf.text))

        else:
            textf.buffer.cursor_right()
        update_stored_pos(None)

    @kb.add('home')
    def kb_home(event):
        textf.buffer.selection_state = None
        width = getTermWidth()
        doc = textf.document
        if textf.buffer.cursor_position == doc._line_start_indexes[
                cursor_row()] + int(cursor_col() / width) * width:
            textf.buffer.cursor_position = doc._line_start_indexes[
                cursor_row()]
        else:
            textf.buffer.cursor_position = doc._line_start_indexes[
                cursor_row()] + int(cursor_col() / width) * width
        update_stored_pos(None)

    @kb.add('end')
    def kb_end(event):
        textf.buffer.selection_state = None
        width = getTermWidth()
        doc = textf.document
        row = cursor_row()
        if textf.buffer.cursor_position == doc._line_start_indexes[row] + (
                int(cursor_col() / width) + 1) * width - 1:
            textf.buffer.cursor_position = doc._line_start_indexes[row] + len(
                doc.current_line)
        else:
            textf.buffer.cursor_position = min(
                doc._line_start_indexes[row] +
                (int(cursor_col() / width) + 1) * width - 1,
                doc._line_start_indexes[row] + len(doc.current_line))
        update_stored_pos(None)

    @kb.add('up')
    def kb_up(event):
        textf.freezestore = True
        width = getTermWidth()
        doc = textf.document
        textf.buffer.selection_state = None
        col = cursor_col()
        row = cursor_row()
        if width > 9000:  # A failsafe in case the terminal size is incorrectly detected
            textf.buffer.cursor_up()
            return

        if col >= width:  # Move one row up staying on the same line
            textf.buffer.cursor_position = doc._line_start_indexes[row] + int(
                col / width - 1) * width + textf.stored_cursor_pos
        elif row >= 1:  # Moving up to a different line
            prevlinelen = len(doc.lines[row - 1])

            textf.buffer.cursor_position = min(
                doc._line_start_indexes[row] - 1,
                doc._line_start_indexes[row - 1] +
                int(prevlinelen / width) * width + textf.stored_cursor_pos)
        else:  # Cursor is on the first row of first line
            textf.buffer.cursor_position = 0
            textf.freezestore = False
            update_stored_pos(None)

    @kb.add('down')
    def kb_down(event):
        textf.freezestore = True
        width = getTermWidth()
        doc = textf.document
        textf.buffer.selection_state = None
        col = cursor_col()
        row = cursor_row()
        nextlinelen = len(doc.lines[row +
                                    1]) if row < len(doc.lines) - 1 else -1
        if width > 9000:  # A failsafe in case the terminal size is incorrectly detected
            textf.buffer.cursor_down()
            return

        if col <= len(doc.current_line
                      ) - width:  # Move one row down staying on the same line
            textf.buffer.cursor_position = doc._line_start_indexes[row] + int(
                col / width + 1) * width + textf.stored_cursor_pos
        elif nextlinelen < 0:  # Move to the very end
            textf.buffer.cursor_position = len(textf.text)
            textf.freezestore = False
            update_stored_pos(None)
        # Move to the end of the same line the cursor is on
        elif col != len(doc.lines[row]) and textf.stored_cursor_pos >= len(
                doc.lines[row]) - int(len(doc.lines[row]) / width) * width:
            textf.buffer.cursor_position = doc._line_start_indexes[row + 1] - 1
        else:  # Move to a different line
            textf.buffer.cursor_position = min(
                doc._line_start_indexes[row + 1] + nextlinelen,
                doc._line_start_indexes[row + 1] + textf.stored_cursor_pos)

    textf = TextArea()
    bottom_bar_text = FormattedTextControl(
        text=
        '\nCurrently editing. Press Ctrl+Q, Alt+Enter or Esc + Enter to exit.')
    bottom_bar = Window(content=bottom_bar_text)

    root_container = HSplit([
        textf,
        bottom_bar,
    ])

    layout = Layout(root_container)

    app = Application(key_bindings=kb,
                      layout=layout,
                      enable_page_navigation_bindings=True,
                      full_screen=False)
    textf.freezestore = False
    textf.text = default_text
    textf.buffer.cursor_position = len(textf.buffer.text)

    # Find the row the cursor is at
    # My own function, in fear of race conditions
    def cursor_row():
        i = 0
        while i < len(
                textf.document._line_start_indexes
        ) and textf.buffer.cursor_position >= textf.document._line_start_indexes[
                i]:
            i += 1
        return i - 1

    # Find the column the cursor is at
    # There is a built-in function, but I think there's some kind of a race condition if it's used
    def cursor_col():
        i = textf.buffer.cursor_position - 1
        while i >= 0 and textf.text[i] != '\n':
            i -= 1
        return textf.buffer.cursor_position - i - 1

    def update_stored_pos(event):
        if not event:
            textf.freezestore = False
        if textf.freezestore:
            textf.freezestore = False
            return
        width = getTermWidth()
        col = cursor_col()
        textf.stored_cursor_pos = col - int(col / width) * width

    textf.buffer.on_cursor_position_changed += update_stored_pos
    update_stored_pos(None)

    text = app.run()

    clear_lines(1)

    return text
Esempio n. 2
0
@kb.add("c-a")
def select_all(event=None):
    code.buffer.cursor_position = 0
    code.buffer.start_selection()
    code.buffer.cursor_position = len(code.buffer.text)


def insert_time_and_date():
    code.buffer.insert_text(datetime.now().isoformat())


search_toolbar = SearchToolbar()
code = TextArea(
    scrollbar=True,
    wrap_lines=False,
    focus_on_click=True,
    line_numbers=True,
    search_field=search_toolbar,
)
code.window.right_margins[0].up_arrow_symbol = "↑"  # type: ignore
code.window.right_margins[0].down_arrow_symbol = "↓"  # type: ignore


class CodeFrame:
    """A custom frame for the quick python code container to match desired styling"""
    def __init__(
        self,
        body: AnyContainer,
        title: AnyFormattedText = "",
        style: str = "",
        width: AnyDimension = None,
Esempio n. 3
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)),
            ])
Esempio n. 4
0
    Pressing Ctrl-Q will exit the user interface.

    Setting a return value means: quit the event loop that drives the user
    interface and return this value from the `Application.run()` call.
    """
    event.app.exit()


# Now we add an event handler that captures change events to the buffer on the
# left. If the text changes over there, we'll update the buffer on the right.

right_buffer = Buffer()  # Output buffer.

input_field = TextArea(height=1,
                       prompt='>>> ',
                       style='class:input-field',
                       multiline=False,
                       wrap_lines=False)


# Attach accept handler to the input field. We do this by assigning the
# handler to the `TextArea` that we created earlier. it is also possible to
# pass it to the constructor of `TextArea`.
# NOTE: It's better to assign an `accept_handler`, rather then adding a
#       custom ENTER key binding. This will automatically reset the input
#       field and add the strings to the history.
def accept(buff):
    # Evaluate "calculator" expression.
    try:
        output = '\n\nIn:  {}\nOut: {}'.format(
            input_field.text,
Esempio n. 5
0
class FormatText(Processor):
    def apply_transformation(self, ti):
        try:
            fragments = to_formatted_text(
                HTML(fragment_list_to_text(ti.fragments)))
            return Transformation(fragments)
        except Exception:
            return Transformation(ti.fragments)


# todo: make textbuffer fixed length (for example: len = max(10000))

_output_window = TextArea(
    complete_while_typing=False,
    scrollbar=True,
    focus_on_click=True,
    line_numbers=True,
    input_processors=[FormatText()],
)
output = _output_window.buffer

kb = KeyBindings()


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


_current_menu = None
Esempio n. 6
0
def accept_yes():
    get_app().exit(result=True)


def accept_no():
    get_app().exit(result=False)


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


yes_button = Button(text='Yes', handler=accept_yes)
no_button = Button(text='No', handler=accept_no)
textfield = TextArea()
checkbox1 = Checkbox(text='Checkbox')
checkbox2 = Checkbox(text='Checkbox')

radios = RadioList(values=[
    ('Red', 'red'),
    ('Green', 'green'),
    ('Blue', 'blue'),
    ('Orange', 'orange'),
    ('Yellow', 'yellow'),
    ('Purple', 'Purple'),
    ('Brown', 'Brown'),
])

animal_completer = WordCompleter([
    'alligator',
Esempio n. 7
0
    def __init__(self, first_game, engine):

        self.completer = CustomCompleter(['start'])
        self.elements = {
            'board':
            Window(FormattedTextControl(
                ANSI(show_board(chess.STARTING_BOARD_FEN))),
                   width=35,
                   height=13),
            'input':
            TextArea(height=1,
                     prompt='>>> ',
                     style='class:input-field',
                     width=80,
                     completer=self.completer),
            'p1':
            Window(FormattedTextControl(ANSI('Games')),
                   width=31,
                   height=13,
                   wrap_lines=True),
            'p2':
            Window(FormattedTextControl(ANSI('Legal Moves')),
                   width=31,
                   height=13,
                   wrap_lines=True),
        }

        self.frames = {}
        self.frames['board'] = Float(Frame(self.elements['board'],
                                           style='bg:#2e2e2e #ffffff'),
                                     top=10)
        self.frames['input'] = Float(Frame(self.elements['input'],
                                           style='bg:#2e2e2e #ffffff'),
                                     top=30)
        self.frames['p1'] = Float(Frame(self.elements['p1'],
                                        style='bg:#1e1e1e #ffffff'),
                                  top=10,
                                  left=10)
        self.frames['p2'] = Float(Frame(self.elements['p2'],
                                        style='bg:#1e1e1e #ffffff'),
                                  top=10,
                                  right=10)

        self.body = FloatContainer(content=Window(FormattedTextControl('')),
                                   floats=[v for k, v in self.frames.items()])
        self.kb = KeyBindings()

        self.app = Application(layout=Layout(
            self.body, focused_element=self.elements['input']),
                               key_bindings=self.kb,
                               full_screen=True)
        self.set_kb()

        self.game = first_game
        self.board = first_game.board()
        self.moves = list(first_game.main_line())
        self.engine = engine

        self.state = 'init'
        self.now = 0
        self.N = len(self.moves)
        self.chain = []
        self.selected = None
        self.quit = False
Esempio n. 8
0
#!/usr/bin/env python
"""
A simple example of a a text area displaying "Hello World!".
"""
from prompt_toolkit.application import Application
from prompt_toolkit.key_binding import KeyBindings
from prompt_toolkit.layout import Layout
from prompt_toolkit.widgets import Box, Frame, TextArea

# Layout for displaying hello world.
# (The frame creates the border, the box takes care of the margin/padding.)
root_container = Box(
    Frame(
        TextArea(
            text="Hello world!\nPress control-c to quit.",
            width=40,
            height=10,
        )), )
layout = Layout(container=root_container)

# Key bindings.
kb = KeyBindings()


@kb.add("c-c")
def _(event):
    " Quit when control-c is pressed. "
    event.app.exit()


# Build a main application object.
Esempio n. 9
0

def button3_clicked():
    text_area.text = 'Button 3 clicked'


def exit_clicked():
    get_app().exit()


# All the widgets for the UI.
button1 = Button('Button 1', handler=button1_clicked)
button2 = Button('Button 2', handler=button2_clicked)
button3 = Button('Button 3', handler=button3_clicked)
button4 = Button('Exit', handler=exit_clicked)
text_area = TextArea(focusable=True)

# Combine all the widgets in a UI.
# The `Box` object ensures that padding will be inserted around the containing
# widget. It adapts automatically, unless an explicit `padding` amount is given.
root_container = Box(
    HSplit([
        Label(text='Press `Tab` to move the focus.'),
        VSplit([
            Box(body=HSplit([button1, button2, button3, button4], padding=1),
                padding=1,
                style='class:left-pane'),
            Box(body=Frame(text_area), padding=1, style='class:right-pane'),
        ]),
    ]), )
Esempio n. 10
0
def button_handler():
    global info
    info = False
    layout.focus(input_field)


dialog = Dialog(title="Info",
                body=Label(text="...", dont_extend_height=True),
                buttons=[
                    Button(text="OK", handler=button_handler),
                ])

search_field = SearchToolbar()
input_field = TextArea(height=1,
                       prompt='/',
                       style='class:input-field',
                       multiline=False,
                       wrap_lines=False,
                       search_field=search_field)
input_field.accept_handler = filterTable

table = Window(content=FormattedTextControl(
    text=getFormattedTable(selected, filteredList),
    get_cursor_position=GetCursorPosition()))

root_container = HSplit([
    table,
    ConditionalContainer(content=input_field, filter=isSearching),
    ConditionalContainer(content=dialog, filter=showInfo)
])
layout = Layout(container=root_container)
Esempio n. 11
0
        for cmd in cmds:
            t3 = cmd.rstrip().partition('(')
            x = t3[0]
            args = t3[2].rstrip(')').partition(',')
            if x in ("stream", "change"):
                dest = capture1
                if args[0] == "2":
                    dest = capture2
                _print(dest, ('\ninput[' + args[0] + '] = ' + args[2] + '\n'))
            elif len(cmd) > 0:
                myprint('^^' + cmd + '\n')
    elif len(text) > 0:
        myprint(text + '\n')


capture1 = TextArea(style='class:capture-field', height=2)
capture2 = TextArea(style='class:capture-field', height=2)
captures = VSplit([capture1, capture2])
output_field = TextArea(style='class:output-field', text=druid_intro)
statusbar = Window(height=1,
                   char='/',
                   style='class:line',
                   content=FormattedTextControl(text='druid////'),
                   align=WindowAlign.RIGHT)
input_field = TextArea(height=1,
                       prompt='> ',
                       multiline=False,
                       wrap_lines=False,
                       style='class:input-field')
container = HSplit([captures, output_field, statusbar, input_field])
Esempio n. 12
0
    commandWindowFrame.title = title


#listens cursor changes in pods list
def podListCursorChanged(buffer):
    #when position changes, save cursor position to state
    state.cursor_line = buffer.document.cursor_position_row

    if args.no_dynamic_title == False:
        setCommandWindowTitle()


#pods window
podListArea = TextArea(text="",
                       multiline=True,
                       wrap_lines=False,
                       scrollbar=enableScrollbar,
                       lexer=lexer.ResourceWindowLexer(),
                       read_only=True)

#add listener to cursor position changed
podListArea.buffer.on_cursor_position_changed = Event(podListArea.buffer,
                                                      podListCursorChanged)
podListArea.buffer.name = WindowName.resource
podListArea.window.cursorline = to_filter(True)
podListAreaFrame = Frame(podListArea, title="Pods", width=podListWindowSize)

left_container = HSplit([
    upper_left_container,
    #HorizontalLine(),
    #Window(height=1, char='-'),
    podListAreaFrame
Esempio n. 13
0
from __future__ import unicode_literals
import prompt_toolkit
from prompt_toolkit.application import Application
from prompt_toolkit.eventloop import use_asyncio_event_loop
from prompt_toolkit.key_binding import KeyBindings
from prompt_toolkit.layout import Layout, VSplit, HSplit
from prompt_toolkit.widgets import Box, Button, Frame, TextArea
import asyncio
import time

lineCount = 6
debugAxis = 2
debugSleep = 0.2
bytesSentText = TextArea(text="")
bytesReceivedText = TextArea(text="")


def handleHome():
    # time.sleep(debugSleep)
    sendHome(debugAxis)


def goAway():
    goAway(debugAxis)


def debugAxisX():
    debugAxisX()


def debugAxisY():
Esempio n. 14
0
    "dim": "#444",
    "bold": "bold",
    "sidebar.label": "#aaa",
    "sidebar.label selected": "#fff bold",
    "sidebar.label seldim": "bg:#444 #fff bold",
    "sidebar.modified": "bg:orange white bold",
    "status": "reverse",
    "topbar": "bg:#fff bg:blue",
    "notification": "#000",
})

# Text editor
text_window = TextArea(
    text=state.current_text,
    scrollbar=True,
    line_numbers=True,
    multiline=True,
    width=Dimension(min=24),
    focus_on_click=True,
)


def save_current_note():
    """ Save the current note """
    text = text_window.document.text or ""

    if not state.current_note:
        return

    if state.current_note.get("_INSERT_FLAG"):
        note_id = db.insert(
            (state.current_note["title"], text, state.current_note["ts"]))
Esempio n. 15
0
#!/usr/bin/env python
"""
Example usage of 'print_container', a tool to print
any layout in a non-interactive way.
"""
from prompt_toolkit.shortcuts import print_container
from prompt_toolkit.widgets import Frame, TextArea

print_container(
    Frame(
        TextArea(text="Hello world!\n"),
        title="Stage: parse",
    )
)
Esempio n. 16
0
def main():
    # The layout.
    search_field = SearchToolbar()  # For reverse search.

    output_field = TextArea(style='class:output-field', text=help_text)
    input_field = TextArea(
        height=1, prompt='>>> ', style='class:input-field', multiline=False,
        wrap_lines=False, search_field=search_field)

    container = HSplit([
        output_field,
        Window(height=1, char='-', style='class:line'),
        input_field,
        search_field,
    ])

    # Attach accept handler to the input field. We do this by assigning the
    # handler to the `TextArea` that we created earlier. it is also possible to
    # pass it to the constructor of `TextArea`.
    # NOTE: It's better to assign an `accept_handler`, rather then adding a
    #       custom ENTER key binding. This will automatically reset the input
    #       field and add the strings to the history.
    def accept(buff):
        # Evaluate "calculator" expression.
        try:
            output = '\n\nIn:  {}\nOut: {}'.format(
                input_field.text,
                eval(input_field.text))  # Don't do 'eval' in real code!
        except BaseException as e:
            output = '\n\n{}'.format(e)
        new_text = output_field.text + output

        # Add text to output buffer.
        output_field.buffer.document = Document(
            text=new_text, cursor_position=len(new_text))

    input_field.accept_handler = accept

    # The key bindings.
    kb = KeyBindings()

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

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

    # Run application.
    application = Application(
        layout=Layout(container, focused_element=input_field),
        key_bindings=kb,
        style=style,
        mouse_support=True,
        full_screen=True)

    application.run()
Esempio n. 17
0
    def __init__(self, config, out_queue, state=TaskState()):
        self.config = config
        tui_config = config['tui']
        self.tui_config = tui_config
        self.out_queue = out_queue

        def commandHandler(buffer):
            #check incoming command
            cmdString = buffer.text
            #executeCommand(cmdString)
            pass

        def commandPrompt(line_number, wrap_count):
            return "command> "

        ########################################################################

        kb = KeyBindings()

        @kb.add('c-d')
        def exit_(event):
            """
            Pressing Esc will exit the user interface.

            Setting a return value means: quit the event loop that drives the user
            interface and return this value from the `CommandLineInterface.run()` call.
            """
            event.app.exit()

        @kb.add('tab')
        def tab_(event):
            focus_next(event)

        @kb.add('s-tab')
        def stab_(event):
            focus_previous(event)

        @kb.add('s-right')
        def next_tab(event):
            state.next_tab()
            event.app.invalidate()

        @kb.add('s-left')
        def next_tab(event):
            state.prev_tab()
            event.app.invalidate()

        orders_kb = KeyBindings()

        @orders_kb.add('f5')
        def _(event):
            #command = ('refresh', something...)
            #self.out_queue.put_nowait(command)
            pass

        ########################################################################

        outputArea = TextArea(
            text="",
            multiline=True,
            wrap_lines=False,
            #lexer=lexer.OutputAreaLexer(),
            #scrollbar=enableScrollbar,
            style='class:output-field',
            read_only=True)

        content_container = Frame(outputArea, title="Output")

        log_container = Frame(
            Window(
                BufferControl(
                    buffer=Buffer(name='logger_buffer', read_only=True),
                    input_processors=[FormatTextHTML()],
                ),
                right_margins=[ScrollbarMargin(display_arrows=True)
                               ],  # low-level scrollbar
            ),
            title='Log',
            height=8,
        )

        command_container = TextArea(text="",
                                     multiline=False,
                                     accept_handler=commandHandler,
                                     get_line_prefix=commandPrompt)

        commandWindowFrame = Frame(
            command_container,
            title=
            "TuiTerminal (Ctrl-D to exit, Tab to switch focus and refresh UI, 'help' for help)",
            height=4)

        root_container = HSplit(
            [content_container, log_container, commandWindowFrame])

        layout = Layout(root_container, focused_element=command_container)

        style = Style.from_dict({
            'output-field': 'bg:#101010',
            'frame.border': 'SteelBlue',
            'frame.label': 'PowderBlue',
        })

        application = Application(
            layout=layout,
            key_bindings=kb,
            style=style,
            full_screen=tui_config.getboolean('full_screen'),
            mouse_support=tui_config.getboolean('mouse_support'),
            #after_render=after_render,
        )

        self.application = application
Esempio n. 18
0

#buffer to store the user input
left_buffer = Buffer(accept_handler=runCommand,
                     multiline=False,
                     completer=mainCompleter(),
                     history=FileHistory('history.txt'),
                     complete_while_typing=True)

#input window, storing the user input buffer
left_window = Window(BufferControl(buffer=left_buffer))

#one of two regions used to store system ouput
responseOutput = TextArea(
    text="FTP Communication Responses(and commands)",
    scrollbar=True,
    line_numbers=True,
)

#region to display the system outputs
systemOutput = TextArea(
    text="System Output",
    scrollbar=True,
    line_numbers=True,
)


#function to append new text to the responce ouput text area
def printResponceOutput(text):
    currentText = responseOutput.document.text
    newText = currentText + "\n" + text
Esempio n. 19
0
 def _get_answer_widget(self):
     return TextArea(multiline=False)
Esempio n. 20
0
def progress_log_dialog(
    title: AnyFormattedText = "",
    text: AnyFormattedText = "",
    wait_text: str = "Wait",
    quit_text: str = "Quit",
    status_text: AnyFormattedText = "",
    run_callback: Callable[[
        Callable[[int], None], Callable[[str], None], Callable[
            [str], None], Callable[[dict], None], Callable[[], bool]
    ], None] = (lambda *a: None),
    style: Optional[BaseStyle] = None,
) -> Application[None]:
    """
    :param run_callback: A function that receives as input a `set_percentage`
        function and it does the work.
    """
    loop = get_event_loop()

    def wait_handler() -> None:
        pass

    def quit_handler() -> None:
        app = get_app()
        if not app.exited:
            app.exited = True
            app.exit(result=app.result)

    wait_button = Button(text=wait_text, handler=wait_handler)
    quit_button = Button(text=quit_text, handler=quit_handler)

    progressbar = ProgressBar()
    text_area = TextArea(
        focusable=False,
        # Prefer this text area as big as possible, to avoid having a window
        # that keeps resizing when we add text to it.
        height=D(preferred=10**10),
        width=D(preferred=10**10))
    status = Label(text=status_text)

    dialog = Dialog(
        title=title,
        body=HSplit([
            Box(Label(text=text)),
            Box(text_area, padding=D.exact(1)),
            Box(status, padding=D.exact(1)),
            progressbar,
        ]),
        buttons=[wait_button, quit_button],
        with_background=True,
    )
    app = _create_app(dialog, style)
    app.result = None
    app.exited = False

    def set_percentage(value: int) -> None:
        progressbar.percentage = int(value)
        app.invalidate()

    def log_text(text: str) -> None:
        loop.call_soon_threadsafe(text_area.buffer.insert_text, text)
        app.invalidate()

    def change_status(text: str) -> None:
        status.formatted_text_control.text = text
        app.invalidate()

    def set_result(new_result: dict) -> None:
        app.result = new_result

    def get_exited() -> bool:
        return app.exited

    # Run the callback in the executor. When done, set a return value for the
    # UI, so that it quits.
    def start() -> None:
        result = None
        try:
            result = run_callback(set_percentage, log_text, change_status,
                                  set_result, get_exited)
        finally:
            if not app.exited:
                app.exited = True
                app.exit(result=result)

    def pre_run() -> None:
        run_in_executor_with_context(start)

    app.pre_run_callables.append(pre_run)

    return app
Esempio n. 21
0
def main(role, addr, target, name, cert, ns, domain):

    cert_file, key_file = cssc(getcwd(), cert, cert.replace("pem", "key"))
    hash_str = self_hash(path=join(getcwd(), "atomic_p2p"))

    dashboard_text = "==================== Dashboard ====================\n"
    peer_text = "====================    Peer   ====================\n"
    device_text = "====================   Device   ====================\n"

    #dashboard_field = FormattedTextControl(ANSI(dashboard_text))
    dashboard_field = TextArea(text=dashboard_text)
    #peer_field = FormattedTextControl(ANSI(peer_text))
    peer_field = TextArea(text=peer_text)
    device_field = TextArea(text=device_text)
    input_field = TextArea(height=1, prompt=" > ", style="class:input-field")

    addr = addr.split(":")
    service = {
        "peer": None,
        "monitor": None,
        "device": None
    }
    service["peer"] = Peer(host=addr, name=name, role=role,
                           cert=(cert_file, key_file), _hash=hash_str, ns=ns,
                           output_field=[dashboard_field, peer_field])
    service["monitor"] = service["peer"].monitor
    service["device"] = Device(peer=service["peer"],
                               output_field=[dashboard_field, device_field])
    service["peer"].start()
    service["device"].start()

    if target is not None:
        service["peer"]._on_command(["join", target])
    elif domain is not None:
        if ns is None:
            service["peer"]._on_command(["join", domain])
        else:
            service["peer"]._on_command(["join", domain, ns])
    else:
        # printText("\x1b[1;33;40myou are first peer.\x1b[0m", output=[dashboard_field, peer_field])
        printText("you are first peer.", output=[dashboard_field, peer_field])

    left_split = HSplit([
        #Window(height=10, content=peer_field),
        peer_field,
        Window(height=1, char="-", style="class:line"),
        #Window(dashboard_field),
        dashboard_field,
        Window(height=1, char="-", style="class:line"),
        input_field
    ])
    right_split = HSplit([
        device_field
    ])

    container = VSplit([left_split, right_split])
    kb = KeyBindings()

    @kb.add("c-q")
    def _(event):
        for each in service:
            service[each].stop()
        event.app.exit()

    @kb.add("c-c")
    def _(event):
        input_field.text = ""

    @kb.add("enter")
    def _(event):
        cmd = input_field.text.split(" ")
        service_key = cmd[0].lower()
        if service_key in service:
            service[service_key]._on_command(cmd[1:])
        elif service_key == "help":
            helptips = "peer help            - See peer's help\n"\
                       "monitor help         - See monitor's help\n"\
                       "device help          - See defice's help\n"\
                       "exit/stop            - exit the whole program.\n"
            printText(helptips, output=dashboard_field)
        elif service_key == "exit" or service_key == "stop":
            for each in service:
                service[each].stop()
            event.app.exit()
        else:
            printText("command error , input 'help' to check the function.",
                      output=dashboard_field)
        input_field.text = ""

    prompt_style = Style([
        ("input_field", "bg:#000000 #ffffff"),
        ("line", "#004400")
    ])

    application = Application(
        layout=Layout(container, focused_element=input_field),
        key_bindings=kb,
        style=prompt_style,
        full_screen=True
    )
    application.run()
Esempio n. 22
0
def _(event):
    """
    Create new task/folder
    """
    global waiting_for_confirmation
    global prompt_window

    waiting_for_confirmation = True

    # Check if we are creating new task or folder
    if focus_folder:
        # We are creating a new folder
        input_field = TextArea(
            height=1,
            prompt="New folder: ",
            style="class:input-field",
            multiline=False,
            wrap_lines=False,
        )

        # Get new folder name
        def get_name(buff):
            global waiting_for_confirmation
            global prompt_window
            global left_window

            user_input = input_field.text
            if user_input:
                # Create new folder
                auth.create_folder(user_input)
                # Refresh folders
                load_folders()

            # Return to normal state
            waiting_for_confirmation = False
            prompt_window = Window()

    else:
        # We are creating a new task
        input_field = TextArea(
            height=1,
            prompt="New task: ",
            style="class:input-field",
            multiline=False,
            wrap_lines=False,
        )

        # Get new task name
        def get_name(buff):
            global waiting_for_confirmation
            global prompt_window
            user_input = input_field.text

            if user_input:
                # Create new task
                auth.create_task(user_input, folder2id[focus_index_folder])
                # Refresh tasks
                load_tasks()

            # Return to normal state
            waiting_for_confirmation = False
            prompt_window = Window()

    input_field.accept_handler = get_name

    prompt_window = input_field
    event.app.layout.focus(input_field)
Esempio n. 23
0
def preview_element(my_app: "sqlApp"):
    help_text = """
    Press Enter in the input box to page through the table.
    Alternatively, enter a filtering SQL statement and then press Enter
    to page through the results.
    """
    formatter = TabularOutputFormatter()
    input_buffer = Buffer(name="previewbuffer",
                          tempfile_suffix=".sql",
                          multiline=False)

    input_control = BufferControl(buffer=input_buffer,
                                  include_default_input_processors=False,
                                  preview_search=False)
    input_window = Window(input_control, )

    search_buffer = Buffer(name="previewsearchbuffer")
    search_field = SearchToolbar(search_buffer)
    output_field = TextArea(
        style="class:preview-output-field",
        text=help_text,
        height=D(preferred=50),
        search_field=search_field,
        wrap_lines=False,
        focusable=True,
        read_only=True,
        preview_search=True,
        input_processors=[
            ConditionalProcessor(
                processor=HighlightIncrementalSearchProcessor(),
                filter=has_focus("previewsearchbuffer")
                | has_focus(search_field.control),
            ),
            HighlightSelectionProcessor(),
        ])

    def refresh_results(window_height) -> bool:
        sql_conn = my_app.selected_object.conn

        if sql_conn.execution_status == executionStatus.FAIL:
            # Let's display the error message to the user
            output = sql_conn.execution_err
        else:
            crsr = sql_conn.cursor
            if crsr.description:
                cols = [col.name for col in crsr.description]
            else:
                cols = []
            if len(cols):
                sql_conn.status = connStatus.FETCHING
                res = sql_conn.async_fetchmany(size=window_height - 4)
                output = formatter.format_output(res, cols, format_name="psql")
                output = "\n".join(output)
            else:
                sql_conn.status = connStatus.IDLE
                output = "No rows returned\n"

        # Add text to output buffer.
        output_field.buffer.set_document(
            Document(text=output, cursor_position=0), True)

        return True

    def accept(buff: Buffer) -> bool:
        obj = my_app.selected_object
        sql_conn = obj.conn
        catalog = None
        schema = None
        # TODO: Verify connected
        if obj.parent is not None:
            if type(obj.parent).__name__ == "myDBSchema":
                schema = obj.parent.name
            elif type(obj.parent).__name__ == "myDBCatalog":
                catalog = obj.parent.name
            if obj.parent.parent is not None:
                if type(obj.parent.parent).__name__ == "myDBCatalog":
                    catalog = obj.parent.parent.name

        if catalog:
            catalog = (sql_conn.quotechar + "%s" +
                       sql_conn.quotechar) % catalog
        if schema:
            schema = (sql_conn.quotechar + "%s" + sql_conn.quotechar) % schema
        name = (sql_conn.quotechar + "%s" + sql_conn.quotechar) % obj.name
        identifier = ".".join(list(filter(None, [catalog, schema, obj.name])))
        query = sql_conn.preview_query(table=identifier,
                                       filter_query=buff.text,
                                       limit=my_app.preview_limit_rows)

        func = partial(
            refresh_results,
            window_height=output_field.window.render_info.window_height)
        # If status is IDLE, this is the first time we are executing.
        if sql_conn.query != query or sql_conn.status == connStatus.IDLE:
            # Exit the app to execute the query
            my_app.application.exit(result=["preview", query])
            my_app.application.pre_run_callables.append(func)
        else:
            # No need to exit let's just go and fetch
            func()
        return True  # Keep filter text

    input_buffer.accept_handler = accept

    def cancel_handler() -> None:
        sql_conn = my_app.selected_object.conn
        sql_conn.close_cursor()
        sql_conn.status = connStatus.IDLE
        input_buffer.text = ""
        output_field.buffer.set_document(
            Document(text=help_text, cursor_position=0), True)
        my_app.show_preview = False
        my_app.show_sidebar = True
        my_app.application.layout.focus(input_buffer)
        my_app.application.layout.focus("sidebarbuffer")
        return None

    cancel_button = Button(text="Done", handler=cancel_handler)

    container = HSplit([
        Box(body=VSplit([input_window, cancel_button], padding=1),
            padding=1,
            style="class:preview-input-field"),
        Window(height=1, char="-", style="class:preview-divider-line"),
        output_field,
        search_field,
    ])

    frame = Shadow(body=Frame(title="Table Preview",
                              body=container,
                              style="class:dialog.body",
                              width=D(preferred=180, min=30),
                              modal=True))

    return ConditionalContainer(content=frame,
                                filter=ShowPreview(my_app) & ~is_done)
Esempio n. 24
0
    )


# Global key bindings
kb = KeyBindings()

top_bar = Window(
    height=1,
    content=FormattedTextControl(get_topbar_text),
    align=WindowAlign.CENTER,
    style="class:topbar",
)
text_window = TextArea(
    text="",
    multiline=True,
    wrap_lines=True,
    focusable=True,
    scrollbar=True,
    line_numbers=True,
)
title_bar = Window(
    FormattedTextControl(get_statusbar_upper_text),
    align=WindowAlign.CENTER,
    style="class:notification",
    height=1,
)
status_bar = VSplit(
    [
        Window(
            FormattedTextControl(
                HTML(
                    'Press <style bg="blue"><b>F2</b></style> or <style bg="blue"><b>Ctrl-R</b></style> to set a title'
Esempio n. 25
0
def login_prompt(my_app: "sqlApp"):
    def ok_handler() -> None:
        my_app.application.layout.focus(uidTextfield)
        obj = my_app.selected_object
        try:
            obj.conn.connect(username=uidTextfield.text,
                             password=pwdTextfield.text)
            # Query the type of back-end and instantiate an appropriate class
            dbms = obj.conn.get_info(SQLGetInfo.SQL_DBMS_NAME)
            # Now clone object
            cls = connWrappers[dbms] if dbms in connWrappers.keys(
            ) else sqlConnection
            newConn = cls(dsn=obj.conn.dsn,
                          conn=obj.conn.conn,
                          username=obj.conn.username,
                          password=obj.conn.password)
            obj.conn.close()
            newConn.connect()
            obj.conn = newConn
            my_app.active_conn = obj.conn
            # OG some thread locking may be needed here
            obj.expand()
        except ConnectError as e:
            msgLabel.text = "Connect failed"
        else:
            msgLabel.text = ""
            my_app.show_login_prompt = False
            my_app.show_sidebar = True
            my_app.application.layout.focus("sidebarbuffer")

        uidTextfield.text = ""
        pwdTextfield.text = ""

    def cancel_handler() -> None:
        msgLabel.text = ""
        my_app.application.layout.focus(uidTextfield)
        my_app.show_login_prompt = False
        my_app.show_sidebar = True
        my_app.application.layout.focus("sidebarbuffer")

    def accept(buf: Buffer) -> bool:
        my_app.application.layout.focus(ok_button)
        return True

    ok_button = Button(text="OK", handler=ok_handler)
    cancel_button = Button(text="Cancel", handler=cancel_handler)

    pwdTextfield = TextArea(multiline=False,
                            password=True,
                            accept_handler=accept)
    uidTextfield = TextArea(multiline=False,
                            password=False,
                            accept_handler=accept)
    msgLabel = Label(text="",
                     dont_extend_height=True,
                     style="class:frame.label")
    msgLabel.window.align = WindowAlign.CENTER
    dialog = Dialog(
        title="Server Credentials",
        body=HSplit(
            [
                Label(text="Username ", dont_extend_height=True), uidTextfield,
                Label(text="Password", dont_extend_height=True), pwdTextfield,
                msgLabel
            ],
            padding=D(preferred=1, max=1),
        ),
        width=D(min=10, preferred=50),
        buttons=[ok_button, cancel_button],
        with_background=False)

    return ConditionalContainer(content=dialog,
                                filter=ShowLoginPrompt(my_app) & ~is_done)
Esempio n. 26
0
File: run.py Progetto: wxnacy/et
            ('No', False),
            ('Maybe...', None),
        ],
    ).run()


emails = {
    "1": Window(content=FormattedTextControl(text='1 Hello world'), height=1),
    "2": Window(content=FormattedTextControl(text='2 Hello world'), height=1),
    "3": Window(content=FormattedTextControl(text='3 Hello world'), height=1),
}

revs = Box(
    Frame(TextArea(
        text='Hello world',
        width=40,
        height=1,
    )),
)

email_list = [v for k, v in emails.items()]

def create_input(name, label, default=''):
    return HSplit([
        #  Window(height=1, char='-'),
        VSplit([
            Window(content=FormattedTextControl(text=label), height=1,
                width=wcswidth(label)+1),
            Window(content=BufferControl(buffer=Buffer(name=name)), height=1),
        ]),
        Window(height=1, char='-'),
Esempio n. 27
0
def get_caller_identity():
    client = boto3.client("sts")
    caller_identity = client.get_caller_identity()
    return "User ID: {}\nAccount: {}\nCaller ARN: {}".format(
        caller_identity["UserId"],
        caller_identity["Account"],
        caller_identity["Arn"],
    )


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


console_area = Frame(body=TextArea())
service_radio = RadioList(values=[
    ("ec2", "ec2"),
    ("s3", "s3"),
    ("vpc", "vpc"),
    ("route53", "route53"),
    ("ecr", "ecr"),
    ("blah", "blah"),
], )
service_selection_frame = service_radio
root_container = HSplit([
    Window(FormattedTextControl("AWS > "), height=1, style="reverse"),
    service_selection_frame,
    console_area,
    Frame(
        title="Caller Identity",
Esempio n. 28
0
def get_statusbar_text():
    return " Press Ctrl-C to 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=DynamicLexer(lambda: PygmentsLexer.from_filename(
        ApplicationState.current_path or ".txt", sync_from_start=False)),
    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():
Esempio n. 29
0
                        text_area.document.cursor_position_col + 1)),
        ('class:status', ' - Press '),
        ('class:status.key', 'Ctrl-C'),
        ('class:status', ' to exit, '),
        ('class:status.key', '/'),
        ('class:status', ' for searching.'),
    ]


search_field = SearchToolbar(
    text_if_not_searching=[('class:not-searching',
                            "Press '/' to start searching.")])

text_area = TextArea(text=text,
                     read_only=True,
                     scrollbar=True,
                     line_numbers=True,
                     search_field=search_field,
                     lexer=PygmentsLexer(PythonLexer))

root_container = HSplit([
    # The top toolbar.
    Window(content=FormattedTextControl(get_statusbar_text),
           height=D.exact(1),
           style='class:status'),

    # The main content.
    text_area,
    search_field,
])

# Key bindings.
Esempio n. 30
0
def main():
    # The layout.
    search_field = SearchToolbar()  # For reverse search.

    output_field = TextArea(style='class:output-field', text=help_text)
    input_field = TextArea(
        height=1, prompt='>>> ', style='class:input-field', multiline=False,
        wrap_lines=False, search_field=search_field)

    container = HSplit([
        output_field,
        Window(height=1, char='-', style='class:line'),
        input_field,
        search_field,
    ])

    # Attach accept handler to the input field. We do this by assigning the
    # handler to the `TextArea` that we created earlier. it is also possible to
    # pass it to the constructor of `TextArea`.
    # NOTE: It's better to assign an `accept_handler`, rather then adding a
    #       custom ENTER key binding. This will automatically reset the input
    #       field and add the strings to the history.
    def accept(buff):
        # Evaluate "calculator" expression.
        try:
            output = '\n\nIn:  {}\nOut: {}'.format(
                input_field.text,
                eval(input_field.text))  # Don't do 'eval' in real code!
        except BaseException as e:
            output = '\n\n{}'.format(e)
        new_text = output_field.text + output

        # Add text to output buffer.
        output_field.buffer.document = Document(
            text=new_text, cursor_position=len(new_text))

    input_field.accept_handler = accept

    # The key bindings.
    kb = KeyBindings()

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

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

    # Run application.
    application = Application(
        layout=Layout(container, focused_element=input_field),
        key_bindings=kb,
        style=style,
        mouse_support=True,
        full_screen=True)

    application.run()
Esempio n. 31
0
        for cmd in cmds:
            t3 = cmd.rstrip().partition('(')
            x = t3[0]
            args = t3[2].rstrip(')').partition(',')
            if x == "stream" or x == "change":
                dest = capture1
                if args[0] == "2":
                    dest = capture2
                _print(dest, ('\ninput[' + args[0] + '] = ' + args[2] + '\n'))
            elif len(cmd) > 0:
                myprint(cmd + '\n')
    elif len(text) > 0:
        myprint(text + '\n')


capture1 = TextArea(style='class:capture-field', height=2)
capture2 = TextArea(style='class:capture-field', height=2)
output_field = TextArea(style='class:output-field', text=druid_intro)


async def shell():
    global crow
    input_field = TextArea(height=1,
                           prompt='> ',
                           style='class:input-field',
                           multiline=False,
                           wrap_lines=False)

    captures = VSplit([capture1, capture2])
    container = HSplit([
        captures, output_field,