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 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=[], )
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=[])
def make_canvas(_noise, args): global noise global debug_file global root_container noise = _noise ui = [ VSplit( [ Frame( title="Delete noise until only signal remains", body=Window(content=BufferControl(buffer=buffer)), ), Frame( title="Signals", body=Window(width=15, content=subcanvasses_display), ), Frame(title="Gaps", body=Window(width=10, content=gaps_display)), ] ), VSplit( [ Window(content=FormattedTextControl(text=legend_left)), Window(content=FormattedTextControl(text=legend_center)), Window( content=FormattedTextControl(text=legend_right), align=WindowAlign.RIGHT, ), ] ), ] if args.debug: debug_file = open(config.runtime.debug_log, "w") debug(f"cog started {datetime.now()}") ui.append(HorizontalLine()) ui.append(Window(content=debug_display)) root_container = HSplit(ui) subcanvasses.append(Data(Kind.signal, noise)) # start with the input noise as the signal buffer.text = noise kb = KeyBindings() @kb.add("c-c") def done(event): event.app.exit() # https://github.com/prompt-toolkit/python-prompt-toolkit/issues/502#issuecomment-466591259 sys.stdin = sys.stderr Application( key_bindings=kb, layout=Layout(root_container), editing_mode=EditingMode.VI ).run()
def __init__(self, lexer_name='yaml'): self.buf = Buffer() self.buf.text = '' self.lexer = PygmentsLexer(find_lexer_class_by_name(lexer_name)) self.window = HSplit([ HorizontalLine(), Window(content=BufferControl(buffer=self.buf, lexer=self.lexer)) ], height=Dimension(min=5, max=20, weight=1)) super(InfoWindow, self).__init__(content=self.window, filter=has_focus(self))
def _get_layout(self): self.message_output_field = TextArea(style="class:output-field") layout = HSplit([ HSplit(self.get_questions_widgets()), HorizontalLine(), self.message_output_field, ]) self.logger = WizardLogger(self.message_output_field) return layout
def _get_layout_folders(self): return flatten( map(lambda i: (HorizontalLine(), i.radio_list), self.folders))
def __enter__(self) -> Application: """Build a Layout and instantiate an Application around it.""" main = VSplit( ( # Command History on most of the left panel, Prompt at the bottom. HSplit( ( self.terminal, ConditionalContainer( Window( # Command Prompt. BufferControl(self.command_buffer, self.procs), dont_extend_height=True, wrap_lines=True, ), Condition(lambda: not self.busy()), ), ConditionalContainer( Window( # "Busy" Prompt, blocks Commands. FormattedTextControl("..."), height=1, ignore_content_width=True, ), Condition(self.busy), ), ConditionalContainer( Window( # Completion Bar. FormattedTextControl(lambda: self.handler.completion), height=1, ignore_content_width=True, style=self.style_meth, ), Condition(lambda: bool(self.handler.completion)), ), ) ), ConditionalContainer( # Vertical Line. HSplit( ( VerticalLine(), Window( FormattedTextControl( lambda: "├" if self.state is Mode.SCOPES else "│" ), width=1, height=1, ), VerticalLine(), ) ), Condition(lambda: self.state is not Mode.OFF), ), ConditionalContainer( # Scopes Panel. Visualizes nearby Space. HSplit( ( # Top-down visualization on the upper panel. Window( self.scope_topdown, ignore_content_height=True, ignore_content_width=True, ), HorizontalLine(), # Visualization from behind on the lower panel. Window( self.scope_horizon, ignore_content_height=True, ignore_content_width=True, ), ) ), Condition(lambda: self.state is Mode.SCOPES), ), ConditionalContainer( # Scans Panel. Lists nearby Objects. Window(self.scans, ignore_content_width=True), Condition(lambda: self.state is Mode.SCANS), ), ConditionalContainer( # Orders Panel. Shows future actions. Window(self.orders, ignore_content_width=True), Condition(lambda: self.state is Mode.ORDERS), ), ) ) root = Layout( HSplit( ( Window(self.header_bar, height=1, style=self.style_meth), FloatContainer(main, self.floating_elems), ) ) ) root.focus(self.command_buffer) self._app = Application(root, STYLE, full_screen=True, key_bindings=self.kb) return self._app
" - Type \"help\" to see available commands.\n" " - Press \"?\" for the list of keybindings.") entry_placeholder = Label( FormattedText([("class:placeholder", placeholder_text)])) task_list = HSplit([entry_placeholder]) agenda_pane = ScrollablePane(task_list) show_kb_help = False bindings_help = ConditionalContainer(Box( Shadow(Frame(Label(""), "Key bindings:"))), filter=Condition(lambda: show_kb_help)) root_container = FloatContainer( content=HSplit([agenda_pane, HorizontalLine(), history_field, input_field]), floats=[ Float( xcursor=True, ycursor=True, content=CompletionsMenu(max_height=16, scroll_offset=1), ), Float(bindings_help), ], ) key_bindings = KeyBindings() layout = Layout(root_container, focused_element=input_field) app: Application = Application(layout, full_screen=True, style=style,
def get_root_container(self) -> FloatContainer: score_store = Scores() with score_store: high_scores = score_store.get_scores(self._selected_game, self._selected_difficulty) score_table = format_scores(high_scores, sort_method=self._selected_sort, header_style=None) buttons = [ Button( "Sort By", width=MENU_BUTTON_WIDTH, handler=lambda: self.multi_screen.add_floating_screen( self._sort_select_screen), ), HorizontalLine(), Button("Back", width=MENU_BUTTON_WIDTH, handler=self.multi_screen.set_previous), ] menu_keybindings = _create_menu_keybindings(buttons) buttons_container = Frame( HSplit( buttons, width=Dimension(min=MENU_BUTTON_WIDTH, max=40), height=Dimension(), ), title="High Scores", key_bindings=menu_keybindings, ) difficulty_label_container = Box( Label( text=lambda: "Difficulty: {0}".format(self._selected_difficulty ), width=Dimension(min=40), ), padding=0, padding_left=1, ) high_scores_text_area = TextArea( text=score_table, read_only=True, scrollbar=True, wrap_lines=False, ) high_scores_text_area.window.cursorline = to_filter(True) high_scores_container = Box( high_scores_text_area, padding=0, padding_left=1, ) return FloatContainer( VSplit([ buttons_container, Frame( HSplit([ difficulty_label_container, HorizontalLine(), high_scores_container, ]), title=self._selected_game.game_name, ), ]), floats=[], )
def get_root_container(self) -> FloatContainer: buttons = [ Button("Play", width=MENU_BUTTON_WIDTH, handler=self._return_session), Button( "Difficulty", width=MENU_BUTTON_WIDTH, handler=lambda: self.multi_screen.add_floating_screen( self._difficulty_select_screen), ), Button("High Scores", width=MENU_BUTTON_WIDTH, handler=lambda: self.multi_screen.set_screen( self._high_score_screen)), HorizontalLine(), Button( "Back", width=MENU_BUTTON_WIDTH, handler=self.multi_screen.set_previous, ), ] menu_keybindings = _create_menu_keybindings(buttons) options_buttons_container = Frame( HSplit( buttons, width=Dimension(min=MENU_BUTTON_WIDTH, max=40), height=Dimension(), ), title="Options", key_bindings=menu_keybindings, ) difficulty_label_container = Box( Label( text=lambda: "Difficulty: {0}".format(self._selected_difficulty ), width=Dimension(min=40), ), padding=0, padding_left=1, ) game_description_container = Box( TextArea( text=self._selected_game.description, dont_extend_height=False, width=Dimension(min=40), read_only=True, scrollbar=True, wrap_lines=False, ), padding=0, padding_left=1, ) return FloatContainer(VSplit([ options_buttons_container, Frame( HSplit([ difficulty_label_container, HorizontalLine(), game_description_container, ]), title=self._selected_game.game_name, ), ]), floats=[])
def homeLayoutFactory(self): content = self.studio.content statusBar = Frame( Window(BufferControl(buffer=content.getBuffer("statusBar"), focusable=False), height=D(min=1, max=1, preferred=1), align=WindowAlign.CENTER)) savedModelsBox = Box(HSplit([ Label(text="Saved Models: ", style="class:blue class:underlined"), Window( BufferControl(buffer=content.getBuffer("savedModels"), focusable=False)) ]), padding=0) modelDefinitionsBox = Box(HSplit([ Label(text="Model Definitions: ", style="class:blue class:underlined"), Window( BufferControl(buffer=content.getBuffer("modelDefinitions"), focusable=False)) ]), padding=0) rightSidebar = Frame( HSplit([savedModelsBox, HorizontalLine(), modelDefinitionsBox])) createModelButton = Button("[C] Create Model ", handler=self.studio.layouts.swapper( Layouts.CREATE)) loadModelButton = Button("[L] Load Saved Model ", handler=self.studio.layouts.swapper( Layouts.LOAD)) importModelButton = Button("[I] Import Model From Definition ", handler=self.studio.layouts.swapper( Layouts.IMPORT)) editModelButton = Button("[E] Edit Model ", handler=self.studio.layouts.swapper( Layouts.EDIT)) deleteModelButton = Button("[D] Delete Model ", handler=self.studio.layouts.swapper( Layouts.DELETE)) quitButton = Button("[Q] Quit ", handler=self.studio.exit) editModelButton = ConditionalContainer( editModelButton, filter=self.studio.controller.modelExistsFilter()) leftSidebar = HSplit([ createModelButton, loadModelButton, importModelButton, editModelButton, deleteModelButton, quitButton, ]) creditBar = Label( text="Created by Samuel Ellertson - github.com/SamuelEllertson", style="class:blue") body = VSplit([Frame(Sizeable(leftSidebar)), Sizeable(rightSidebar)]) root = HSplit([statusBar, body, creditBar]) return Layout(container=root, focused_element=createModelButton)
def pager(title, text, lexer_name="", height=10, full_screen=False): """Small implementation of an editor/pager for small pieces of text. :param title: Title of the pager :type title: str :param text: Editable text :type text: str :param lexer_name: If the editable text should be highlighted with some kind of grammar, examples are ``yaml``, ``python`` ... :type lexer_name: str :param height: Max height of the text area :type height: int :param full_screen: Wether or not the text area should be full screen. :type full_screen: bool :return: Edited text, if saved, else None :rtype : str """ from prompt_toolkit import Application from prompt_toolkit.enums import EditingMode from prompt_toolkit.buffer import Buffer from prompt_toolkit.layout.containers import HSplit from prompt_toolkit.layout.layout import Layout from prompt_toolkit.key_binding import KeyBindings from prompt_toolkit.widgets import HorizontalLine from .utils.general import ( get_default_window, get_buffer_window ) assert(type(title) == str) assert(type(text) == str) assert(type(lexer_name) == str) assert(type(height) == int) assert(type(full_screen) == bool) buffer = Buffer() buffer.text = text # Define keybindings for pager key_bindings = KeyBindings() # Leave pager @key_bindings.add('c-c') def exit_(event): event.app.exit(0) # Leave pager and save edited text @key_bindings.add('c-a') def save_(event): event.app.return_text = buffer.text event.app.exit(1) class Pager(Application): return_text = None # Generate windows with titles and text, as well as define layout of pager text_window = get_buffer_window(buffer, height=height, lexer_name=lexer_name, style=user._tui_text_style) layout= Layout(HSplit([ get_default_window(text=title, style=user._tui_window_style), HorizontalLine(), text_window , get_default_window(text="Deny [Ctrl-c] Accept [Ctrl-a]", style=user._tui_window_style), ]) ) layout.focus(text_window) # Get object of class Pager, set layout, edit mode as well as key bindings and run the pager pager = Pager( editing_mode=( EditingMode.EMACS if user._tui_edit_mode == 'emacs' else EditingMode.VI ), layout=layout, key_bindings=key_bindings, full_screen=full_screen ) pager.run() # Return the edited text, if saved return pager.return_text
def __init__(self): super().__init__(None, None, HorizontalLine())
def make_app(fs): global append_to_log class PTK_STDOUT(): # our stdout def __init__(self, out): self.out = out def write(self, s): append(s, self.out) return len(s) def flush(self): pass class PTK_LOGGER(logging.StreamHandler): def __init__(self, level=logging.NOTSET, out=None): super().__init__(level) self.out = out def handle(self, record): append(record.getMessage(), self.out) def get_screen_size(): import fcntl import termios # Buffer for the C call buf = array.array(u'h', [0, 0, 0, 0]) fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ, buf) return (buf[0], buf[1]) def my_on_resize(old_rs_handler, fs): fill_top(fs) return old_rs_handler() # ---------------------------------------------------------------------- # prepare the layout rows, _ = get_screen_size() top = Label('', style='reverse') log = TextArea(height=int((rows - 4) / 2), scrollbar=True) out = TextArea(text='\n^c: clear input, ^l: redraw, ^q: quit\n', scrollbar=True) msg = Label('cwd is /', style='reverse') cli_args = [] # for cli_accept(), filled later def append(s, c=out): if not c: c.text += '\n---\n' if c == log: s = s.split('\n')[0][:get_screen_size()[1] - 2] + '\n' t = c.text + s c.buffer.document = Document(text=t, cursor_position=len(t) - 1) def cli_accept(buf): app, cli, fs = cli_args append('\n---\n> ' + cli.text + '\n') app.cmd.onecmd(cli.text) msg.text = 'cwd is ' + fs.getcwd() cli.buffer.history.append_string(cli.text) cli.text = '' def fill_top(fs): s1 = ' SSB Drive' # (v20180831)' s2 = '[uuid ' + fs.uuid() + '] ' w = get_screen_size()[1] top.text = s1 + ' ' * (w - len(s1) - len(s2)) + s2 cli = TextArea(multiline=False, accept_handler=cli_accept) bot = VSplit([Label('> ', dont_extend_width=True), cli]) top_container = HSplit([top, log, HorizontalLine(), out, msg, bot]) app = Application(Layout(top_container), key_bindings=kb, full_screen=True) cli_args += [app, cli, fs] # for cli_accept() app.cli = cli # for retrieving it in the keyboard handler app.layout.focus(cli) fill_top(fs) old_rs_resize = app._on_resize app._on_resize = lambda: my_on_resize(old_rs_resize, fs) app.stdout = PTK_STDOUT(out) # used for cmd logging.getLogger('packet_stream').addHandler(PTK_LOGGER(out=log)) return app
Window(FormattedTextControl(get_column_name(column)), width=10) for column in controller.view.visible_columns() ] ], height=1), # Display each row HSplit([ VSplit([ Window(FormattedTextControl(HTML(str(row))), width=2), *[ Window(FormattedTextControl(get_cell(cell)), width=10) for cell in controller.view.get_visible_cells(row, row=True) ] ]) for row in controller.view.visible_rows() ], height=controller.view.rows_to_show), HorizontalLine(), Window(content=FormattedTextControl( controller.view.get_current_cell_formula), height=1), ConditionalContainer(content=cell_input_dialog, filter=Condition(lambda: controller.input_mode)) ]) root_container = HSplit([ # Header for the columns name VSplit([ Window(FormattedTextControl(), width=10), *[ Window(FormattedTextControl(get_column_name(column)), width=10) for column in controller.view.visible_columns() ] ],
def demo(): txt1 = "Lorem ipsum dolor sit amet, consectetur adipiscing" txt2 = "Praesent eu ultrices massa. Cras et dui bibendum" txt3 = "Proin in varius purus. <b>Aliquam nec nulla</b>" sht1 = "Hello World" sht2 = "Buzz" sht3 = "The quick brown fox jumps over the lazy dog." kb = KeyBindings() @kb.add('c-c') def _(event): " Abort when Control-C has been pressed. " event.app.exit(exception=KeyboardInterrupt, style='class:aborting') @kb.add("tab") def _(event): event.app.layout.focus_next() @kb.add("s-tab") def _(event): event.app.layout.focus_previous() def abort(): " Abort when Control-C has been pressed. " get_app().exit(result=True) buffers = [TextArea(txt1, style="fg:ansigreen"), TextArea(txt2), TextArea(txt3)] def save(): x=list(get_app().layout.find_all_controls()) for y in buffers: try: print(y.text) print("--") except: pass table_1 = [ [Label('field1', style="fg:ansicyan"), buffers[0]], [Label('field2'), buffers[1]], [Label('field3'), buffers[2]] ] table_2 = [ [Button('Save', handler=save), Button('Abort',handler=abort)], ] # table = TextArea(txt2) layout = Layout( HSplit([ Table( table=table_1, column_widths=[D(10, 30), D(30, 80)], borders=RoundedBorder), HorizontalLine(), Table( table=table_2, column_widths=[D(10, 30), D(30, 80)], borders=RoundedBorder) ] ), ) return Application(layout, key_bindings=kb, full_screen=True)