def run(self): labels = self.neo4j.get_labels() relationship_types = self.neo4j.get_relationship_types() properties = self.neo4j.get_property_keys() if self.filename: with open(self.filename, "rb") as f: queries = split_queries_on_semicolons(f.read()) for query in queries: print("> " + query) self.handle_query(query) print() return click.secho(" ______ __ __ ______ __ __ ", fg="red") click.secho("/\ ___\ /\ \_\ \ /\ ___\ /\ \ /\ \ ", fg="yellow") click.secho("\ \ \____ \ \____ \ \ \ \____ \ \ \____ \ \ \ ", fg="green") click.secho(" \ \_____\ \/\_____\ \ \_____\ \ \_____\ \ \_\ ", fg="blue") click.secho(" \/_____/ \/_____/ \/_____/ \/_____/ \/_/ ", fg="magenta") print("Cycli version: {}".format(__version__)) print("Neo4j version: {}".format(".".join(map(str, self.neo4j.neo4j_version)))) print("Bug reports: https://github.com/nicolewhite/cycli/issues\n") completer = CypherCompleter(labels, relationship_types, properties) layout = create_prompt_layout( lexer=CypherLexer, get_prompt_tokens=get_tokens, reserve_space_for_menu=8, ) buff = CypherBuffer( accept_action=AcceptAction.RETURN_DOCUMENT, history=FileHistory(filename=os.path.expanduser('~/.cycli_history')), completer=completer, complete_while_typing=True, ) application = Application( style=PygmentsStyle(CypherStyle), buffer=buff, layout=layout, on_exit=AbortAction.RAISE_EXCEPTION, key_bindings_registry=CypherBinder.registry ) cli = CommandLineInterface(application=application, eventloop=create_eventloop()) try: while True: document = cli.run() query = document.text self.handle_query(query) except UserWantsOut: print("Goodbye!") except Exception as e: print(e)
def _build_cli(self, history): def set_vi_mode(value): self.vi_mode = value key_binding_manager = mssqlcli_bindings( get_vi_mode_enabled=lambda: self.vi_mode, set_vi_mode_enabled=set_vi_mode) def prompt_tokens(_): prompt = self.get_prompt() return [(Token.Prompt, prompt)] def get_continuation_tokens(cli, width): continuation = self.multiline_continuation_char * (width - 1) + ' ' return [(Token.Continuation, continuation)] get_toolbar_tokens = create_toolbar_tokens_func( lambda: self.vi_mode, None, None, None) layout = create_prompt_layout( lexer=PygmentsLexer(PostgresLexer), reserve_space_for_menu=self.min_num_menu_lines, get_prompt_tokens=prompt_tokens, get_continuation_tokens=get_continuation_tokens, get_bottom_toolbar_tokens=get_toolbar_tokens, display_completions_in_columns=self.wider_completion_menu, multiline=True, extra_input_processors=[ # Highlight matching brackets while editing. ConditionalProcessor( processor=HighlightMatchingBracketProcessor( chars='[](){}'), filter=HasFocus(DEFAULT_BUFFER) & ~IsDone()), ]) with self._completer_lock: buf = MssqlBuffer(auto_suggest=AutoSuggestFromHistory(), always_multiline=self.multi_line, multiline_mode=self.multiline_mode, completer=self.completer, history=history, complete_while_typing=Always(), accept_action=AcceptAction.RETURN_DOCUMENT) editing_mode = EditingMode.VI if self.vi_mode else EditingMode.EMACS application = Application( style=style_factory(self.syntax_style, self.cli_style), layout=layout, buffer=buf, key_bindings_registry=key_binding_manager.registry, on_exit=AbortAction.RAISE_EXCEPTION, on_abort=AbortAction.RETRY, ignore_case=True, editing_mode=editing_mode) cli = CommandLineInterface(application=application, eventloop=self.eventloop) return cli
def __init__(self, app_name, commands, completers={}, snippets_path=None): # Configure the application name. self.app_name = app_name # Initialize the interface of this app. self.interface = {} self.snippets_path = snippets_path self.completers = completers self.commands = commands self.__configure_bindings() self.__configure_layout() self.__configure_snippets() # Creating the application. self.app = Application(layout=self.body_layout, key_bindings=self.key_bindings, full_screen=True, editing_mode=EditingMode.VI) # Focus on command line self.app.layout.focus(self.input_container) self.add_object_to_interface("ooa", self)
def _create_cli(self): """Create the prompt_toolkit's CommandLineInterface.""" history = FileHistory(os.path.expanduser('~/.haxornewshistory')) toolbar = Toolbar(lambda: self.paginate_comments) layout = create_default_layout( message=u'haxor> ', reserve_space_for_menu=8, get_bottom_toolbar_tokens=toolbar.handler, ) cli_buffer = Buffer( history=history, auto_suggest=AutoSuggestFromHistory(), enable_history_search=True, completer=self.completer, complete_while_typing=Always(), accept_action=AcceptAction.RETURN_DOCUMENT) self.key_manager = self._create_key_manager() style_factory = StyleFactory(self.theme) application = Application( mouse_support=False, style=style_factory.style, layout=layout, buffer=cli_buffer, key_bindings_registry=self.key_manager.manager.registry, on_exit=AbortAction.RAISE_EXCEPTION, on_abort=AbortAction.RETRY, ignore_case=True) eventloop = create_eventloop() self.cli = CommandLineInterface( application=application, eventloop=eventloop)
def make_app(path_to_checklist, new_session): session = ChecklistSession(path_to_checklist, new_session) checklist = session.load() def status_bar_text(): items = checklist.items() return "{name} : {checked}/{total} done | 'q': quit | 'z': undo | '?' help | <up>/<down> moves | <space> toggles".format( name=checklist.name, checked=len([i for i in items if i.checked]), total=len(items)) checklist_window = Window(ChecklistControl(checklist, session), left_margins=[NumberedMargin()], right_margins=[ ScrollbarMargin(display_arrows=True), ]) status_bar_window = Window(content=FormattedTextControl(status_bar_text), height=1, style='reverse') root_container = FloatContainer( content=HSplit([ checklist_window, status_bar_window, ]), floats=[], ) if session.duplicates: root_container.floats.append( Float(content=DuplicatesWarningDialog(session.duplicates))) return Application(layout=Layout(root_container), full_screen=True, key_bindings=build_key_bindings())
def editor_window(self): """configure the editor window and returns a application class""" self.buffer_1 = Buffer() # need the text in another method self.text = self.open_file() f_ext = pathlib.PurePath(self.file_abs_path).suffix # set container(s) self.buffer_1.text = self.text style_n = style_from_pygments_cls(get_style_by_name("friendly")) container = Window( BufferControl(buffer=self.buffer_1, lexer=syntax_highlight(f_ext))) # create layout layout_editor = Layout(container) # make an instance from keybinds method key_bind = self.key_binds("") # define application that will be started app = Application(layout=layout_editor, key_bindings=key_bind, full_screen=True, style=style_n) return app
def __init__(self, inpipe): self.inpipe = inpipe self.tempfile = tempfile.NamedTemporaryFile(mode="w", delete=True) self.initialize_nodes() root = VSplit( [ # Input buffer and status line HSplit( [ self.first_line, Window( content=BufferControl( buffer=self.input_buffer, # This lexer is disabled for now because # I don't want to mess with colourschemes # lexer=PygmentsLexer(PythonLexer), ) ), self.error_output, ], width=Dimension(), ), Window(width=1, char="|"), # Output display area Window(ignore_content_width=True, content=self.output, wrap_lines=True), ], width=Dimension(), ) layout = Layout(root) self.app = Application(layout=layout, key_bindings=kb, full_screen=True)
def initialize(self): history = InMemoryHistory() toolbar_handler = create_toolbar_handler(self.get_long_options) layout = create_prompt_layout( get_prompt_tokens=self.get_prompt_tokens, lexer=create_lexer(), get_bottom_toolbar_tokens=toolbar_handler) buf = Buffer(history=history, completer=CrutchCompleter(self.renv), complete_while_typing=Always(), accept_action=AcceptAction.RETURN_DOCUMENT) manager = get_key_manager(self.set_long_options, self.get_long_options) application = Application(style=style_factory(), layout=layout, buffer=buf, key_bindings_registry=manager.registry, on_exit=AbortAction.RAISE_EXCEPTION, on_abort=AbortAction.RETRY, ignore_case=True) eventloop = create_eventloop() self.cli = CommandLineInterface(application=application, eventloop=eventloop)
def _build_cli(self): layout = create_prompt_layout( message='{0}> '.format(self.args['username']), lexer=PygmentsLexer(SqlLexer), ) buf = Buffer(completer=self.completer, history=self.history, complete_while_typing=Always(), accept_action=AcceptAction.RETURN_DOCUMENT) key_binding_manager = KeyBindingManager( enable_abort_and_exit_bindings=True, ) application = Application( layout=layout, buffer=buf, key_bindings_registry=key_binding_manager.registry, on_exit=AbortAction.RAISE_EXCEPTION, on_abort=AbortAction.RETRY, ignore_case=True) cli = CommandLineInterface(application=application, eventloop=self.eventloop) return cli
def __init__(self, nb_path: str): self.nb_path = nb_path self.cells: List[Cell] = [] self.executing_cells: List[Cell] = [] self.nb_json: Dict[str, Any] = {} self.key_bindings = KeyBindings() self.bind_keys() if os.path.exists(nb_path): self.read_nb() else: self.create_nb() self.create_layout() self._current_cell = self.cells[0] self._cell_entered = False self.app: Application = Application(layout=self.layout, key_bindings=self.key_bindings, full_screen=True) kernel_name = self.nb_json["metadata"]["kernelspec"]["name"] try: self.kd = kernel_driver.KernelDriver(kernel_name=kernel_name, log=False) kernel_driver.driver._output_hook_default = self._output_hook except RuntimeError: self.kd = None self.focus(0) self.execution_count = 0 self.idle = None asyncio.run(self.main())
def run(): validate_osenvironment() print_banner() cli_buffer = OSBuffer() ltobj = OSLayout(multiwindow=False) application = Application(style=PygmentsStyle(OSStyle), layout=ltobj.layout, buffers=cli_buffer.buffers, on_exit=AbortAction.RAISE_EXCEPTION, key_bindings_registry=OSKeyBinder.registry) cli = CommandLineInterface(application=application, eventloop=create_eventloop()) while True: try: document = cli.run(reset_current_buffer=True) process_document(document) except KeyboardInterrupt: # A keyboardInterrupt generated possibly due to Ctrl-C print "Keyboard Interrupt Generated" continue except EOFError: print "cntl-D" sys.exit()
async def show_cli_widget(widget): from prompt_toolkit import Application from prompt_toolkit.layout import Layout app = Application(full_screen=False, layout=Layout(widget), mouse_support=True) return await app.run_async()
def __init__(self, manager: mp.Manager, shared_state: dict, rpc_channel: mp.Queue): self.manager = manager self.shared_state = shared_state self.rpc_channel = rpc_channel self.fileman = Filemanager(self) self.fileman_visible = True self.toolbar = Toolbar(self) self.views = OrderedDict() # type: Dict[str, SimpleView] self.app = Application( full_screen=True, mouse_support=True, color_depth=ColorDepth.DEPTH_24_BIT, clipboard=InMemoryClipboard(), enable_page_navigation_bindings=False, # key_bindings=get_filemanager_kb() layout=Layout( container=HSplit([ DynamicContainer(self._get_children), DynamicContainer(lambda: self.toolbar) ]), # focused_element=(self.current_view or self.fileman).input_field, ), )
def __init__(self): self.app = Application( layout=mainlayout.mainlay(), key_bindings=keybinds.mainkeybinds, full_screen=True, mouse_support=True, )
def main(): # vytvoření aplikace s textovým uživatelským rozhraním application = Application(layout=layout, key_bindings=key_bindings, full_screen=True) # spuštění aplikace application.run()
def __init__(self, maze_grid: MazeGrid) -> None: self._maze_screen = MazeScreen(self, maze_grid) self._global_keybindings = self._create_global_keybindings() app = Application(style=GUI_STYLE, key_bindings=self._global_keybindings) super().__init__(app, self._maze_screen)
def __init__(self, table: Table) -> None: self._table_screen = TableScreen(self, table) self._global_keybindings = self._create_global_keybindings() app = Application(style=GUI_STYLE, key_bindings=self._global_keybindings) super().__init__(app, self._table_screen)
def __init__(self, tree: TreeNode, closure_table: ClosureTable) -> None: self._tree_screen = TreeScreen(self, tree, closure_table) self._global_keybindings = self._create_global_keybindings() app = Application(style=GUI_STYLE, key_bindings=self._global_keybindings) super().__init__(app, self._tree_screen)
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 _build_cli(self): eventloop = create_eventloop() if self._options.persistent_history: history = FileHistory( os.path.join( os.path.expanduser("~"), ".{}_history".format(self._ctx.binary_name) ) ) else: history = InMemoryHistory() layout = create_prompt_layout( lexer=PygmentsLexer(NubiaLexer), reserve_space_for_menu=5, get_prompt_tokens=self.get_prompt_tokens, get_rprompt_tokens=self._status_bar.get_rprompt_tokens, get_bottom_toolbar_tokens=self._status_bar.get_tokens, display_completions_in_columns=False, multiline=True, extra_input_processors=[ ConditionalProcessor( processor=HighlightMatchingBracketProcessor(chars="[](){}"), filter=HasFocus(DEFAULT_BUFFER) & ~IsDone(), ) ], ) buf = Buffer( completer=self._completer, history=history, auto_suggest=self._suggestor, complete_while_typing=Always(), accept_action=AcceptAction.RETURN_DOCUMENT, ) # If EDITOR does not exist, take EMACS # if it does, try fit the EMACS/VI pattern using upper editor = getattr( EditingMode, os.environ.get("EDITOR", EditingMode.EMACS).upper(), EditingMode.EMACS, ) application = Application( style=shell_style, buffer=buf, editing_mode=editor, key_bindings_registry=self._registry, layout=layout, on_exit=AbortAction.RAISE_EXCEPTION, on_abort=AbortAction.RETRY, ignore_case=True, ) cli = CommandLineInterface(application=application, eventloop=eventloop) return cli
async def app_main(): app = Application( layout=root_con, full_screen=True, key_bindings=kb ) await app.run_async()
def cli(): app = Application(full_screen=True, layout=LAYOUT, style=patched_style(), color_depth=ColorDepth.TRUE_COLOR, key_bindings=KG) app.editing_mode = EditingMode.VI app.run() shortcuts.clear_title()
def show(self): self.key_bindings = PtKeyBindings() self.bind_keys() self.create_layout() self.app = Application(layout=self.layout, key_bindings=self.key_bindings, full_screen=True) self.focus(0) asyncio.run(self._show())
def __init__(self, command, refresh_interval=2): self.setup_layout() self._command = command self._app = Application(layout=self._layout, key_bindings=self.generate_keybindings(), full_screen=False, erase_when_done=True, before_render=self.refresh, min_redraw_interval=refresh_interval)
def __init__(self, challenge_grid: PatternGrid, solution_grids: List[PatternGrid]) -> None: self._pattern_screen = PatternScreen(self, challenge_grid, solution_grids) self._global_keybindings = self._create_global_keybindings() app = Application(style=GUI_STYLE, key_bindings=self._global_keybindings) super().__init__(app, self._pattern_screen)
def __init__(self) -> None: self._global_keybindings = self._create_global_keybindings() self._game_select_screen = GameSelectScreen(self) app = Application(style=GUI_STYLE, full_screen=True, mouse_support=True, key_bindings=self._global_keybindings) super().__init__(app, self._game_select_screen)
def _create_cli(self): """Creates the prompt_toolkit's CommandLineInterface. Args: * None. Returns: None. """ history = FileHistory(os.path.expanduser('~/.saws-history')) toolbar = Toolbar(self.get_color, self.get_fuzzy_match, self.get_shortcut_match) layout = create_default_layout( message='saws> ', reserve_space_for_menu=8, lexer=CommandLexer, get_bottom_toolbar_tokens=toolbar.handler, extra_input_processors=[ ConditionalProcessor( processor=HighlightMatchingBracketProcessor( chars='[](){}'), filter=HasFocus(DEFAULT_BUFFER) & ~IsDone()) ] ) cli_buffer = Buffer( history=history, auto_suggest=AutoSuggestFromHistory(), enable_history_search=True, completer=self.completer, complete_while_typing=Always(), accept_action=AcceptAction.RETURN_DOCUMENT) self.key_manager = KeyManager( self.set_color, self.get_color, self.set_fuzzy_match, self.get_fuzzy_match, self.set_shortcut_match, self.get_shortcut_match, self.refresh_resources_and_options, self.handle_docs) style_factory = StyleFactory(self.theme) application = Application( mouse_support=False, style=style_factory.style, layout=layout, buffer=cli_buffer, key_bindings_registry=self.key_manager.manager.registry, on_exit=AbortAction.RAISE_EXCEPTION, on_abort=AbortAction.RETRY, ignore_case=True) eventloop = create_eventloop() self.aws_cli = CommandLineInterface( application=application, eventloop=eventloop)
def loop(cmd, history_file): buf = create_buffer(cmd, history_file) key_bindings = KeyBindings() bind_keys(buf, key_bindings) layout = create_layout( buffer=buf, multiline=True, lexer=SqlLexer, extra_input_processors=[ ConditionalProcessor( processor=HighlightMatchingBracketProcessor(chars='[](){}'), filter=HasFocus(DEFAULT_BUFFER) & ~IsDone()) ], get_bottom_toolbar_tokens=lambda: get_toolbar_tokens(cmd), get_prompt_tokens=lambda: [('class:prompt', 'cr> ')]) output = get_default_output() app = Application(layout=layout, style=style_from_pygments_cls(CrateStyle), key_bindings=merge_key_bindings( [key_bindings, load_open_in_editor_bindings()]), editing_mode=_get_editing_mode(), output=output) cmd.get_num_columns = lambda: output.get_size().columns while True: try: text = app.run() if text: cmd.process(text) buf.reset() except ProgrammingError as e: if '401' in e.message: username = cmd.username password = cmd.password cmd.username = input('Username: '******'Bye!') return
def _build_cli(self, history): def set_vi_mode(value): self.vi_mode = value key_binding_manager = pgcli_bindings( get_vi_mode_enabled=lambda: self.vi_mode, set_vi_mode_enabled=set_vi_mode) def prompt_tokens(_): return [(Token.Prompt, '%s> ' % self.pgexecute.dbname)] def get_continuation_tokens(cli, width): return [(Token.Continuation, '.' * (width - 1) + ' ')] get_toolbar_tokens = create_toolbar_tokens_func( lambda: self.vi_mode, self.completion_refresher.is_refreshing) layout = create_prompt_layout( lexer=PygmentsLexer(PostgresLexer), reserve_space_for_menu=4, get_prompt_tokens=prompt_tokens, get_continuation_tokens=get_continuation_tokens, get_bottom_toolbar_tokens=get_toolbar_tokens, display_completions_in_columns=self.wider_completion_menu, multiline=True, extra_input_processors=[ # Highlight matching brackets while editing. ConditionalProcessor( processor=HighlightMatchingBracketProcessor( chars='[](){}'), filter=HasFocus(DEFAULT_BUFFER) & ~IsDone()), ]) with self._completer_lock: buf = PGBuffer(always_multiline=self.multi_line, completer=self.completer, history=history, complete_while_typing=Always(), accept_action=AcceptAction.RETURN_DOCUMENT) application = Application( style=style_factory(self.syntax_style, self.cli_style), layout=layout, buffer=buf, key_bindings_registry=key_binding_manager.registry, on_exit=AbortAction.RAISE_EXCEPTION, on_abort=AbortAction.RETRY, ignore_case=True) cli = CommandLineInterface(application=application) return cli
def __init__( self, store: FullNodeStore, blockchain: Blockchain, server: ChiaServer, port: int, parent_close_cb: Callable, ): self.port: int = port self.store: FullNodeStore = store self.blockchain: Blockchain = blockchain self.node_server: ChiaServer = server self.connections: PeerConnections = server.global_connections self.logs: List[logging.LogRecord] = [] self.app: Optional[Application] = None self.closed: bool = False self.num_blocks: int = 10 self.num_top_block_pools: int = 5 self.top_winners: List[Tuple[uint64, bytes32]] = [] self.our_winners: List[Tuple[uint64, bytes32]] = [] self.prev_route: str = "home/" self.route: str = "home/" self.focused: bool = False self.parent_close_cb = parent_close_cb self.kb = self.setup_keybindings() self.style = Style([("error", "#ff0044")]) self.pool_pks: List[PublicKey] = [] key_config_filename = os.path.join(ROOT_DIR, "config", "keys.yaml") if os.path.isfile(key_config_filename): config = safe_load(open(key_config_filename, "r")) self.pool_pks = [ PrivateKey.from_bytes(bytes.fromhex(ce)).get_public_key() for ce in config["pool_sks"] ] self.draw_initial() self.app = Application( style=self.style, layout=self.layout, full_screen=True, key_bindings=self.kb, mouse_support=True, ) self.closed = False self.update_ui_task = asyncio.get_running_loop().create_task( self.update_ui()) self.update_data_task = asyncio.get_running_loop().create_task( self.update_data())