Esempio n. 1
0
def test_basic_html():
    html = HTML('<i>hello</i>')
    assert to_formatted_text(html) == [('class:i', 'hello')]

    html = HTML('<i><b>hello</b></i>')
    assert to_formatted_text(html) == [('class:i,b', 'hello')]

    html = HTML('<i><b>hello</b>world<strong>test</strong></i>after')
    assert to_formatted_text(html) == [
        ('class:i,b', 'hello'),
        ('class:i', 'world'),
        ('class:i,strong', 'test'),
        ('', 'after'),
    ]

    # It's important that `to_formatted_text` returns a `FormattedText`
    # instance. Otherwise, `print_formatted_text` won't recognise it and will
    # print a list literal instead.
    assert isinstance(to_formatted_text(html), FormattedText)
Esempio n. 2
0
    def bottom_toolbar():
        if swapped[0]:
            on = 'on=true'
        else:
            on = 'on=false'

        return HTML(
            'Press <style bg="#222222" fg="#ff8888">[control-t]</style> '
            'to swap between dark/light colors. '
            '<style bg="ansiblack" fg="ansiwhite">[%s]</style>') % on
Esempio n. 3
0
    def run(self):
        try:
            self.__open_brain()
        except Exception as ex:
            print(HTML(f"<style fg='ansired'>Unable to open brain: {ex}</style>"))

        command = ""
        while command != "/q":
            try:
                command = self.__prompt().strip()
                if command.startswith("/"):
                    self.__execute(command)
                else:
                    self.__execute("/activate-thought " + command)
            except CommandException as ex:
                print(HTML(f"<style fg='ansired'>{ex.message}</style>"))
                print(ex.__traceback__)
            except Exception as ex:
                print(HTML(f"<style fg='ansired'>{ex}</style>"))
Esempio n. 4
0
def options_to_html(
    options: Sequence[Tuple[RadioListType, AnyFormattedText]],
) -> Sequence[Tuple[RadioListType, AnyFormattedText]]:
    formatted_options: List[Tuple[RadioListType, AnyFormattedText]] = []

    for option in options:
        option_text = HTML(cast(str, option[1]))
        formatted_options.append((option[0], option_text))

    return formatted_options
Esempio n. 5
0
def create_pager_prompt(
    style: BaseStyle, title: AnyFormattedText = ""
) -> PromptSession[PagerResult]:
    """
    Create a "continue" prompt for paginated output.
    """
    bindings = KeyBindings()

    @bindings.add("enter")
    @bindings.add("down")
    def next_line(event: KeyPressEvent) -> None:
        event.app.exit(result=PagerResult.NEXT_LINE)

    @bindings.add("space")
    def next_page(event: KeyPressEvent) -> None:
        event.app.exit(result=PagerResult.NEXT_PAGE)

    @bindings.add("a")
    def print_all(event: KeyPressEvent) -> None:
        event.app.exit(result=PagerResult.PRINT_ALL)

    @bindings.add("q")
    @bindings.add("c-c")
    @bindings.add("c-d")
    @bindings.add("escape", eager=True)
    def no(event: KeyPressEvent) -> None:
        event.app.exit(result=PagerResult.ABORT)

    @bindings.add("<any>")
    def _(event: KeyPressEvent) -> None:
        "Disallow inserting other text."
        pass

    style

    session: PromptSession[PagerResult] = PromptSession(
        merge_formatted_text(
            [
                title,
                HTML(
                    "<status-toolbar>"
                    "<more> -- MORE -- </more> "
                    "<key>[Enter]</key> Scroll "
                    "<key>[Space]</key> Next page "
                    "<key>[a]</key> Print all "
                    "<key>[q]</key> Quit "
                    "</status-toolbar>: "
                ),
            ]
        ),
        key_bindings=bindings,
        erase_when_done=True,
        style=style,
    )
    return session
Esempio n. 6
0
File: log.py Progetto: Be5yond/gf
def row(cmt, num, ins, de):
    message = cmt.message.split('\n')[0]

    # 添加分支和tag信息
    try:
        for ref in repo.remote().refs:
            if cmt == ref.commit:
                message = f'<b><style bg="ansired" fg="ansiwhite">[️{ref.name}]</style></b>' + message
    except NoSectionError:
        # 处理未关联remote分支的场景
        pass
    for tag in repo.tags:
        if cmt == tag.commit:
            message = f'<b><style bg="ansiyellow" fg="ansiblack">[️Tag:{tag.name}]</style></b>' + message
    for head in repo.heads:
        if cmt == head.commit:
            message = f'<b><style bg="ansigreen" fg="ansiblack">[️{head.name}]</style></b>' + message
    if cmt == repo.head.commit:
        message = '<b><style bg="ansiblue" fg="ansiblack">[HEAD]</style></b>' + message

    try:
        message = HTML(message)
    except xml.parsers.expat.ExpatError:
        # messge中包含特殊字符时
        pass

    return VSplit([
        Window(content=FormattedTextControl(f'{num}'), width=5),
        Window(width=1, char="|"),
        Window(content=FormattedTextControl(cmt.hexsha[:7]), width=9),
        Window(width=1, char="|"),
        Window(content=FormattedTextControl(cmt.committer.name), width=20),
        Window(width=1, char="|"),
        Window(content=FormattedTextControl(
            cmt.committed_datetime.strftime('%Y-%m-%d %H:%M:%S')),
               width=21),
        Window(width=1, char="|"),
        Label(HTML(f'<b><style fg="ansigreen">+{ins}</style></b>'), width=5),
        Label(HTML(f'<b><style fg="ansired">-{de}</style></b>'), width=5),
        Window(width=1, char="|"),
        Label(message)
    ])
Esempio n. 7
0
 def commit_type():
     result = radiolist_dialog(
         title=HTML(f'Choose a commit type: (Press {ansired("Enter")} to confirm, {ansired("Ctrl+C")} to cancel.)'),
         values=[
             (emoji.Commit.FEATURE.value, HTML(f'<style bg="orange" fg="black">{emoji.Commit.FEATURE.value}[feature]:  新功能</style>')),
             (emoji.Commit.BUGFIX.value, HTML(f'<style bg="green" fg="black">{emoji.Commit.BUGFIX.value}[bugfix]:   修复问题</style>')),
             (emoji.Commit.REFACTOR.value, HTML(f'<style bg="red" fg="black">{emoji.Commit.REFACTOR.value}[refactor]: 重构</style>')),
             (emoji.Commit.CHORE.value, HTML(f'<style bg="blue" fg="black">{emoji.Commit.CHORE.value}[chore]:    工具依赖变动</style>')),
             (emoji.Commit.DOCUMENT.value, HTML(f'<style bg="gray" fg="white">{emoji.Commit.DOCUMENT.value}[document]: 文档或注释</style>')),
             (emoji.Commit.STYLE.value, HTML(f'<style bg="gray" fg="white">{emoji.Commit.STYLE.value}[style]:    格式</style>')),
             (emoji.Commit.TEST.value, HTML(f'<style bg="gray" fg="white">{emoji.Commit.TEST.value}[test]:     添加测试</style>'))
         ])
     return result
Esempio n. 8
0
def test_html_interpolation():
    # %-style interpolation.
    value = HTML("<b>%s</b>") % "hello"
    assert to_formatted_text(value) == [("class:b", "hello")]

    value = HTML("<b>%s</b>") % ("hello", )
    assert to_formatted_text(value) == [("class:b", "hello")]

    value = HTML("<b>%s</b><u>%s</u>") % ("hello", "world")
    assert to_formatted_text(value) == [("class:b", "hello"),
                                        ("class:u", "world")]

    # Format function.
    value = HTML("<b>{0}</b><u>{1}</u>").format("hello", "world")
    assert to_formatted_text(value) == [("class:b", "hello"),
                                        ("class:u", "world")]

    value = HTML("<b>{a}</b><u>{b}</u>").format(a="hello", b="world")
    assert to_formatted_text(value) == [("class:b", "hello"),
                                        ("class:u", "world")]
Esempio n. 9
0
def select_keys_directory(network):
    # Prompt the user for a directory that contains keys he generated already for the selected
    # network

    valid_keys_directory = False
    entered_directory = None
    input_canceled = False

    while not valid_keys_directory:
        not_valid_msg = ''
        if entered_directory is not None:
            not_valid_msg = ('''

<style bg="red" fg="black">Your last input was <b>not a valid keys directory</b>. Please make sure to enter a
valid keys directory.</style>''')

        entered_directory = input_dialog(title='Keys directory',
                                         text=(HTML(f'''
Please enter the directory in which we can find the keys you generated. It
should include all the files that the eth2.0-deposit-cli tool created
including:

- deposit_data(...).json
- keystore-(...).json

When creating your keys offline or elsewhere, make sure you select the
correct network: {network.capitalize()}

* Press the tab key to switch between the controls below{not_valid_msg}
'''))).run()

        if not entered_directory:
            input_canceled = True
            break

        tilde_index = entered_directory.find('~')
        if tilde_index != -1:
            entered_directory = entered_directory.replace(
                '~', str(Path.home()), 1)

        entered_directory = Path(entered_directory)

        if not entered_directory.is_dir():
            continue

        generated_keys = search_for_generated_keys(entered_directory)
        if (generated_keys['deposit_data_path'] is not None
                and len(generated_keys['keystore_paths']) > 0):
            valid_keys_directory = True

    if input_canceled:
        return ''

    return entered_directory
Esempio n. 10
0
def test_html_interpolation():
    # %-style interpolation.
    value = HTML('<b>%s</b>') % 'hello'
    assert to_formatted_text(value) == [('class:b', 'hello')]

    value = HTML('<b>%s</b>') % ('hello', )
    assert to_formatted_text(value) == [('class:b', 'hello')]

    value = HTML('<b>%s</b><u>%s</u>') % ('hello', 'world')
    assert to_formatted_text(value) == [('class:b', 'hello'),
                                        ('class:u', 'world')]

    # Format function.
    value = HTML('<b>{0}</b><u>{1}</u>').format('hello', 'world')
    assert to_formatted_text(value) == [('class:b', 'hello'),
                                        ('class:u', 'world')]

    value = HTML('<b>{a}</b><u>{b}</u>').format(a='hello', b='world')
    assert to_formatted_text(value) == [('class:b', 'hello'),
                                        ('class:u', 'world')]
Esempio n. 11
0
 def apply_transformation(self, ti):
     try:
         fragments = to_formatted_text(
             HTML(fragment_list_to_text(ti.fragments)))
     except Exception as ex:
         # xml.parsers.expat.ExpatError
         # not well-formed (invalid token): line 1, column 138
         logger.error('FormatText: {} {}'.format(type(ex), str(ex)))
         #return Transformation([('', ' ')])
         return Transformation([])
     return Transformation(fragments)
Esempio n. 12
0
    async def show_notification(self, message: str, timeout: int):
        """
        Shows notification in the reserved space for `timeout` and then hides

        :param message: Message to display
        :param timeout: Timeout
        """
        self.notification_text = HTML(
            f'<style bg="white" color="black">[ {message} ]</style>')
        await asyncio.sleep(timeout)
        self.notification_text = None
Esempio n. 13
0
def example_2():
    """
    Using HTML for the formatting.
    """
    answer = prompt(HTML('<username>john</username><at>@</at>'
                         '<host>localhost</host>'
                         '<colon>:</colon>'
                         '<path>/user/john</path>'
                         '<style bg="#00aa00" fg="#ffffff">#</style> '),
                    style=style)
    print('You said: %s' % answer)
Esempio n. 14
0
 def rprompt(self):
     brain = self.__api.brains.active
     if not brain:
         return ""
     if not brain.active_thought:
         return ""
     if brain.active_thought.has_component("taxonomy"):
         category = brain.active_thought.taxonomy.category or ""
         tags = ", ".join(sorted(brain.active_thought.taxonomy.tags))
         return HTML(f"<style bg='#ff0066'>{category}</style> <style bg='#6600ff'>{tags}</style>")
     return ""
Esempio n. 15
0
def display_analysis_screen(event, game_list, game_number, moves, move_place,
                            analysis_archive):
    chess_text = set_analysis_chess_text(game_list, game_number, moves,
                                         move_place, analysis_archive)
    event.app.layout.container.children[2].content.text = HTML(chess_text)

    set_analysis_history_text(event, game_list, game_number, move_place,
                              analysis_archive)

    event.app.renderer._last_size: Optional[Size] = None
    event.app.renderer.output.flush()
Esempio n. 16
0
 def format(
     self,
     progress_bar: "Progress",
     progress: "PlayerModel",
     width: int,
 ) -> AnyFormattedText:
     if not isinstance(progress, PlayerModel):
         return ''
     player: PlayerModel = progress
     return HTML("<video-file>{text}</video-file>").format(
         text=self.get_render_text(player))
Esempio n. 17
0
    def format(self, progress_bar: 'ProgressBar',
               progress: 'ProgressBarCounter', width: int) -> AnyFormattedText:

        time_left = progress.time_left
        if time_left is not None:
            formatted_time_left = _format_timedelta(time_left)
        else:
            formatted_time_left = self.unknown

        return HTML(
            self.template).format(time_left=formatted_time_left.rjust(width))
Esempio n. 18
0
def _rmove(group, deltas, refresh_period=0.1, bar_options=None):
    start_states = group.get_states()
    start_positions = group.get_pos()
    final_positions = [p + d for p, d in zip(start_positions, deltas)]
    motion = Motion(
        group, start_states, start_positions, start_positions, final_positions
    )

    def motion_loop(gen):
        for states, positions in gen_rate_limiter(gen, refresh_period):
            prog_bar.update(states, positions)

    def on_ok():
        nonlocal title
        title = HTML("<done>Finished!</done>")

    def on_error(error):
        nonlocal title
        group.start_stop()
        kb = isinstance(error, KeyboardInterrupt)
        if kb:
            msg = "<ctrlc>Stopping... </ctrlc>"
        else:
            msg = "<error>Motion error: {!r}<error>. ".format(error)
            msg += "Waiting for motors to stop..."
        title = HTML(msg)
        motion_loop(gen_motion(group))
        title = HTML(msg + "[<done>DONE</done>]")

    def always_end_with():
        prog_bar.update(group.get_states(), group.get_pos())

    title = HTML("<preparing>Preparing...</preparing>")
    bar_options = bar_options or {}
    bar_options.setdefault("title", lambda: title)
    prog_bar = MotionProgressBar(motion, bar_options=bar_options)
    power = ensure_power(group)
    handler = MotionHandler(on_ok, on_error, always_end_with)
    with prog_bar, power, handler:
        title = HTML("<moving>Moving...</moving>")
        motion_loop(gen_rmove(group, deltas))
Esempio n. 19
0
async def update_spots(application):
    """
    Coroutine that updates spots
    """
    lasthash = ""
    try:
        while True:
            r = requests.get(
                'http://www.dxsummit.fi/DxSpots.aspx?count=50&include_modes=PHONE')
            cleantext = BeautifulSoup(r.text, "lxml").get_text()
            currenthash = hashlib.md5(cleantext.encode('utf-8')).hexdigest()

            clusterdata = []

            i = 0
            for line in cleantext.splitlines():
                line = line[:73] + ':' + line[73:]
                #line = line[:76] + line[84:]
                cleanline = ' '.join(line.split())
                splitstring = cleanline.split(sep=" ", maxsplit=3)
                clusterdata.append(
                    (hashlib.md5(line.encode('utf-8')).hexdigest() + " " + splitstring[1]+" "+splitstring[2], " " + line))
                data = cleanline.split(sep=" ", maxsplit=3)
                if ((auto_tune.checked is True) and (i == 0) and (data[2] != globalvars['lastcall'])):
                    globalvars['lastcall'] = data[2]
                    frequency.content=FormattedTextControl(HTML('<b fg="#884444">Freq.:</b> ' + (data[1] + " Khz").rjust(15)))
                    dx.content=FormattedTextControl(HTML('<b fg="#884444">Call:</b> ' + data[2].rjust(12)))
                    if qrz.checked is True:
                        redis.rpush('qrzLookupQueue',data[2])
                i+=1

            radios.values = clusterdata

            if currenthash != lasthash:
                application.invalidate()
                await asyncio.sleep(15)
            else:
                await asyncio.sleep(30)
    except asyncio.CancelledError:
        #TODO safe config here ?
        print()
def test_with_style():
    """
    Text `print_formatted_text` with `HTML` wrapped in `to_formatted_text`.
    """
    f = _Capture()

    html = HTML('<ansigreen>hello</ansigreen> <b>world</b>')
    formatted_text = to_formatted_text(html, style='class:myhtml')
    pt_print(formatted_text, file=f)

    assert f.data == \
        b'\x1b[0m\x1b[?7h\x1b[0;32mhello\x1b[0m \x1b[0;1mworld\x1b[0m\r\n\x1b[0m'
Esempio n. 21
0
def show_unsupported_platform():
    # Show a message about the current platform not being supported

    button_dialog(title='Platform not supported',
                  text=(HTML('''
eth-wizard has no support for your platform. We only support
the following platforms:

* <b>Ubuntu 20.04</b> (x86_64)
* <b>Windows 10</b> (amd64)
''')),
                  buttons=[('Quit', False)]).run()
Esempio n. 22
0
def prompt(
    title: str, options: Sequence[Tuple[RadioListType,
                                        AnyFormattedText]]) -> RadioListType:
    control = RadioList(options_to_html(options))

    application: Application[None] = Application(
        layout=Layout(HSplit([Label(HTML(title)), control])),
        mouse_support=False,
        full_screen=False,
    )

    return cast(RadioListType, application.run())
Esempio n. 23
0
def delete():
    values = [(head, head.name) for head in repo.heads
              if head.name.startswith('f')]
    result = radiolist_dialog(title=HTML(
        f'Choose a branch to delete (Press {ansired("Enter")} to confirm, {ansired("Esc")} to cancel):'
    ),
                              values=values)
    if not result:
        raise typer.Abort()
    if repo.head.reference == result:
        nt(repo.git.checkout)('develop')
    nt(repo.delete_head)(result)
Esempio n. 24
0
def get_info_app(app: Flask):
    left_part = HTML("<left-part>"
                     " <import_name>%s</import_name> "
                     "<path>%s</path>"
                     "</left-part>") % (app.import_name, app.root_path)
    right_part = HTML("<right-part> "
                      " <env>%s</env> "
                      " <time>%s</time> "
                      "</right-part>") % (os.environ["ZEMFROG_ENV"],
                                          datetime.datetime.now().isoformat())

    used_width = sum([
        fragment_list_width(to_formatted_text(left_part)),
        fragment_list_width(to_formatted_text(right_part)),
    ])

    total_width = get_app().output.get_size().columns
    padding_size = total_width - used_width

    padding = HTML("<padding>%s</padding>") % (" " * padding_size, )
    return left_part, padding, right_part, "\n"
Esempio n. 25
0
    def __init__(self, prompt_session):
        Loader.__init__(self)
        self.type = "module"
        self.paths = ["modules/"]

        self.name = 'modules'
        self.prompt = HTML('ST (<ansired>modules</ansired>) ≫ ')
        self.completer = STCompleter(self)
        self.prompt_session = prompt_session

        self.selected = None
        self.get_loadables()
Esempio n. 26
0
    def format(self, progress_bar, progress, width):
        label = self._add_suffix(progress.label)
        cwidth = get_cwidth(label)

        if cwidth > width:
            # It doesn't fit -> scroll task name.
            max_scroll = cwidth - width
            current_scroll = int(time.time() * 3 % max_scroll)
            label = label[current_scroll:]

        # It does fit.
        return HTML(self.template).format(label=label)
Esempio n. 27
0
    def get_layout(self):
        game_labels = []
        for game in self.riitag_info.games:
            if not game:
                continue

            console_and_game_id = game.split('-')
            if len(console_and_game_id) == 2:
                console: str = console_and_game_id[0]
                game_id: str = console_and_game_id[1]

                label_text = f'<b>-</b> {game_id} ({console.title()})'
            else:
                label_text = f'<b>-</b> {console_and_game_id[0]}'
            game_labels.append(Label(HTML(label_text)))

        right_panel_layout = HSplit([])
        if self.right_panel_state == 'Menu':
            right_panel_layout = self.menu_layout
        elif self.right_panel_state == 'Settings':
            right_panel_layout = self.settings_layout

        return HSplit([
            Box(
                Label(text='Use the arrow keys and enter to navigate.'),
                height=3,
                padding_left=2
            ),
            VSplit([
                Frame(
                    Box(
                        HSplit([
                            Label(HTML(f'<b>Name:</b>   {self.riitag_info.name}')),
                            Label(HTML(f'<b>Games:</b>  {len(game_labels)}')),
                            *game_labels
                        ]), padding_left=3, padding_top=2
                    ), title='RiiTag'),
                right_panel_layout
            ])
        ])
Esempio n. 28
0
 def check_train_txt(self):
     train_log_path = os.path.join(self.path, "analog/sample_set/train.txt")
     test_black_path = os.path.join(self.path,
                                    "analog/sample_set/test_black_log.txt")
     test_raw_path = os.path.join(self.path,
                                  "analog/sample_set/test_white_log.txt")
     check_path = [train_log_path, test_black_path, test_raw_path]
     flag = True
     for path in check_path:
         try:
             if check_txt(path) is False:
                 flag = False
                 print_formatted_text(
                     HTML('<yellow>Necessary file ' + path +
                          ' is <red>empty</red> ! </yellow>'),
                     style=self.style)
         except FileNotFound:
             print_formatted_text(HTML('<yellow>Necessary file ' + path +
                                       '  <red>Not found</red> ! </yellow>'
                                       '\nGenerate file automatically.'),
                                  style=self.style)
     return flag
Esempio n. 29
0
    def __init__(self, prompt_session):
        self.name = 'sessions'
        self.prompt = HTML('ST (<ansired>sessions</ansired>) ≫ ')
        self.completer = WordCompleter(['info', 'list', 'stagers', 'listeners', 'modules', 'exit'])
        self.prompt_session = prompt_session

        self.sessions = []

        ipc_server.attach(NEW_SESSION, self.__add_session)
        ipc_server.attach(SESSION_STAGED, self.__notify_session_staged)
        ipc_server.attach(SESSION_CHECKIN, self.__session_checked_in)
        ipc_server.attach(NEW_JOB, self.__add_job)
        ipc_server.attach(JOB_RESULT, self.__job_result)
def prompt_continuation(width, line_number, is_soft_wrap):
    """
    The continuation: display line numbers and '->' before soft wraps.

    Notice that we can return any kind of formatted text from here.
    """
    # (make sure that the width of the continuation does not exceed the given
    # width. -- It is the prompt that determines the width of the left margin.)
    if is_soft_wrap:
        return ' ' * (width - 3) + '-> '
    else:
        text = ('- %i - ' % (line_number + 1)).rjust(width)
        return HTML('<strong>%s</strong>') % text