Beispiel #1
0
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()
Beispiel #2
0
layout = Layout(container=root_container, focused_element=btn_start)

# Key bindings.
kb = KeyBindings()
kb.add("tab")(focus_next)
kb.add("s-tab")(focus_previous)
kb.add("right")(focus_next)
kb.add("left")(focus_previous)
kb.add("q")(exit_clicked)

# Styling.
style = Style([
    ("left-pane", "bg:#888800 #000000"),
    ("right-pane", "bg:#00aa00 #000000"),
    ("button", "#000000"),
    ("button-arrow", "#000000"),
    ("button focused", "bg:#ff0000"),
    ("red", "#ff0000"),
    ("green", "#00ff00"),
])

# Build a main application object.
application = Application(layout=layout,
                          key_bindings=kb,
                          style=style,
                          full_screen=True)


def draw():
    tomato.update()
    text_area.text = tomato.as_formatted_text()
Beispiel #3
0
import re
import requests
import os

from colorama import Fore
from prompt_toolkit.validation import Validator

from . import aws_account_util, config_file_util, pre_checks, utils
from prompt_toolkit.styles import Style

custom_style = Style([
    ("qmark", "fg:#02abab bold"),
    ("question", "bold"),
    ("answer", "fg:#02abab bold"),
    ("pointer", "fg:#02abab bold"),
    ("highlighted", "fg:#02abab bold"),
    ("selected", "fg:#02abab"),
    ("separator", "fg:#02abab"),
    ("instruction", ""),
    ("text", ""),
])

AWS_OS_TYPES = {"AmazonLinux2": "linux", "AmazonWindows2019": "windows"}

CancelAnswer = questionary.Choice(title="Cancel")


class Question:
    answer: str = None
    params: dict = None
Beispiel #4
0
#!/usr/bin/env python
# encoding: utf-8

import questionary
from prompt_toolkit.styles import Style
from . import *

style = Style([
    ("separator", "fg:#6C6C6C"),
    ("qmark", "fg:#FF9D00 bold"),
    ("question", ""),
    ("selected", "fg:#2e82c7 bg:#d9d9d9"),
    ("pointer", "fg:#FF9D00 bold"),
    ("answer", "fg:#2e9dd1 bold bg:#363636"),
])


def main():
    generator = questionary.autocomplete(
        "What do you want to generate?",
        choices=[
            "Apache Config",
            "Windows Install",
        ],
        style=style,
    ).ask()

    if generator == "Apache Config":
        gen = ApacheConfigGenerator()

        apache_path: str = questionary.path(
Beispiel #5
0
 def style(self):
     return merge_styles([
         Style(BaseCommitizen.default_style_config),
         Style(self.config.settings["style"]),
     ])
Beispiel #6
0
def main(play_with_engine=False):
    search_field = SearchToolbar()
    engine = None
    if play_with_engine:
        engine = chess.engine.SimpleEngine.popen_uci('/usr/bin/stockfish')
    board = chess.Board()
    chess_completer = WordCompleter([str(x) for x in board.legal_moves])

    output_field = TextArea(style="class:output-field", text=board.unicode())
    input_field = TextArea(height=1,
                           prompt=">>> ",
                           style="class:input-field",
                           multiline=False,
                           wrap_lines=False,
                           search_field=search_field,
                           completer=chess_completer,
                           complete_while_typing=True)
    container = HSplit([
        output_field,
        Window(height=1, char="-", style="class:line"),
        input_field,
        search_field,
    ])

    def accept(buff):
        new_move = chess.Move.from_uci(input_field.text)
        board.push(new_move)

        if engine:
            result = engine.play(board, chess.engine.Limit(time=0.1))
            board.push(result.move)

        output = board.unicode()
        output_field.buffer.document = Document(text=output)

        input_field.completer = WordCompleter(
            [str(x) for x in board.legal_moves])

    input_field.accept_handler = accept

    kb = KeyBindings()

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

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

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

    application.run()
Beispiel #7
0
from prompt_toolkit.styles import Style, merge_styles
from prompt_toolkit.styles.defaults import (PROMPT_TOOLKIT_STYLE, COLORS_STYLE,
                                            WIDGETS_STYLE)

# from prompt_toolkit.filters import ViInsertMode
# from prompt_toolkit.key_binding.key_processor import KeyPress
# from prompt_toolkit.keys import Keys
from pygments.token import Token

from ptpython.layout import CompletionVisualisation

__all__ = ('configure', )

yo_dogg = merge_styles([
    Style(styles)
    for styles in (PROMPT_TOOLKIT_STYLE, COLORS_STYLE, WIDGETS_STYLE)
])


def configure(repl):
    """
    Configuration method. This is called during the start-up of ptpython.
    
    :param repl: `PythonRepl` instance.
    """
    # Show function signature (bool).
    repl.show_signature = True

    # Show docstring (bool).
    repl.show_docstring = True
Beispiel #8
0
    def start_cli():
        """
        Start cli loop and execute command
        :return:
        """
        CLI.add_command("help", CLI.list_commands, "Show commands")

        command_completer = WordCompleter(list(sorted(CLI.prompt_to_execution.keys())), ignore_case=True)

        welcome_text = TextArea(text="Type help for command overview. Quit with ctrl-c.", height=1, style='class:output-field')

        output_field = TextArea(style='class:output-field')

        input_output = TextArea(style='class:output-field', multiline=True, wrap_lines=True)

        input_field = TextArea(
            height=1,
            prompt='> ',
            style='class:input-field',
            wrap_lines=True,
            history=FileHistory('cli_history'),
            auto_suggest=AutoSuggestFromHistory(),
            completer=command_completer,
            complete_while_typing=True)

        container = FloatContainer(
            content=VSplit([
                HSplit([
                    welcome_text,
                    input_field,
                    Window(height=1, char='', style='class:line'),
                    input_output

                ]),
                Window(width=1, char='|', style='class:line'),
                output_field,
            ]),
            floats=[
                Float(xcursor=True,
                      ycursor=True,
                      content=CompletionsMenu(max_height=16, scroll_offset=1))
            ]
        )

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

        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()
            os._exit(0)

        @kb.add('c-m')
        def accept(event=None):
            user_input = input_field.text

            user_input = user_input.split(" ")

            if user_input[0] in CLI.prompt_to_execution:
                command = CLI.prompt_to_execution.get(user_input[0], lambda: 'Invalid')[0]
                args = CLI.prompt_to_execution.get(user_input[0], lambda: 'Invalid')[1]

                if len(user_input) == 2:
                    command(user_input[1])
                elif len(user_input) == 3:
                    command(user_input[1], user_input[2])
                elif len(user_input) == 4:
                    command(user_input[1], user_input[2], user_input[3])
                elif len(user_input) == 5:
                    command(user_input[1], user_input[2], user_input[3], user_input[4])
                elif args is not None:
                    command(args)
                else:
                    command()
            else:
                Log.error("Command not found")


            input_field.text = ''


            #input_field.document = Document(text=new_text, cursor_position=len(new_text))

        def log_to_input(**kwargs):
            msg = kwargs.get("str")

            new_text = input_output.buffer.text + msg + "\n"

            input_output.buffer.document = Document(
                text=new_text, cursor_position=len(new_text)
            )

        def clear_input():
            new_text = ''

            input_output.buffer.document = Document(
                text=new_text, cursor_position=len(new_text)
            )

        def log_to_output(**kwargs):
            msg = kwargs.get('str')
            new_text = output_field.buffer.text + msg + "\n"

            output_field.buffer.document = Document(
                text=new_text, cursor_position=len(new_text))

        Event.on('log_to_input', log_to_input)
        Event.on('log_to_output', log_to_output)

        CLI.add_command("clear", clear_input, "Clears cli output")

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

        application.run()

        Log.info("Starting cli")
        return
    loop.create_task(update_leaderboard())


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

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

root_container = FloatContainer(
    content=HSplit([
        output_field,
        Window(height=1, char="-", style="class:line"),
        input_field,
        search_field
    ]),
    floats=[
        completions_menu
    ],
    key_bindings=KeyBindings())
Beispiel #10
0
    event.app.exit()


style = Style([
    ('output-field', 'bg:#000044 #ffffff'),
    ('maintitle', '#aaaa00'),
    ('maintitle.since', 'reverse'),
    ('exchangetitle', '#aaaa00 bg:black bold'),
    ('exchangetitle.runtime', 'reverse'),
    ('exchangetitle.prefix', '#fcba03 bg:black bold'),
    ('vline', 'reverse'),
    ('line.light', '#4d4d4d'),
    ('mbline', "fg:ansiyellow bg:black bold"),
    ('lastbid', "#34eb37"),
    ('spacer', "#bfbfbf bold"),
    ('lastask', "#eb4c34"),
    ('status', "#aaaa00"),
    ('status.position', '#aaaa00'),
    ('status.key', '#c6e334'),

    ("book.unique", '#666699'),
    ("book.bq", '#00ff00'),
    ("book.bb", '#33cc33'),
    ("book.spacer", '#666699'),
    ("book.bo", '#cc0000'),
    ("book.aq", '#ff0000'),

])


Beispiel #11
0
    def main(self, data):
        fr = FileReader(data)
        bc = BufferCache()

        all_input_processors = [
            ConditionalProcessor(HighlightSearchProcessor(), ~is_searching),
            HighlightIncrementalSearchProcessor(),
            HighlightSelectionProcessor(),
            DisplayMultipleCursors(),
        ]

        search_toolbar = SearchToolbar(vi_mode=True)

        lst_window = Window(
            BufferControl(
                Buffer(
                    name="file_list",
                    document=Document(fr.get_list_text(), cursor_position=0),
                    read_only=True,
                ),
                search_buffer_control=search_toolbar.control,
                preview_search=True,
                include_default_input_processors=False,
                input_processors=all_input_processors,
            ),
            cursorline=True,
        )

        txt_window = Window(
            BufferControl(
                bc.current_buffer,
                search_buffer_control=search_toolbar.control,
                preview_search=True,
                include_default_input_processors=False,
                input_processors=all_input_processors,
            ),
            wrap_lines=False,
        )

        toolbar = FormattedTextToolbar(text="hello world!",
                                       style="class:buf_name")

        body = HSplit([lst_window])
        # Key bind
        kb = KeyBindings()
        kb.add(Keys.ControlD)(scroll_half_page_down)
        kb.add(Keys.ControlU)(scroll_half_page_up)

        @kb.add(Keys.ControlQ)
        def _(event):
            event.app.exit()

        @kb.add(Keys.Enter, filter=has_focus("file_list"))
        def _(event):
            idx = event.current_buffer.document.cursor_position_row
            path = str(fr.get_path(idx))
            origin_data = str(fr.get_relative_path(idx))
            origin_data2 = origin_data.split("|")[0]
            number = origin_data2.split(":")[-1]
            command = "vim " + "+" + number + " " + path
            res = subprocess.call(command.split())

        @kb.add("k")
        def _(event):
            event.current_buffer.cursor_up()
            idx = event.current_buffer.document.cursor_position_row
            path = str(fr.get_relative_path(idx))
            try:
                set_buffer_txt_window(bc.get_or_append_buffer(path, "AAAAA"))
                set_text_toolbar(bc.current_buffer_name)
            except:
                pass

        @kb.add("j")
        def _(event):
            event.current_buffer.cursor_down()
            idx = event.current_buffer.document.cursor_position_row
            path = str(fr.get_relative_path(idx))
            set_buffer_txt_window(bc.get_or_append_buffer(path, "AAAAA"))
            set_text_toolbar(bc.current_buffer_name)

        def set_buffer_txt_window(buf):
            txt_window.content.buffer = buf

        def set_text_toolbar(text):
            toolbar.content.text = text

        @Condition
        def search_buffer_is_empty():
            return get_app().current_buffer.text == ""

        style = Style([
            ("buf_name", "fg:#dddddd bg:#8a2be2"),
            ("incsearch", "fg:ansibrightyellow reverse"),
        ])

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

        app.run()
Beispiel #12
0
 def for_dialog(self):
     return merge_styles(
         [default_ui_style(),
          Style(list(self._dialog_styles.items()))])
Beispiel #13
0
 def for_prompt(self):
     return merge_styles(
         [default_ui_style(),
          Style(list(self._prompt_styles.items()))])
Beispiel #14
0
root = VSplit([
    Box(Frame(buttons, style="class:button_panel"), padding=2),
    Box(Frame(text_area, title="Events", style="class:edit_panel"), padding=2),
])

layout = Layout(root)

# napojení na klávesové zkratky
key_bindings = KeyBindings()
key_bindings.add("up")(focus_previous)
key_bindings.add("down")(focus_next)

style = Style([
    ("button_panel", "bg:#ansiblue #ansiwhite"),
    ("edit_panel", "bg:#ansigreen #000000"),
    ("button", "#ansibrightyellow"),
    ("button focused", "bg:#ff0000"),
    ("text-area focused", "bg:#ff0000"),
])


@key_bindings.add("escape")
def on_escape_press(event):
    """Callback funkce volaná při stisku klávesy Esc."""
    print("\n\n[escape]\n\n")
    event.app.exit()


def main():
    # vytvoření aplikace s textovým uživatelským rozhraním
    application = Application(layout=layout,
Beispiel #15
0
NO_OR_YES = "(y/N)"

# Instruction for multiline input
INSTRUCTION_MULTILINE = "(Finish with 'Alt+Enter' or 'Esc, Enter')\n>"

# Selection token used to indicate the selection cursor in a list
SELECTED_POINTER = "»"

# Item prefix to identify selected items in a checkbox list
INDICATOR_SELECTED = "●"

# Item prefix to identify unselected items in a checkbox list
INDICATOR_UNSELECTED = "○"

# Prefix displayed in front of questions
DEFAULT_QUESTION_PREFIX = "?"

# Message shown when a user aborts a question prompt using CTRL-C
DEFAULT_KBI_MESSAGE = "Cancelled by user"

# Default message style
DEFAULT_STYLE = Style([
    ("qmark", "fg:#5f819d"),  # token in front of the question
    ("question", "bold"),  # question text
    ("answer", "fg:#FF9D00 bold"),  # submitted answer text behind the question
    ("pointer", ""),  # pointer used in select and checkbox prompts
    ("selected", ""),  # style for a selected item of a checkbox
    ("separator", ""),  # separator in lists
    ("instruction", ""),  # user instructions for select, rawselect, checkbox
])
Beispiel #16
0
def checkbox(
    message: str,
    choices: Sequence[Union[str, Choice, Dict[str, Any]]],
    default: Optional[str] = None,
    validate: Callable[[List[str]], Union[bool, str]] = lambda a: True,
    qmark: str = DEFAULT_QUESTION_PREFIX,
    style: Optional[Style] = None,
    use_pointer: bool = True,
    initial_choice: Optional[Union[str, Choice, Dict[str, Any]]] = None,
    **kwargs: Any,
) -> Question:
    """Ask the user to select from a list of items.

    This is a multiselect, the user can choose one, none or many of the
    items.

    Example:
        >>> import questionary
        >>> questionary.checkbox(
        ...    'Select toppings',
        ...    choices=[
        ...        "Cheese",
        ...        "Tomato",
        ...        "Pineapple",
        ...    ]).ask()
        ? Select toppings done (2 selections)
        ['Cheese', 'Pineapple']

    .. image:: ../images/checkbox.gif

    This is just a realy basic example, the prompt can be customised using the
    parameters.


    Args:
        message: Question text

        choices: Items shown in the selection, this can contain :class:`Choice` or
                 or :class:`Separator` objects or simple items as strings. Passing
                 :class:`Choice` objects, allows you to configure the item more
                 (e.g. preselecting it or disabling it).

        default: Default return value (single value). If you want to preselect
                 multiple items, use ``Choice("foo", checked=True)`` instead.

        validate: Require the entered value to pass a validation. The
                  value can not be submitted until the validator accepts
                  it (e.g. to check minimum password length).

                  This should be a function accepting the input and
                  returning a boolean. Alternatively, the return value
                  may be a string (indicating failure), which contains
                  the error message to be displayed.

        qmark: Question prefix displayed in front of the question.
               By default this is a ``?``.

        style: A custom color and style for the question parts. You can
               configure colors as well as font types for different elements.

        use_pointer: Flag to enable the pointer in front of the currently
                     highlighted element.

        initial_choice: A value corresponding to a selectable item in the choices,
                        to initially set the pointer position to.

    Returns:
        :class:`Question`: Question instance, ready to be prompted (using ``.ask()``).
    """

    merged_style = merge_styles([
        DEFAULT_STYLE,
        # Disable the default inverted colours bottom-toolbar behaviour (for
        # the error message). However it can be re-enabled with a custom
        # style.
        Style([("bottom-toolbar", "noreverse")]),
        style,
    ])

    if not callable(validate):
        raise ValueError("validate must be callable")

    ic = InquirerControl(choices,
                         default,
                         use_pointer=use_pointer,
                         initial_choice=initial_choice)

    def get_prompt_tokens() -> List[Tuple[str, str]]:
        tokens = []

        tokens.append(("class:qmark", qmark))
        tokens.append(("class:question", " {} ".format(message)))

        if ic.is_answered:
            nbr_selected = len(ic.selected_options)
            if nbr_selected == 0:
                tokens.append(("class:answer", "done"))
            elif nbr_selected == 1:
                if isinstance(ic.get_selected_values()[0].title, list):
                    ts = ic.get_selected_values()[0].title
                    tokens.append((
                        "class:answer",
                        "".join([token[1] for token in ts]),  # type:ignore
                    ))
                else:
                    tokens.append((
                        "class:answer",
                        "[{}]".format(ic.get_selected_values()[0].title),
                    ))
            else:
                tokens.append(("class:answer",
                               "done ({} selections)".format(nbr_selected)))
        else:
            tokens.append((
                "class:instruction",
                "(Use arrow keys to move, "
                "<space> to select, "
                "<a> to toggle, "
                "<i> to invert)",
            ))
        return tokens

    def get_selected_values() -> List[Any]:
        return [c.value for c in ic.get_selected_values()]

    def perform_validation(selected_values: List[str]) -> bool:

        verdict = validate(selected_values)
        valid = verdict is True

        if not valid:
            if verdict is False:
                error_text = INVALID_INPUT
            else:
                error_text = str(verdict)

            error_message = FormattedText([("class:validation-toolbar",
                                            error_text)])

        ic.error_message = (error_message
                            if not valid and ic.submission_attempted else None)

        return valid

    layout = common.create_inquirer_layout(ic, get_prompt_tokens, **kwargs)

    bindings = KeyBindings()

    @bindings.add(Keys.ControlQ, eager=True)
    @bindings.add(Keys.ControlC, eager=True)
    def _(event):
        event.app.exit(exception=KeyboardInterrupt, style="class:aborting")

    @bindings.add(" ", eager=True)
    def toggle(_event):
        pointed_choice = ic.get_pointed_at().value
        if pointed_choice in ic.selected_options:
            ic.selected_options.remove(pointed_choice)
        else:
            ic.selected_options.append(pointed_choice)

        perform_validation(get_selected_values())

    @bindings.add("i", eager=True)
    def invert(_event):
        inverted_selection = [
            c.value for c in ic.choices if not isinstance(c, Separator)
            and c.value not in ic.selected_options and not c.disabled
        ]
        ic.selected_options = inverted_selection

        perform_validation(get_selected_values())

    @bindings.add("a", eager=True)
    def all(_event):
        all_selected = True  # all choices have been selected
        for c in ic.choices:
            if (not isinstance(c, Separator)
                    and c.value not in ic.selected_options and not c.disabled):
                # add missing ones
                ic.selected_options.append(c.value)
                all_selected = False
        if all_selected:
            ic.selected_options = []

        perform_validation(get_selected_values())

    @bindings.add(Keys.Down, eager=True)
    @bindings.add("j", eager=True)
    def move_cursor_down(_event):
        ic.select_next()
        while not ic.is_selection_valid():
            ic.select_next()

    @bindings.add(Keys.Up, eager=True)
    @bindings.add("k", eager=True)
    def move_cursor_up(_event):
        ic.select_previous()
        while not ic.is_selection_valid():
            ic.select_previous()

    @bindings.add(Keys.ControlM, eager=True)
    def set_answer(event):

        selected_values = get_selected_values()
        ic.submission_attempted = True

        if perform_validation(selected_values):
            ic.is_answered = True
            event.app.exit(result=selected_values)

    @bindings.add(Keys.Any)
    def other(_event):
        """Disallow inserting other text. """
        pass

    return Question(
        Application(
            layout=layout,
            key_bindings=bindings,
            style=merged_style,
            **utils.used_kwargs(kwargs, Application.__init__),
        ))
Beispiel #17
0
    def __init__(self, buffer_queue):
        self.buffer = Buffer()
        self.modules = {}
        self.module_prompt_callback = None
        self.prompt_ident = None
        self.prompt_ident_skip = []

        key_bindings = KeyBindings()

        default_text = """
Welcome to VoltronBot!
Type ? for available commands.
Control-C or type 'quit' to exit
"""
        lexer = PygmentsLexer(VoltronOutputLexer)
        ## Main output TextArea
        self.scrolling_output = TextArea(focusable=True,
                                         text=default_text,
                                         lexer=lexer)

        self.buffer_queue = buffer_queue
        self.buffer_thread = UIBufferQueue(self, self.buffer_queue,
                                           self.scrolling_output)
        self.buffer_thread.start()
        self.prompt_queue = queue.Queue()

        ## Exit keybinds
        @key_bindings.add('c-q')
        @key_bindings.add('c-c')
        def _exit(event):
            self.buffer_queue.put('SHUTDOWN')
            self.buffer_thread.join()
            event.app.exit()

        ## TextArea for prompt
        self.prompt = TextArea(
            height=1,
            #prompt=DEFAULT_PROMPT,
            multiline=False,
            wrap_lines=True)
        self.prompt.accept_handler = self.input_recv

        ## Create status bar
        self.status_text = FormattedTextControl(text=DEFAULT_STATUS)
        self.scroll_text = FormattedTextControl(text="")

        self.status_window = Window(content=self.status_text,
                                    height=1,
                                    style="class:status-bar")
        self.scroll_window = Window(content=self.scroll_text,
                                    height=1,
                                    width=6,
                                    style="class:status-bar")
        status_split = VSplit([self.status_window, self.scroll_window])

        self.prompt_text = FormattedTextControl(text=DEFAULT_PROMPT)
        self.prompt_window = Window(content=self.prompt_text,
                                    height=1,
                                    width=len(DEFAULT_PROMPT) + 1)

        ## Create top bar
        self.main_container = HSplit([
            Window(content=FormattedTextControl(text=f"VoltronBot v{VERSION}"),
                   height=1,
                   style="class:title-bar"),
            self.scrolling_output,
            status_split,
            VSplit([self.prompt_window, self.prompt]),
        ])

        style = Style([
            ('title-bar', 'bg:ansiblue #000000'),
            ('status-bar', 'bg:ansicyan #000000'),
            ('status-bar-important', 'bg:ansired #000000'),
        ])

        self.layout = Layout(self.main_container, focused_element=self.prompt)

        ## Keybind for page up
        @key_bindings.add('pageup')
        def _scroll_up(event):
            self.layout.focus(self.scrolling_output)
            scroll_one_line_up(event)
            self.layout.focus(self.prompt)

            if not self._scrolled_to_bottom:
                self.scroll_text.text = '(more)'
            else:
                self.scroll_text.text = ''

        ## Keybind for page down
        @key_bindings.add('pagedown')
        def _scroll_down(event):
            self.layout.focus(self.scrolling_output)
            scroll_one_line_down(event)
            self.layout.focus(self.prompt)

            if not self._scrolled_to_bottom:
                self.scroll_text.text = '(more)'
            else:
                self.scroll_text.text = ''

        self._app = Application(layout=self.layout,
                                full_screen=True,
                                key_bindings=key_bindings,
                                style=style)
Beispiel #18
0
        self.busy = False
        time.sleep(self.delay)
        if exception is not None:
            return False


# custom style for question properties
custom_style = Style([
    ('qmark', 'fg:#fac731 bold'),  # token in front of the question
    ('question', ''),  # question text
    # pointer used in select and checkbox prompts
    ('pointer', 'fg:#673ab7 bold'),
    # pointed-at choice in select and checkbox prompts
    ('highlighted', 'fg:#673ab7 bold'),
    ('selected', 'fg:#0abf5b'),  # style for a selected item of a checkbox
    ('separator', 'fg:#cc5454'),  # separator in lists
    # user instructions for select, rawselect, checkbox
    ('instruction', ''),
    ('text', 'fg:#4688f1 bold'),  # plain text
    # disabled choices for select and checkbox prompts
    ('disabled', 'fg:#858585 italic'),
    # submitted answer text behind the question
    ('answer', 'fg:#f44336 bold'),
])

# api routes/endpoints
routes = {
    'auth': {
        'route':
        'https://api-pa-cliente.equatorialenergia.com.br/auth/connect/token',
        'headers': {
Beispiel #19
0
def main():
    click.secho(" ______     __  __     ______     __         __    ",
                fg="red")
    click.secho("/\  ___\   /\ \_\ \   /\  ___\   /\ \       /\ \   ",
                fg="yellow")
    click.secho("\ \ \____  \ \____ \  \ \ \____  \ \ \____  \ \ \  ",
                fg="green")
    click.secho(" \ \_____\  \/\_____\  \ \_____\  \ \_____\  \ \_\ ",
                fg="blue")
    click.secho("  \/_____/   \/_____/   \/_____/   \/_____/   \/_/ ",
                fg="magenta")

    main_prompt = prompt('graphistry>> ', enable_system_prompt=True)

    # The layout.
    output_field = TextArea(style='class:output-field', text=help_text)
    input_field = TextArea(height=2,
                           prompt='graphistry>> ',
                           style='class:input-field')
    bottom_field = TextArea(height=1,
                            style='class:bottom-toolbar',
                            text=revisionist_commit_history())

    main_output = VSplit([
        output_field,
        Window(char='~'),
        Window(width=20, style='class:line'),
    ])
    container = HSplit([
        main_output,
        Window(height=1, char='~', style='class:line'), input_field,
        bottom_field
    ])

    # 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()

    @kb.add('enter', filter=has_focus(input_field))
    def _(event):
        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

        output_field.buffer.document = Document(text=new_text,
                                                cursor_position=len(new_text))
        input_field.text = ''

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

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

    application.run()
Beispiel #20
0
    fontsize = default_fontsize

print(fontsize)

directory_list = os.listdir(ztree_path)[::-1]  # This reverses the list order

from prompt_toolkit.styles import Style

custom_style_fancy = Style([
    #    ('qmark', 'fg:#673ab7 bold'),       # token in front of the question
    ('question', 'bold'),  # question text
    #    ('answer', 'fg:#f44336 bold'),      # submitted answer text behind the question
    ('pointer', 'fg:#FFFF00 bold'
     ),  # pointer used in select and checkbox prompts
    (
        'highlighted', 'fg:#FFFF00 bold'
    ),  # pointed-at choice in select and checkbox prompts if use_pointer=False
    ('selected', 'fg:#cc5454'),  # style for a selected item of a checkbox
    #    ('separator', 'fg:#cc5454'),        # separator in lists
    #    ('instruction', ''),                # user instructions for select, rawselect, checkbox
    #    ('text', ''),                       # plain text
    #    ('disabled', 'fg:#858585 italic')   # disabled choices for select and checkbox prompts
])

version = questionary.select(
    "Please select z-Tree version.",
    choices=directory_list,
    style=custom_style_fancy).ask()  # returns value of selection

with open(os.path.join(settings_path, fontsize_filename),
          "w+") as fontsize_file:
Beispiel #21
0
# Styling.
from prompt_toolkit.styles import Style

style = Style(
    [
        ("left-pane", "bg:#888800 #000000"),
        ("right-pane", "bg:#00aa00 #000000"),
        ("button", "#000000"),
        ("button-arrow", "#000000"),
        ("button focused", "bg:#ff0000"),
        ("text-area focused", "bg:#ff0000"),
        ("danger", "#ff3300"),
    ]
)
Beispiel #22
0
def start_app(args):
    """Text-based GUI application"""
    cmd = Commands()
    completer = WordCompleter(cmd.commands(),
                              meta_dict=cmd.meta_dict(),
                              ignore_case=True)
    history = InMemoryHistory()

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

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

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

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

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

    # The key bindings.
    kb = KeyBindings()

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

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

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

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

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

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

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

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

    # Run application.
    application = MyApplication(layout=Layout(root_container,
                                              focused_element=input_field),
                                key_bindings=kb,
                                style=style,
                                mouse_support=True,
                                full_screen=True)
    application.run()
Beispiel #23
0
from prompt_toolkit.styles import Style, merge_styles

override_style = Style([("bottom-toolbar", "noreverse")])

style = REDIS_TOKEN = {
    "key": "#33aa33",
    "important-key": "#058B06",
    "pattern": "bold #33aa33",
    "string": "#FD971F",
    "member": "#FD971F",
    "command": "bold #008000",
    "integer": "#AE81FF",
    "start": "#AE81FF",  # TODO auto merge with integer
    "end": "#AE81FF",
    "const": "bold #AE81FF",
    "time": "#aa22ff",
    "double": "#bb6688",
    "nil": "#808080",
    "bit": "#8541FF",
    "field": "cyan",
}

GROUP = {
    "group.cluster": "#E6DB74",
    "group.connection": "#E6DB74",
    "group.generic": "#E6DB74",
    "group.geo": "#E6DB74",
    "group.hash": "#E6DB74",
    "group.hyperloglog": "#E6DB74",
    "group.list": "#E6DB74",
    "group.pubsub": "#E6DB74",
Beispiel #24
0
# The name of the directory containing descriptions of each game relative to the root package. Because this is a
# resource string and not a filesystem path, it must use forward slashes.
DESCRIPTIONS_DIR = "descriptions"

# The name of the directory containing template files relative to the root package. Because this is a resource string
# and not a filesystem path, it must use forward slashes.
TEMPLATES_DIR = "templates"

# The path of the template file containing the default difficulty presets. Because this is a resource string and not a
# filesystem path, it must use forward slashes.
DIFFICULTY_TEMPLATE = "/".join([TEMPLATES_DIR, "difficulty.json"])

# The master style sheet for all GUIs.
GUI_STYLE = Style([
    ("button.focused", "bg:ansired"),
    ("dialog.body", "fg:ansidefault bg:ansidefault"),
    ("dialog shadow", "fg:ansibrightblack bg:ansibrightblack"),
    ("dialog frame.label", "fg:ansigreen"),
    ("cursor-line", "fg:ansidefault bg:ansidefault reverse nounderline"),
    ("cursor-column", "fg:ansidefault bg:ansidefault reverse"),
    ("selectable-label", ""),
    ("selectable-label.focused", "reverse"),
    ("column-name", "bold"),
])

# The number of spaces to indent when serializing JSON.
JSON_INDENT = 4

# The name of the default difficulty level.
DEFAULT_DIFFICULTY = "Normal"
Beispiel #25
0
            Box(body=Frame(text_area), padding=1, style='class:right-pane'),
        ]),
    ]), )

layout = Layout(container=root_container, focused_element=button1)

# Key bindings.
kb = KeyBindings()
kb.add('tab')(focus_next)
kb.add('s-tab')(focus_previous)

# Styling.
style = Style([
    ('left-pane', 'bg:#888800 #000000'),
    ('right-pane', 'bg:#00aa00 #000000'),
    ('button', '#000000'),
    ('button-arrow', '#000000'),
    ('button focused', 'bg:#ff0000'),
    ('text-area focused', 'bg:#ff0000'),
])

# Build a main application object.
application = Application(layout=layout,
                          key_bindings=kb,
                          style=style,
                          full_screen=True)


def main():
    application.run()

Beispiel #26
0
def gatherup(project, no_instruct, lang, debug, setup, demo):
    """GatherUp helps you post essential Python config details to GitHub
       or Discourse, all beautifully formatted"""

    global config, console, qs, rich_theme, questionary_style, autocomplete_style

    config_file = get_config_file()

    if config_file != '':
        config = set_config()
    else:
        config = None

    rich_theme = Theme({
        "h1": "bold grey0 on yellow1",
        "h2": "bold hot_pink",
        "ul": "bold white",
        "t1": "bold yellow1",
        "t2": "bold spring_green3",
        "bw": "bold white",
        "edge": "grey23",
        "link": "dodger_blue3",
        "markers":"white italic bold on deep_pink1"
    })

    questionary_style = Style([
        ('qmark', 'fg:#00d75f bold'),       # token in front of the question
        ('expected', 'bold'),                # the expected value we think the user has
        ('question', 'bold'),               # question text
        ('answer', 'fg:#ffff00 bold'),      # submitted answer text behind the question
        ('pointer', 'fg:#ff5fd7 bold'),     # pointer used in select and checkbox prompts
        ('highlighted', 'fg:#ff5fd7 bold'), # pointed-at choice in select and checkbox prompts
        ('selected', 'fg:#949494'),         # style for a selected item of a checkbox
        ('instruction', ''),                # user instructions for select, rawselect, checkbox
        ('text', ''),                       # plain text
        ('disabled', 'fg:#858585 italic')   # disabled choices for select and checkbox prompts
    ])

    autocomplete_style = Style([
        ('qmark', 'fg:#00d75f bold'),       # token in front of the question - CORRECT
        #('expected', 'fg:#000000 bg:#ffffff bold'),                # the expected value we think the user has NOT USED
        ('question', 'bold'),               # question text - CORRECT, IS FOR QUESTION TEXT
        ('answer', 'fg:#00d75f bg:#322e2e bold'),      # submitted answer text behind the question - ACTUALLY USED FOR PRIMARY DROP-DOWN
        #('pointer', 'fg:#ffffff bg:#000000 bold'),     # pointer used in select and checkbox prompts NOT USED
        #('highlighted', 'fg:#ffffff bg:#000000 bold'), # pointed-at choice in select and checkbox prompts NOT USED
        #('selected', 'fg:#000000 bg:#ffffff'),         # style for a selected item of a checkbox SELECTED PRIMARY DROP-DOWN, OTHERWISE SEEMS TO INVERT???
        ('text', 'fg:#322e2e')                       # plain text - ACTUALLY USED FOR SECONDARY DROP-DOWN
    ])


    console = Console(width=120, theme=rich_theme)
    qs = questionary

    if debug:
        console.print('\nDEBUG IS ON')
        console.print(f'Options:\n\t --lang {lang}')
        console.print(f'\t --no_instruct {no_instruct}')
        console.print(f'\t --project {project}')
        if config is None:
            console.print('There is no config file')
        else:
            console.print(f'Config file: {config_file}')

    gather_intro(debug=debug)

    #TODO: remove this once languages work beyond instructions only
    if not no_instruct:
        lang = get_language_choice(LANGUAGES, lang, debug=debug)
    else:
        lang = 'en'

    if setup:
        do_setup()

    if demo:
        do_demo()
        #TODO proper quit
        return

    while not QUIT: 
        if not no_instruct:
            offer_instructions(lang, debug=debug)
        output_text = gather_input(project, debug=debug)
        handle_output(output_text, debug=debug)
        check_successful(debug=debug)
    finished(debug=debug)
Beispiel #27
0
def get_cmd_input():
    return questionary.text("",
                            qmark="Your input ->",
                            style=Style([('qmark', '#b373d6'),
                                         ('', '#b373d6')])).ask().strip()
Beispiel #28
0
    def __init__(self) -> None:
        self.logger = logging.getLogger(self.__class__.__name__)
        self.config_file = os.getenv('IG_CLI_CONFIG', 'config.yml')
        self.config = {}
        self._id = None
        self.authd = False
        self._stop_update = Event()
        self.client = None
        self.positions_thread = None
        self.activity_thread = None
        self.orders_thread = None
        self.trackers_thread = None
        self.status_thread = RepeatTimer(self.update_status, 1)

        self.style = Style([('output-field', 'bg:#5F9EA0 #F0FFFF'),
                            ('input-field', 'bg:#20B2AA #F0FFFF'),
                            ('separator', '#000000'),
                            ('status-bar', 'bg:#D3D3D3 #2F4F4F')])

        self.trackers_field = TextArea(style='class:output-field')
        self.positions_field = TextArea(style='class:output-field')
        self.orders_field = TextArea(style='class:output-field')
        self.activity_field = TextArea(height=7, style='class:output-field')
        self.msg_field = TextArea(height=7, style='class:output-field')

        self.output_container = HSplit([
            VSplit([
                self.positions_field,
                Window(width=1, char='|', style='class:separator'),
                HSplit([
                    self.trackers_field,
                    Window(height=1, char='-', style='class:separator'),
                    self.orders_field
                ])
            ]),
            Window(height=1, char='-', style='class:separator'),
            VSplit([
                self.msg_field,
                Window(width=1, char='|', style='class:separator'),
                self.activity_field
            ])
        ])

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

        self.input_field.accept_handler = self.parse

        self.status_field = TextArea(height=1,
                                     style='class:status-bar',
                                     multiline=False,
                                     wrap_lines=False,
                                     text=self.status)
        self.time_field = TextArea(height=1,
                                   style='class:status-bar',
                                   multiline=False,
                                   wrap_lines=False,
                                   text=self.get_time())

        self.container = HSplit([
            self.output_container,
            Window(height=1, char='-', style='class:separator'),
            self.input_field, self.search_field, self.status_field
        ])

        self.app = Application(Layout(self.container,
                                      focused_element=self.input_field),
                               style=self.style,
                               full_screen=True,
                               mouse_support=True,
                               key_bindings=self.kb)
        self.autologin()
        self.status_thread.start()
Beispiel #29
0
 def build_application(self, container: Container,
                       keys: KeyBindings) -> Application:
     return Application(layout=Layout(container),
                        key_bindings=keys,
                        full_screen=True,
                        style=Style([("header", "bg:#005fff fg:black")]))
Beispiel #30
0
kb = KeyBindings()


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


@kb.add("c-c")
def _(event):
    q_commands.put('\x03')


style = Style(
    [
        ("input-field", "bg:#000000 #ffffff"),
        ("line", "#004400"),
    ]
)
application = Application(
    layout=Layout(container, focused_element=input_field),
    key_bindings=kb,
    style=style,
    mouse_support=True,
    full_screen=True,
)


def accept(buff):
    command = input_field.text
    if 255 >= len(command) > 0:
        if command == "clear":