def __init__(self, title='', label_text='', completer=None): self.future = Future() def accept_text(buf): get_app().layout.focus(ok_button) buf.complete_state = None return True def accept(): self.future.set_result(self.text_area.text) def cancel(): self.future.set_result(None) self.text_area = TextArea(completer=completer, multiline=False, width=D(preferred=40), accept_handler=accept_text) ok_button = Button(text='OK', handler=accept) cancel_button = Button(text='Cancel', handler=cancel) self.dialog = Dialog(title=title, body=HSplit( [Label(text=label_text), self.text_area]), buttons=[ok_button, cancel_button], width=D(preferred=80), modal=True)
def progress_dialog(title: AnyFormattedText = '', text: AnyFormattedText = '', run_callback: Callable[ [Callable[[int], None], Callable[[str], None]], 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() 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)) dialog = Dialog(body=HSplit([ Box(Label(text=text)), Box(text_area, padding=D.exact(1)), progressbar, ]), title=title, with_background=True) app = _create_app(dialog, style) 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() # Run the callback in the executor. When done, set a return value for the # UI, so that it quits. def start() -> None: try: run_callback(set_percentage, log_text) finally: app.exit() def pre_run() -> None: run_in_executor_with_context(start) app.pre_run_callables.append(pre_run) return app
def input_dialog(title: AnyFormattedText = '', text: AnyFormattedText = '', ok_text: str = 'OK', cancel_text: str = 'Cancel', completer: Optional[Completer] = None, password: FilterOrBool = False, style: Optional[BaseStyle] = None) -> Application[str]: """ Display a text input box. Return the given text, or None when cancelled. """ def accept(buf: Buffer) -> bool: get_app().layout.focus(ok_button) return True # Keep text. def ok_handler() -> None: 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 _create_app(dialog, style)
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.
#!/usr/bin/env python """ Example usage of 'print_container', a tool to print any layout in a non-interactive way. """ from prompt_toolkit_dev.shortcuts import print_container from prompt_toolkit_dev.widgets import Frame, TextArea print_container( Frame( TextArea(text='Hello world!\n'), title='Stage: parse', ))
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'), ]), ]), )
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()
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(lexer=PygmentsLexer(HtmlLexer)) 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', 'ant', 'ape', 'bat', 'bear', 'beaver', 'bee', 'bison',
#!/usr/bin/env python """ A simple example of a a text area displaying "Hello World!". """ from prompt_toolkit_dev.application import Application from prompt_toolkit_dev.key_binding import KeyBindings from prompt_toolkit_dev.layout import Layout from prompt_toolkit_dev.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.
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():