def tele_ls(): try: path = sys.argv[2] sub_path = __sub_path(path, False) except IndexError: sub_path = __sub_path('./', False) server_target = _choose_server_target() if server_target: from . import SshProtocol res = SshProtocol.command(server_target['user'], server_target['host'], server_target['path'], server_target['port'], f'ls -lah {sub_path}').strip().split('\n')[3:] res = [i.strip().split() for i in res] from rich.table import Table from rich.box import SIMPLE_HEAVY from rich.color import Color from rich.text import Text from rich.style import Style table = Table(title=f'{sub_path}', box=SIMPLE_HEAVY, show_header=True, header_style='bold magenta') table.add_column('permission' if user_lang != 'zh' else '权限码', justify='center') table.add_column('size' if user_lang != 'zh' else '尺寸', justify='center') table.add_column('owner' if user_lang != 'zh' else '拥有者', justify='center') table.add_column('time' if user_lang != 'zh' else '修改时间', justify='center') table.add_column('name' if user_lang != 'zh' else '文件名', justify='right') for i in res: is_dir = True if i[0][0] == 'd' else False color = Color.from_rgb(112, 87, 250) if is_dir else None p_color = Color.from_rgb(171, 157, 242) permission = ''.join(['1' if j != '-' else '0' for j in i[0][1:]]) permission = '%d%d%d' % (int(permission[:3], 2), int(permission[3: 6], 2), int(permission[6:], 2)) table.add_row(*[Text(permission, style=Style(color=p_color)), f'[green]{i[4]}', '[bold yellow]' + i[2], '[blue]' + ' '.join(i[5:8]), Text(" ".join(i[8:]), style=Style(color=color, bold=is_dir))]) QproDefaultConsole.print(table, justify='center')
def __rich_console__(self, console: Console, options: ConsoleOptions) -> RenderResult: for y in range(0, 5): for x in range(options.max_width): h = x / options.max_width l = 0.1 + ((y / 5) * 0.7) r1, g1, b1 = colorsys.hls_to_rgb(h, l, 1.0) r2, g2, b2 = colorsys.hls_to_rgb(h, l + 0.7 / 10, 1.0) bgcolor = Color.from_rgb(r1 * 255, g1 * 255, b1 * 255) color = Color.from_rgb(r2 * 255, g2 * 255, b2 * 255) yield Segment("▄", Style(color=color, bgcolor=bgcolor)) yield Segment.line()
def render(self) -> RenderableType: style = Style( bgcolor=(Color.parse("#555555" if self.mouse_over else "#444444")), color=Color.parse( "bright_yellow" if self.grabbed else "bright_magenta"), ) return ScrollBarRender( virtual_size=self.virtual_size, window_size=self.window_size, position=self.position, vertical=self.vertical, style=style, )
def __rich_console__(self, console: Console, options: ConsoleOptions) -> Iterable[Segment]: height = console.size.height - 3 for y in range(0, height): for x in range(options.max_width): h = x / options.max_width l = y / (height + 1) r1, g1, b1 = colorsys.hls_to_rgb(h, l, 1.0) r2, g2, b2 = colorsys.hls_to_rgb(h, l + (1 / height / 2), 1.0) bgcolor = Color.from_rgb(r1 * 255, g1 * 255, b1 * 255) color = Color.from_rgb(r2 * 255, g2 * 255, b2 * 255) yield Segment("▄", Style(color=color, bgcolor=bgcolor)) yield Segment.line()
def test_rich() -> None: color = Color.parse("red") as_text = color.__rich__() print(repr(as_text)) print(repr(as_text.spans)) assert as_text == Text("<color 'red' (standard)⬤ >", spans=[Span(23, 24, Style(color=color))])
def test_get_ansi_codes() -> None: assert Color.parse("default").get_ansi_codes() == ("39",) assert Color.parse("default").get_ansi_codes(False) == ("49",) assert Color.parse("red").get_ansi_codes() == ("31",) assert Color.parse("red").get_ansi_codes(False) == ("41",) assert Color.parse("color(1)").get_ansi_codes() == ("31",) assert Color.parse("color(1)").get_ansi_codes(False) == ("41",) assert Color.parse("#ff0000").get_ansi_codes() == ("38", "2", "255", "0", "0") assert Color.parse("#ff0000").get_ansi_codes(False) == ("48", "2", "255", "0", "0")
def test_get_ansi_codes() -> None: assert Color.parse("default").get_ansi_codes() == ["39"] assert Color.parse("default").get_ansi_codes(False) == ["49"] assert Color.parse("red").get_ansi_codes() == ["31"] assert Color.parse("red").get_ansi_codes(False) == ["41"] assert Color.parse("1").get_ansi_codes() == ["38", "5", "1"] assert Color.parse("1").get_ansi_codes(False) == ["48", "5", "1"] assert Color.parse("#ff0000").get_ansi_codes() == ["38", "2", "255", "0", "0"] assert Color.parse("#ff0000").get_ansi_codes(False) == ["48", "2", "255", "0", "0"]
def setup(self): self.console = Console( file=StringIO(), color_system="truecolor", legacy_windows=False, width=100 ) self.color = Color.parse("#0d1da0") # Warm cache self.color.downgrade(ColorSystem.EIGHT_BIT) self.color.downgrade(ColorSystem.STANDARD) self.color.downgrade(ColorSystem.WINDOWS)
def __rich_console__(self, console: Console, options: ConsoleOptions) -> RenderResult: size = ((options.height or console.height) if self.vertical else (options.max_width or console.width)) thickness = ((options.max_width or console.width) if self.vertical else (options.height or console.height)) _style = console.get_style(self.style) bar = self.render_bar( size=size, window_size=self.window_size, virtual_size=self.virtual_size, position=self.position, vertical=self.vertical, thickness=thickness, back_color=_style.bgcolor or Color.parse("#555555"), bar_color=_style.color or Color.parse("bright_magenta"), ) yield bar
def __rich_console__(self, console: Console, options: ConsoleOptions) -> RenderResult: for y in range(0, 5): for x in range(options.max_width): h = x / options.max_width l = 0.1 + ((y / 5) * 0.7) r, g, b = colorsys.hls_to_rgb(h, l, 1.0) yield Segment( "█", Style(color=Color.from_rgb(r * 255, g * 255, b * 255))) yield Segment.line()
def test_truecolor() -> None: assert Color.parse("#ff0000").get_truecolor() == ColorTriplet(255, 0, 0) assert Color.parse("red").get_truecolor() == ColorTriplet(128, 0, 0) assert Color.parse("1").get_truecolor() == ColorTriplet(128, 0, 0) assert Color.parse("17").get_truecolor() == ColorTriplet(0, 0, 95) assert Color.parse("default").get_truecolor() == ColorTriplet(0, 0, 0) assert Color.parse("default").get_truecolor( foreground=False) == ColorTriplet(255, 255, 255) assert Color("red", ColorType.WINDOWS, number=1).get_truecolor() == ColorTriplet(255, 0, 0)
def test_truecolor() -> None: assert Color.parse("#ff0000").get_truecolor( themes.DEFAULT) == ColorTriplet(255, 0, 0) assert Color.parse("red").get_truecolor(themes.DEFAULT) == ColorTriplet( 128, 0, 0) assert Color.parse("1").get_truecolor(themes.DEFAULT) == ColorTriplet( 128, 0, 0) assert Color.parse("17").get_truecolor(themes.DEFAULT) == ColorTriplet( 0, 0, 95) assert Color.parse("default").get_truecolor( themes.DEFAULT) == ColorTriplet(0, 0, 0) assert Color.parse("default").get_truecolor( themes.DEFAULT, foreground=False) == ColorTriplet(255, 255, 255)
def output_rich(data: Dataset, formatter, cache_disabled): console.record = True table = Table( show_header=True, header_style="bold blue", row_styles=[Style(), Style(color=Color.from_ansi(252))], show_footer=True, footer_style="bold blue", ) table.box = box.MINIMAL rows = list(data.get_rows_list(formatter)) for col in data.output_columns: table.add_column(col, footer="" if len(rows) < 15 else col) for row in rows: table.add_row(*row) console.print(table) console.rule("Information") if len(data.output_columns) < len(data.available_columns): console.print( "[green]More columns available:[/green]", ", ".join(sorted(data.available_columns - set(data.output_columns))), ) console.print("[green]Sorted by:[/green]", ", ".join(data.sort)) if data.where is None: console.print( f"[green]All available rows ({table.row_count}) are shown.[/green]" ) else: console.print( "[green]Filter active:[/green]", f"`[blue]{data.where}[/blue]`", f"→ {table.row_count} rows of {data.original_row_count} available rows shown.", ) if not cache_disabled: console.print( "[green]Caching enabled. To disable, use[/green] --no-cache")
def convertColor(color: Optional[str]) -> str: ignoreColors = ["z", "zzz", "grt", "oth", "utc", "dne", "gmt"] if color is not None and color not in ignoreColors: if color.startswith("#"): return color elif len(color) == 6: return "#" + color else: return { "grn": "green", "amb": "#FFBF00", "hzl": "#8E7618", "gry": "bright_black", "blu": "blue", "brn": "#654321", "lzr": "#00ff00", "xry": "#0083D9" }[color] else: return Color.default().get_truecolor().rgb
def __rich__(self) -> "Table": from rich.color import Color from rich.style import Style from rich.text import Text from rich.table import Table table = Table( "index", "RGB", "Color", title="Palette", caption=f"{len(self._colors)} colors", highlight=True, caption_justify="right", ) for index, color in enumerate(self._colors): table.add_row( str(index), repr(color), Text(" " * 16, style=Style(bgcolor=Color.from_rgb(*color))), ) return table
# -*- coding: utf-8 -*- ######################################################################## # # # # # # # MIT License # # Copyright (c) 2021 Michael Nikitenko # # # ######################################################################## from rich import inspect from rich.color import Color if __name__ == '__main__': color = Color.parse("red") inspect(color, methods=True) # Выводит всю инфу по классу в удобочитаемом виде
def test_downgrade() -> None: assert Color.parse("9").downgrade(0) == Color("9", ColorType.EIGHT_BIT, 9, None) assert Color.parse("#000000").downgrade(ColorSystem.EIGHT_BIT) == Color( "#000000", ColorType.EIGHT_BIT, 16, None) assert Color.parse("#ffffff").downgrade(ColorSystem.EIGHT_BIT) == Color( "#ffffff", ColorType.EIGHT_BIT, 231, None) assert Color.parse("#404142").downgrade(ColorSystem.EIGHT_BIT) == Color( "#404142", ColorType.EIGHT_BIT, 237, None) assert Color.parse("#ff0000").downgrade(ColorSystem.EIGHT_BIT) == Color( "#ff0000", ColorType.EIGHT_BIT, 196, None) assert Color.parse("#ff0000").downgrade(ColorSystem.STANDARD) == Color( "#ff0000", ColorType.STANDARD, 1, None) assert Color.parse("9").downgrade(ColorSystem.STANDARD) == Color( "9", ColorType.STANDARD, 1, None) assert Color.parse("red").downgrade(ColorSystem.WINDOWS) == Color( "red", ColorType.WINDOWS, 1, None) assert Color.parse("bright_red").downgrade(ColorSystem.WINDOWS) == Color( "bright_red", ColorType.WINDOWS, 1, None) assert Color.parse("#ff0000").downgrade(ColorSystem.WINDOWS) == Color( "#ff0000", ColorType.WINDOWS, 1, None) assert Color.parse("255").downgrade(ColorSystem.WINDOWS) == Color( "255", ColorType.WINDOWS, 7, None)
def test_default() -> None: assert Color.default() == Color("default", ColorType.DEFAULT, None, None)
def test_parse_error() -> None: with pytest.raises(ColorParseError): Color.parse("256") with pytest.raises(ColorParseError): Color.parse("rgb(999,0,0)") with pytest.raises(ColorParseError): Color.parse("rgb(0,0)") with pytest.raises(ColorParseError): Color.parse("rgb(0,0,0,0)") with pytest.raises(ColorParseError): Color.parse("nosuchcolor") with pytest.raises(ColorParseError): Color.parse("#xxyyzz")
def apply_color_rule(mark: ProtoStyle, rule_tuple): mode, g, data, original = rule_tuple if mode == "letters": for c in data: if c == "n": # ANSI reset mark.do_reset() continue if (bit := CHAR_MAP.get(c, None)): setattr(mark, bit, True) elif (bit := CHAR_MAP.get(c.lower(), None)): setattr(mark, bit, False) elif (code := BASE_COLOR_MAP.get(c, None)): setattr(mark, "color", Color.from_ansi(code)) elif (code := BASE_COLOR_MAP.get(c.lower(), None)): setattr(mark, "bgcolor", Color.from_ansi(code)) else: pass # I dunno what we got passed, but it ain't relevant. elif g == BgMode.FG: if mode == "numbers": setattr(mark, "color", Color.from_ansi(data)) elif mode == "name": if (found := COLORS.get(data)): setattr(mark, "color", Color.from_ansi(found["xterm"])) elif mode in ("rgb", "hex1", "hex2"): setattr(mark, "color", Color.from_rgb(data["red"], data["green"], data["blue"])) elif g == BgMode.BG:
def test_from_triplet() -> None: assert Color.from_triplet(ColorTriplet(0x10, 0x20, 0x30)) == Color( "#102030", ColorType.TRUECOLOR, None, ColorTriplet(0x10, 0x20, 0x30))
def test_system() -> None: assert Color.parse("default").system == ColorSystem.STANDARD assert Color.parse("red").system == ColorSystem.STANDARD assert Color.parse("#ff0000").system == ColorSystem.TRUECOLOR
import re from rich.text import Text from ..patches.style import MudStyle, ProtoStyle from rich.color import Color from typing import Union, List, Tuple LETTERS = { "x": Color.from_ansi(0), "r": Color.from_ansi(1), "g": Color.from_ansi(2), "y": Color.from_ansi(3), "b": Color.from_ansi(4), "m": Color.from_ansi(5), "c": Color.from_ansi(6), "w": Color.from_ansi(7), } EV_REGEX = { "fg_ansi_bold": re.compile(r"^(r|g|y|b|m|c|x|w)"), "fg_ansi_normal": re.compile(r"^(R|G|Y|B|M|C|X|W)"), "bg_ansi_bold": re.compile(r"^\[(r|g|y|b|m|c|x|w)"), "bg_ansi_normal": re.compile(r"^\[(R|G|Y|B|M|C|X|W)"), "fg_xterm": re.compile(r"^[0-5]{3}"), "bg_xterm": re.compile(r"^\[([0-5]{3})"), } def apply_fg_ansi_bold(proto: ProtoStyle, code): proto.bold = True proto.color = LETTERS[code.group(0)]
def test_repr() -> None: assert repr(Color.parse("red")) == "<color 'red' (standard)>"
def test_str() -> None: assert str( Color.parse("red")) == "\x1b[31m⬤ \x1b[0m<color 'red' (standard)>"
if __name__ == "__main__": # type: ignore from rich import print inspect = Inspect({}, docs=True, methods=True, dunder=True) print(inspect) t = Text("Hello, World") print(Inspect(t)) from rich.style import Style from rich.color import Color print(Inspect(Style.parse("bold red on black"), methods=True, docs=True)) print(Inspect(Color.parse("#ffe326"), methods=True, docs=True)) from rich import get_console print(Inspect(get_console(), methods=False)) print(Inspect(open("foo.txt", "wt"), methods=False)) print(Inspect("Hello", methods=False, dunder=True)) print(Inspect(inspect, methods=False, dunder=False, docs=False)) class Foo: @property def broken(self): 1 / 0
def test_bgcolor_property(): assert Style(bgcolor="black").bgcolor == Color("black", ColorType.STANDARD, 0, None)
def setup(self): self.console = Console( file=StringIO(), color_system="truecolor", legacy_windows=False, width=100 ) self.color = Color.parse("#0d1da0")
def __rich_repr__(self): c = Color.from_hsv(self.color) yield 'name', self.label yield 'color', c.name
def test_parse_success() -> None: assert Color.parse("default") == Color("default", ColorType.DEFAULT, None, None) assert Color.parse("red") == Color("red", ColorType.STANDARD, 1, None) assert Color.parse("bright_red") == Color("bright_red", ColorType.EIGHT_BIT, 9, None) assert Color.parse("yellow4") == Color("yellow4", ColorType.EIGHT_BIT, 106, None) assert Color.parse("100") == Color("100", ColorType.EIGHT_BIT, 100, None) assert Color.parse("#112233") == Color("#112233", ColorType.TRUECOLOR, None, ColorTriplet(0x11, 0x22, 0x33)) assert Color.parse("rgb(90,100,110)") == Color("rgb(90,100,110)", ColorType.TRUECOLOR, None, ColorTriplet(90, 100, 110))