Exemple #1
0
    def __init__(self, event, auth):

        super().__init__()

        self.event = event
        self.authtype = 'digest'

        authuser = auth.get('user', '')
        authpass = auth.get('password', '')

        self.authuser.text = authuser
        self.authuser.buffer.document = Document(authuser, len(authuser))

        self.authpass_one.text = authpass
        self.authpass_one.buffer.document = Document(authpass, len(authpass))

        self.authpass_two.text = authpass
        self.authpass_two.buffer.document = Document(authpass, len(authpass))

        self.dialog = Dialog(
            title='Digest Authentication',
            body=HSplit([
                Label(text='Username:\n'), self.authuser,
                Window(height=1, char=' '),
                Label(text='Password'), self.authpass_one,
                Window(height=1, char=' '),
                Label(text='Retype password'), self.authpass_two
            ]),
            buttons=[self.ok_button, self.cancel_button, self.delete_button],
            width=D(preferred=80),
            with_background=True,
            modal=True)

        root_container.floats.append(Float(self.dialog))
        event.app.layout.focus(self.dialog)
Exemple #2
0
    def __init__(self, key=None, value=None):

        self.key = Label(text=key, width=20)
        self.value = Label(text=value, )
        self.vsplit = VSplit(
            [self.key, Window(width=1, char=' '), self.value],
            align=HorizontalAlign.LEFT)
Exemple #3
0
    def get_root_container(self) -> FloatContainer:
        header_row = self.table.format_table().splitlines()[0]
        data_rows = self.table.format_table().splitlines()[1:]

        row_buttons = [
            SelectableLabel(row,
                            handler=functools.partial(self._handle_answer, i))
            for i, row in enumerate(data_rows)
        ]

        table_container = HSplit([
            Label(FormattedText([("class:column-name", header_row)]), ),
            HorizontalLine(),
            *row_buttons,
        ])

        rules_container = Box(
            Label(
                self.table.format_constraints(separator="\n\n"),
                dont_extend_width=True,
            ), )

        return FloatContainer(
            Box(
                Frame(
                    VSplit([
                        table_container,
                        VerticalLine(),
                        rules_container,
                    ])), ),
            floats=[],
        )
Exemple #4
0
    def test_toggle_back_button(self):
        """The back button is only visible if there are at least 2 pages."""
        first_label = Label("First")
        second_label = Label("Second")

        self.window.push(first_label)
        self.window.push(second_label)

        children = to_container(self.window).get_children()
        back_button = children[1]
        exit_button = to_widget(children[2])

        assert exit_button.text == "Exit"

        # Back button is visible
        assert to_widget(back_button.content).text == "Back"
        assert back_button.filter()

        label = children[0].get_container()
        assert label.text == "Second"

        self.window.pop()

        # Back button is't visible
        assert to_widget(back_button.content).text == "Back"
        assert not back_button.filter()

        label = children[0].get_container()
        assert label.text == "First"
Exemple #5
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.riitag_info = user.RiitagInfo()  # placeholder

        self.menu_settings_button = Button(
            'Settings', handler=lambda: self._set_state('Settings'))
        self.menu_exit_button = Button('Exit', handler=self.quit_app)
        self.menu_logout_button = Button('Logout', handler=self._logout)

        self.settings_back_button = Button(
            'Back...', width=12, handler=lambda: self._set_state('Menu'))
        self.settings_reset_button = Button('Reset...',
                                            width=12,
                                            handler=self._reset_preferences)
        self.settings_pres_timeout_button = PreferenceButton(
            value=self.app.preferences.presence_timeout,
            increments=10,
            limits=(10, 120))
        self.settings_check_interval_button = PreferenceButton(
            value=self.app.preferences.check_interval,
            increments=10,
            limits=(10, 60))

        self.right_panel_state = 'Menu'
        self.menu_layout = Frame(Box(HSplit([
            self.menu_settings_button,
            Label(''),
            self.menu_exit_button,
            self.menu_logout_button,
        ]),
                                     padding_left=3,
                                     padding_top=2),
                                 title='Menu')
        self.settings_layout = Frame(Box(HSplit([
            Window(FormattedTextControl(
                HTML(
                    'This is where you can modify settings\nregarding the underlying presence\nwatcher.'
                )),
                   wrap_lines=True,
                   width=25),
            Label(''),
            VSplit([
                Label('Presence Timeout (min.):'),
                self.settings_pres_timeout_button
            ],
                   width=15),
            VSplit([
                Label('Refresh Interval (sec.):'),
                self.settings_check_interval_button
            ],
                   padding=3),
            Label(''),
            VSplit([self.settings_back_button, self.settings_reset_button],
                   align=WindowAlign.CENTER)
        ]),
                                         padding_left=3,
                                         padding_top=2),
                                     title='Settings')
Exemple #6
0
 def __init__(self,
              title,
              const_value=None,
              label_col="cyan",
              extend_label_width=False):
     if title is not None:
         self.name = title.lower().replace(" ", "_")
         self.title_label = Label(text=title + ": ",
                                  dont_extend_width=not extend_label_width,
                                  style="bold %s" % label_col)
     if const_value is not None:
         self.value_label = Label(text=ANSI(const_value))
Exemple #7
0
    def _draw_widget(self, widget: [Error, Header, Input], label_length):
        if isinstance(widget, Error):
            return Label(
                FormattedText([
                    ("bg:red fg:white", "Error:"),
                    ("", f" {widget.title}\n"),
                ]))

        if isinstance(widget, Header):
            return Label(widget.title, style="bg:black fg:white")

        return self._draw_input(widget, label_length)
Exemple #8
0
    def __init__(
        self,
        mask,
        placeholder='_',
        style=None,
        default=None,
        allowed_chars=None,
    ):
        self._mask = mask
        self._placeholder = placeholder

        self._components = []
        self._fields = []

        size = 0
        for i in range(len(self._mask)):
            char = self._mask[i]
            if char == placeholder:
                size += 1
                continue
            if size > 0:
                widget = FixedLengthTextArea(
                    width=size,
                    max_length=size,
                    style=style,
                    allowed_chars=allowed_chars,
                    widget=self,
                )
                self._components.append(widget)
                self._fields.append(widget)
                size = 0
            self._components.append(Label(char, dont_extend_width=True))

        if size > 0:
            widget = FixedLengthTextArea(
                width=size,
                max_length=size,
                style=style,
                widget=self,
                allowed_chars=allowed_chars,
            )
            self._components.append(widget)
            self._fields.append(widget)
        self._components.append(Label(''))
        if default:
            self.value = default

        super().__init__(self._components)
Exemple #9
0
    def __init__(self, title="", label_text="", completer=None):
        self.future = Future()

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

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

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

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

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

        self.dialog = Dialog(
            title=title,
            body=HSplit([Label(text=label_text), self.text_area]),
            buttons=[ok_button, cancel_button],
            width=D(preferred=80),
            modal=True,
        )
def radiolist_dialog(title='',
                     text='',
                     ok_text='Ok',
                     cancel_text='Cancel',
                     values=None,
                     style=None,
                     async_=False):
    """
    Display a simple message box and wait until the user presses enter.
    """
    def ok_handler():
        get_app().exit(result=radio_list.current_value)

    radio_list = RadioList(values)

    dialog = Dialog(title=title,
                    body=HSplit([
                        Label(text=text, dont_extend_height=True),
                        radio_list,
                    ],
                                padding=1),
                    buttons=[
                        Button(text=ok_text, handler=ok_handler),
                        Button(text=cancel_text, handler=_return_none),
                    ],
                    with_background=True)

    return _run_dialog(dialog, style, async_=async_)
Exemple #11
0
def radiolist_dialog(title='', text='', ok_text='Ok', cancel_text='Cancel',
                     values=None, style=None, async_=False):
    """
    Display a simple list of element the user can choose amongst.

    Only one element can be selected at a time using Arrow keys and Enter.
    The focus can be moved between the list and the Ok/Cancel button with tab.
    """
    def ok_handler():
        get_app().exit(result=radio_list.current_value)

    radio_list = RadioList(values)

    dialog = Dialog(
        title=title,
        body=HSplit([
            Label(text=text, dont_extend_height=True),
            radio_list,
        ], padding=1),
        buttons=[
            Button(text=ok_text, handler=ok_handler),
            Button(text=cancel_text, handler=_return_none),
        ],
        with_background=True)

    return _run_dialog(dialog, style, async_=async_)
Exemple #12
0
    def __init__(self, event, dialog):
        def ok_handler():
            root_container.floats.pop()
            db.update_one(values={'name': name, 'auth': None})
            event.app.layout.focus(ButtonManager.prev_button)
            select_item(event)

        def cancel_handler():
            root_container.floats.pop()
            root_container.floats.append(self.auth_float)
            event.app.layout.focus(dialog)

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

        name = ButtonManager.current_button

        self.dialog = Dialog(
            title='Delete confirmation',
            body=Label(
                text='Are you sure you want to delete authentication for {}?'.
                format(name)),
            buttons=[cancel_button, ok_button],
            width=D(preferred=80),
            with_background=True)

        self.auth_float = root_container.floats.pop()
        root_container.floats.append(Float(self.dialog))
        event.app.layout.focus(self.dialog)
Exemple #13
0
    def get_root_container(self) -> FloatContainer:
        buttons = [
            *self._game_buttons.keys(),
            HorizontalLine(),
            Button("Quit", width=MENU_BUTTON_WIDTH, handler=self._exit),
        ]

        menu_keybindings = _create_menu_keybindings(buttons)

        game_buttons_container = Frame(
            HSplit(
                buttons,
                width=Dimension(min=MENU_BUTTON_WIDTH, max=40),
                height=Dimension(),
            ),
            title="Games",
            key_bindings=menu_keybindings,
        )

        game_description_container = Frame(
            Box(
                Label(
                    text=self._get_game_description,
                    dont_extend_height=False,
                    width=Dimension(min=40),
                ),
                padding=0,
                padding_left=1,
            ), )

        return FloatContainer(VSplit([
            game_buttons_container,
            game_description_container,
        ]),
                              floats=[])
Exemple #14
0
    def get_root_container(self) -> Dialog:
        sort_radiolist = RadioList([(sort_method, sort_method.column_name)
                                    for sort_method in ScoreSort])

        def ok_handler() -> None:
            self._selected_sort_setter(sort_radiolist.current_value)
            self.multi_screen.clear_floating()

        def cancel_handler() -> None:
            self.multi_screen.clear_floating()

        return Dialog(
            title="Sort By",
            body=HSplit(
                [
                    Label(text="Select the column to sort by",
                          dont_extend_height=True),
                    sort_radiolist,
                ],
                padding=1,
            ),
            buttons=[
                Button(text="Okay", handler=ok_handler),
                Button(text="Cancel", handler=cancel_handler),
            ],
            with_background=True,
        )
Exemple #15
0
    def get_root_container(self) -> Dialog:
        difficulty_store = DifficultyPresets()
        with difficulty_store:
            difficulty_names = difficulty_store.get_difficulty_names(
                self._selected_game_getter().game_name)

        difficulty_radiolist = RadioList([(difficulty, difficulty)
                                          for difficulty in difficulty_names])

        def ok_handler() -> None:
            self._selected_difficulty_setter(
                difficulty_radiolist.current_value)
            self.multi_screen.clear_floating()

        def cancel_handler() -> None:
            self.multi_screen.clear_floating()

        return Dialog(
            title="Difficulty",
            body=HSplit(
                [
                    Label(text="Select a difficulty", dont_extend_height=True),
                    difficulty_radiolist,
                ],
                padding=1,
            ),
            buttons=[
                Button(text="Okay", handler=ok_handler),
                Button(text="Cancel", handler=cancel_handler),
            ],
            with_background=True,
        )
Exemple #16
0
def button_dialog(
    title: AnyFormattedText = "",
    text: AnyFormattedText = "",
    buttons: List[Tuple[str, _T]] = [],
    style: Optional[BaseStyle] = None,
) -> Application[_T]:
    """
    Display a dialog with button choices (given as a list of tuples).
    Return the value associated with button.
    """

    def button_handler(v: _T) -> None:
        get_app().exit(result=v)

    dialog = Dialog(
        title=title,
        body=Label(text=text, dont_extend_height=True),
        buttons=[
            Button(text=t, handler=functools.partial(button_handler, v))
            for t, v in buttons
        ],
        with_background=True,
    )

    return _create_app(dialog, style)
Exemple #17
0
    def __init__(self, event):
        def ok_handler():
            # if len(ButtonManager.buttons) > 0:
            delete_server(event, name)
            root_container.floats.pop()

        def cancel_handler():
            root_container.floats.pop()
            event.app.layout.focus(ButtonManager.prev_button)

        # Get data about server currently editing
        name = ButtonManager.current_button

        # Dialog configuration
        ok_button = Button(text='OK', handler=ok_handler)
        cancel_button = Button(text='Cancel', handler=cancel_handler)

        self.dialog = Dialog(
            title='Delete confirmation',
            body=Label(
                text='Are you sure you want to delete {}?'.format(name)),
            buttons=[cancel_button, ok_button],
            width=D(preferred=80),
            with_background=True)

        root_container.floats.append(Float(self.dialog))
        event.app.layout.focus(self.dialog)
Exemple #18
0
    def __init__(self,
                 title: str = "DLNest Command Line",
                 onAccept: Callable[[str], None] = None):
        self.kb = KeyBindings()
        self.onAccept = onAccept

        def accept_text(buf: Buffer):
            if not self.onAccept is None:
                self.onAccept(buf.text)
            return False

        self.completer = getCommandCompleter()
        self.title = title

        self.text = TextArea(height=3,
                             auto_suggest=AutoSuggestFromHistory(),
                             completer=self.completer,
                             prompt=[("#fff5ee", "DLNest>>")],
                             accept_handler=accept_text,
                             scrollbar=True,
                             multiline=False)
        self.text.height = 3
        self.infoBar = Label([
            ("bg:#006060",
             "Press Enter to enter a command. Press ctrl + c to exit.")
        ])

        self.content = HSplit([self.text, self.infoBar])
Exemple #19
0
def disconnect_dialog(my_app: "sqlApp"):
    def yes_handler() -> None:
        obj = my_app.selected_object
        obj.conn.close()
        if my_app.active_conn is obj.conn:
            my_app.active_conn = None
        my_app.show_disconnect_dialog = False
        my_app.show_sidebar = True
        my_app.application.layout.focus("sidebarbuffer")

    def no_handler() -> None:
        my_app.show_disconnect_dialog = False
        my_app.show_sidebar = True
        my_app.application.layout.focus("sidebarbuffer")

    dialog = Dialog(
        title=lambda: my_app.selected_object.name,
        body=Label(text="Are you sure you want to disconnect?",
                   dont_extend_height=True),
        buttons=[
            Button(text="OK", handler=yes_handler),
            Button(text="Cancel", handler=no_handler),
        ],
        with_background=False,
    )

    return ConditionalContainer(content=dialog,
                                filter=ShowDisconnectDialog(my_app) & ~is_done)
Exemple #20
0
    def get_root_container(self) -> FloatContainer:
        validator = CoordinateValidator(self.maze_grid)

        maze_grid_container = Label(text=self.maze_grid.format_grid, )

        coordinates_input_container = Window(
            BufferControl(
                buffer=Buffer(
                    validator=validator,
                    validate_while_typing=False,
                    multiline=False,
                    accept_handler=self._accept_handler,
                ),
                input_processors=[
                    BeforeInput("Enter coordinates (x, y): "),
                ],
            ), )

        validation_toolbar = ConditionalContainer(
            ValidationToolbar(),
            filter=~is_done,
        )

        return FloatContainer(
            HSplit([
                maze_grid_container,
                HorizontalLine(),
                coordinates_input_container,
                validation_toolbar,
            ]),
            floats=[],
        )
def yes_no_dialog(
    title: AnyFormattedText = "",
    text: AnyFormattedText = "",
    yes_text: str = "Yes",
    no_text: str = "No",
    style: Optional[BaseStyle] = None,
) -> Application[bool]:
    """
    Display a Yes/No dialog.
    Return a boolean.
    """
    def yes_handler() -> None:
        get_app().exit(result=True)

    def no_handler() -> None:
        get_app().exit(result=False)

    dialog = Dialog(
        title=title,
        body=Label(text=text, dont_extend_height=True),
        buttons=[
            Button(text=yes_text, handler=yes_handler),
            Button(text=no_text, handler=no_handler),
        ],
        with_background=True,
    )

    return _create_app(dialog, style)
Exemple #22
0
    def __init__(self, path):
        self.theme = "default"
        sections_list = []
        for section in ["text", "prompt"]:
            sections_list.append(sections[section])

        book = Book(root=path)
        book.parse()
        chapters = book.chapters[1]
        chapters.parse()

        contents = chapters.contents[0]
        render = self.get_label(contents)
        label = Label(merge_formatted_text(render))

        self.container = HSplit(
            [
                VSplit(
                    [
                        sections["menu"],
                        sections["vseparator"],
                        HSplit([label, sections["prompt"]]),
                    ]
                ),
                sections["hseparator"],
                sections["status"],
            ]
        )
Exemple #23
0
    def __init__(self,
                 title='',
                 text='',
                 ok_text='Ok',
                 width=None,
                 wrap_lines=True,
                 scrollbar=False):
        self.future = Future()

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

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

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

        text_width = len(max(text.split('\n'), key=len)) + 2

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

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

        self.dialog = Dialog(title=title,
                             body=HSplit([Label(text=text), self.text_area]),
                             buttons=[ok_button, cancel_button],
                             width=width,
                             modal=True)
Exemple #24
0
def InputDialog(on_ok,
                on_cancel,
                title="",
                prompt="",
                ok_text="OK",
                cancel_text="Cancel",
                is_text_valid=lambda text: True) -> Dialog:
    """Returns a Dialogue component displaying a text input box"""
    def on_accept(buf):
        if is_text_valid(textfield.text):
            get_app().layout.focus(ok_button)
        return True  # Keep text.

    def on_ok_clicked():
        if is_text_valid(textfield.text):
            on_ok(textfield.text)

    ok_button = Button(text=ok_text, handler=on_ok_clicked)
    exit_button = Button(text=cancel_text, handler=on_cancel)

    textfield = TextArea(multiline=False, accept_handler=on_accept)

    dialog = Dialog(
        title=title,
        body=HSplit(
            [Label(text=prompt, dont_extend_height=True), textfield],
            padding=Dimension(preferred=1, max=1),
        ),
        buttons=[ok_button, exit_button],
        with_background=True)

    return dialog
    def __init__(self, title='', label_text='', completer=None):
        self.future = Future()

        def accept_text():
            get_app().layout.focus(ok_button)
            self.text_area.buffer.complete_state = None

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

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

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

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

        self.dialog = Dialog(
            title=title,
            body=HSplit([
                Label(text=label_text),
                self.text_area
            ]),
            buttons=[ok_button, cancel_button],
            width=D(preferred=80),
            modal=True)
Exemple #26
0
    def __init__(self) -> None:
        self.cmder_input = TextArea(
            height=1, multiline=False, wrap_lines=False, style="class:normal"
        )
        self.input = self.cmder_input

        self.status_bar = Label("Loading status bar...", style="class:status")

        self.console = Frame(
            TextArea(plover_text, focusable=False),
            title="Console",
            style="class:normal",
        )

        self.tape = Tape()
        self.suggestions = Suggestions()

        self.outputs = [self.console]

        self.container = HSplit(
            [
                DynamicContainer(lambda: VSplit(self.outputs)),
                DynamicContainer(lambda: self.input),
                self.status_bar,
            ]
        )
Exemple #27
0
def input_dialog(title='', text='', ok_text='OK', cancel_text='Cancel',
                 completer=None, password=False, style=None, async_=False):
    """
    Display a text input box.
    Return the given text, or None when cancelled.
    """
    def accept(buf):
        get_app().layout.focus(ok_button)
        return True  # Keep text.

    def ok_handler():
        get_app().exit(result=textfield.text)

    ok_button = Button(text=ok_text, handler=ok_handler)
    cancel_button = Button(text=cancel_text, handler=_return_none)

    textfield = TextArea(
        multiline=False,
        password=password,
        completer=completer,
        accept_handler=accept)

    dialog = Dialog(
        title=title,
        body=HSplit([
            Label(text=text, dont_extend_height=True),
            textfield,
        ], padding=D(preferred=1, max=1)),
        buttons=[ok_button, cancel_button],
        with_background=True)

    return _run_dialog(dialog, style, async_=async_)
Exemple #28
0
def radiolist_dialog(title: AnyFormattedText = '',
                     text: AnyFormattedText = '',
                     ok_text: str = 'Ok',
                     cancel_text: str = 'Cancel',
                     values: Optional[List[Tuple[_T,
                                                 AnyFormattedText]]] = None,
                     style: Optional[BaseStyle] = None) -> Application[_T]:
    """
    Display a simple list of element the user can choose amongst.

    Only one element can be selected at a time using Arrow keys and Enter.
    The focus can be moved between the list and the Ok/Cancel button with tab.
    """
    if values is None:
        values = []

    def ok_handler() -> None:
        get_app().exit(result=radio_list.current_value)

    radio_list = RadioList(values)

    dialog = Dialog(title=title,
                    body=HSplit([
                        Label(text=text, dont_extend_height=True),
                        radio_list,
                    ],
                                padding=1),
                    buttons=[
                        Button(text=ok_text, handler=ok_handler),
                        Button(text=cancel_text, handler=_return_none),
                    ],
                    with_background=True)

    return _create_app(dialog, style)
def yes_no_dialog(title='',
                  text='',
                  yes_text='Yes',
                  no_text='No',
                  style=None,
                  async_=False):
    """
    Display a Yes/No dialog.
    Return a boolean.
    """
    def yes_handler():
        get_app().exit(result=True)

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

    dialog = Dialog(title=title,
                    body=Label(text=text, dont_extend_height=True),
                    buttons=[
                        Button(text=yes_text, handler=yes_handler),
                        Button(text=no_text, handler=no_handler),
                    ],
                    with_background=True)

    return _run_dialog(dialog, style, async_=async_)
Exemple #30
0
    def init_layout(self):
        for i in range(len(self.top_screens)):
            s = self.top_screens[i]
            s.app = self
            s.screen_idx = i
            self.screen_sel_buttons.append(
                Button(text="%s %s" % (s.shortcut.upper(), s.shortcut_label),
                       handler=s.screen_sel))

        self.lbl_screen = Label(text=self.top_screens[0].title)

        self.top_screen = DynamicContainer(self.get_top_screen_container)

        btn_action = Button(text="F8 Action", handler=self.f_action)
        btn_exit = Button(text="F10 Exit", handler=self.f_exit)

        self.root_container = FloatContainer(
            HSplit([
                Box(
                    body=VSplit([self.lbl_screen], align="CENTER", padding=3),
                    style="class:button-bar",
                    height=1,
                ),
                self.top_screen,
                Box(
                    body=VSplit(self.screen_sel_buttons +
                                [btn_action, btn_exit],
                                align="CENTER",
                                padding=3),
                    style="class:button-bar",
                    height=1,
                ),
            ]), self.floats)
        self.top_layout = Layout(self.root_container,
                                 focused_element=self.screen_sel_buttons[0])