response
stringlengths
1
33.1k
instruction
stringlengths
22
582k
Arrange widgets which are *docked*. Args: dock_widgets: Widgets with a non-empty dock. size: Size of the container. viewport: Size of the viewport. Returns: A tuple of widget placements, and additional spacing around them
def _arrange_dock_widgets( dock_widgets: Sequence[Widget], size: Size, viewport: Size ) -> tuple[list[WidgetPlacement], Spacing]: """Arrange widgets which are *docked*. Args: dock_widgets: Widgets with a non-empty dock. size: Size of the container. viewport: Size of the viewport. Returns: A tuple of widget placements, and additional spacing around them """ _WidgetPlacement = WidgetPlacement top_z = TOP_Z width, height = size null_spacing = Spacing() top = right = bottom = left = 0 placements: list[WidgetPlacement] = [] append_placement = placements.append for dock_widget in dock_widgets: edge = dock_widget.styles.dock box_model = dock_widget._get_box_model( size, viewport, Fraction(size.width), Fraction(size.height) ) widget_width_fraction, widget_height_fraction, margin = box_model widget_width = int(widget_width_fraction) + margin.width widget_height = int(widget_height_fraction) + margin.height if edge == "bottom": dock_region = Region(0, height - widget_height, widget_width, widget_height) bottom = max(bottom, widget_height) elif edge == "top": dock_region = Region(0, 0, widget_width, widget_height) top = max(top, widget_height) elif edge == "left": dock_region = Region(0, 0, widget_width, widget_height) left = max(left, widget_width) elif edge == "right": dock_region = Region(width - widget_width, 0, widget_width, widget_height) right = max(right, widget_width) else: # Should not occur, mainly to keep Mypy happy raise AssertionError("invalid value for edge") # pragma: no-cover align_offset = dock_widget.styles._align_size( (widget_width, widget_height), size ) dock_region = dock_region.shrink(margin).translate(align_offset) append_placement( _WidgetPlacement(dock_region, null_spacing, dock_widget, top_z, True) ) dock_spacing = Spacing(top, right, bottom, left) return (placements, dock_spacing)
Get segments used to render a box. Args: name: Name of the box type. inner_style: The inner style (widget background) outer_style: The outer style (parent background) style: Widget style Returns: A tuple of 3 Segment triplets.
def get_box( name: EdgeType, inner_style: Style, outer_style: Style, style: Style, ) -> BoxSegments: """Get segments used to render a box. Args: name: Name of the box type. inner_style: The inner style (widget background) outer_style: The outer style (parent background) style: Widget style Returns: A tuple of 3 Segment triplets. """ _Segment = Segment ( (top1, top2, top3), (mid1, mid2, mid3), (bottom1, bottom2, bottom3), ) = BORDER_CHARS[name] ( (ltop1, ltop2, ltop3), (lmid1, lmid2, lmid3), (lbottom1, lbottom2, lbottom3), ) = BORDER_LOCATIONS[name] inner = inner_style + style outer = outer_style + style styles = ( inner, outer, Style.from_color(outer.bgcolor, inner.color), Style.from_color(inner.bgcolor, outer.color), ) return ( ( _Segment(top1, styles[ltop1]), _Segment(top2, styles[ltop2]), _Segment(top3, styles[ltop3]), ), ( _Segment(mid1, styles[lmid1]), _Segment(mid2, styles[lmid2]), _Segment(mid3, styles[lmid3]), ), ( _Segment(bottom1, styles[lbottom1]), _Segment(bottom2, styles[lbottom2]), _Segment(bottom3, styles[lbottom3]), ), )
Render a border label (the title or subtitle) with optional markup. The styling that may be embedded in the label will be reapplied after taking into account the inner, outer, and border-specific, styles. Args: label: Tuple of label and style to render in the border. is_title: Whether we are rendering the title (`True`) or the subtitle (`False`). name: Name of the box type. width: The width, in cells, of the space available for the whole edge. This is the total space that may also be needed for the border corners and the whitespace padding around the (sub)title. Thus, the effective space available for the border label is: - `width` if no corner is needed; - `width - 2` if one corner is needed; and - `width - 4` if both corners are needed. inner_style: The inner style (widget background). outer_style: The outer style (parent background). style: Widget style. console: The console that will render the markup in the label. has_left_corner: Whether the border edge will have to render a left corner. has_right_corner: Whether the border edge will have to render a right corner. Returns: A list of segments that represent the full label and surrounding padding.
def render_border_label( label: tuple[Text, Style], is_title: bool, name: EdgeType, width: int, inner_style: Style, outer_style: Style, style: Style, console: Console, has_left_corner: bool, has_right_corner: bool, ) -> Iterable[Segment]: """Render a border label (the title or subtitle) with optional markup. The styling that may be embedded in the label will be reapplied after taking into account the inner, outer, and border-specific, styles. Args: label: Tuple of label and style to render in the border. is_title: Whether we are rendering the title (`True`) or the subtitle (`False`). name: Name of the box type. width: The width, in cells, of the space available for the whole edge. This is the total space that may also be needed for the border corners and the whitespace padding around the (sub)title. Thus, the effective space available for the border label is: - `width` if no corner is needed; - `width - 2` if one corner is needed; and - `width - 4` if both corners are needed. inner_style: The inner style (widget background). outer_style: The outer style (parent background). style: Widget style. console: The console that will render the markup in the label. has_left_corner: Whether the border edge will have to render a left corner. has_right_corner: Whether the border edge will have to render a right corner. Returns: A list of segments that represent the full label and surrounding padding. """ # How many cells do we need to reserve for surrounding blanks and corners? corners_needed = has_left_corner + has_right_corner cells_reserved = 2 * corners_needed text_label, label_style = label if not text_label.cell_len or width <= cells_reserved: return text_label = text_label.copy() text_label.truncate(width - cells_reserved, overflow="ellipsis") if has_left_corner: text_label.pad_left(1) if has_right_corner: text_label.pad_right(1) text_label.stylize_before(label_style) label_style_location = BORDER_LABEL_LOCATIONS[name][0 if is_title else 1] flip_top, flip_bottom = BORDER_TITLE_FLIP.get(name, (False, False)) inner = inner_style + style outer = outer_style + style base_style: Style if label_style_location == 0: base_style = inner elif label_style_location == 1: base_style = outer elif label_style_location == 2: base_style = Style.from_color(outer.bgcolor, inner.color) elif label_style_location == 3: base_style = Style.from_color(inner.bgcolor, outer.color) else: assert False if (flip_top and is_title) or (flip_bottom and not is_title): base_style = base_style.without_color + Style.from_color( base_style.bgcolor, base_style.color ) text_label.stylize_before(base_style + label_style) segments = text_label.render(console) yield from segments
Compose a box row with its padded label. This is the function that actually does the work that `render_row` is intended to do, but we have many lists of segments flowing around, so it becomes easier to yield the segments bit by bit, and the aggregate everything into a list later. Args: box_row: Corners and side segments. width: Total width of resulting line. left: Render left corner. right: Render right corner. label_segments: The segments that make up the label. label_alignment: Where to horizontally align the label. Returns: An iterable of segments.
def render_row( box_row: tuple[Segment, Segment, Segment], width: int, left: bool, right: bool, label_segments: Iterable[Segment], label_alignment: AlignHorizontal = "left", ) -> Iterable[Segment]: """Compose a box row with its padded label. This is the function that actually does the work that `render_row` is intended to do, but we have many lists of segments flowing around, so it becomes easier to yield the segments bit by bit, and the aggregate everything into a list later. Args: box_row: Corners and side segments. width: Total width of resulting line. left: Render left corner. right: Render right corner. label_segments: The segments that make up the label. label_alignment: Where to horizontally align the label. Returns: An iterable of segments. """ box1, box2, box3 = box_row corners_needed = left + right label_segments_list = list(label_segments) label_length = sum((segment.cell_length for segment in label_segments_list), 0) space_available = max(0, width - corners_needed - label_length) if left: yield box1 if not space_available: yield from label_segments_list elif not label_length: yield Segment(box2.text * space_available, box2.style) elif label_alignment == "left" or label_alignment == "right": edge = Segment(box2.text * (space_available - 1), box2.style) if label_alignment == "left": yield Segment(box2.text, box2.style) yield from label_segments_list yield edge else: yield edge yield from label_segments_list yield Segment(box2.text, box2.style) elif label_alignment == "center": length_on_left = space_available // 2 length_on_right = space_available - length_on_left yield Segment(box2.text * length_on_left, box2.style) yield from label_segments_list yield Segment(box2.text * length_on_right, box2.style) else: assert False if right: yield box3
Combine two box drawing quads. Args: box1: Existing box quad. box2: New box quad. Returns: A new box quad.
def combine_quads(box1: Quad, box2: Quad) -> Quad: """Combine two box drawing quads. Args: box1: Existing box quad. box2: New box quad. Returns: A new box quad. """ top1, right1, bottom1, left1 = box1 top2, right2, bottom2, left2 = box2 return ( top2 or top1, right2 or right1, bottom2 or bottom1, left2 or left1, )
Count the number of parameters in a callable
def count_parameters(func: Callable) -> int: """Count the number of parameters in a callable""" if isinstance(func, partial): return _count_parameters(func.func) + len(func.args) if hasattr(func, "__self__"): # Bound method func = func.__func__ # type: ignore return _count_parameters(func) - 1 return _count_parameters(func)
Count the number of parameters in a callable
def _count_parameters(func: Callable) -> int: """Count the number of parameters in a callable""" return len(signature(func).parameters)
Retrieve the column index corresponding to the given cell width. Args: line: The line of text to search within. cell_width: The cell width to convert to column index. tab_width: The tab stop width to expand tabs contained within the line. Returns: The column corresponding to the cell width.
def cell_width_to_column_index(line: str, cell_width: int, tab_width: int) -> int: """Retrieve the column index corresponding to the given cell width. Args: line: The line of text to search within. cell_width: The cell width to convert to column index. tab_width: The tab stop width to expand tabs contained within the line. Returns: The column corresponding to the cell width. """ column_index = 0 total_cell_offset = 0 for part, expanded_tab_width in get_tab_widths(line, tab_width): # Check if the click landed on a character within this part. for character in part: total_cell_offset += cell_len(character) if total_cell_offset > cell_width: return column_index column_index += 1 # Account for the appearance of the tab character for this part total_cell_offset += expanded_tab_width # Check if the click falls within the boundary of the expanded tab. if total_cell_offset > cell_width: return column_index column_index += 1 return len(line)
Compose child widgets. Args: node: The parent node. Returns: A list of widgets.
def compose(node: App | Widget) -> list[Widget]: """Compose child widgets. Args: node: The parent node. Returns: A list of widgets. """ _rich_traceback_omit = True from .widget import MountError, Widget app = node.app nodes: list[Widget] = [] compose_stack: list[Widget] = [] composed: list[Widget] = [] app._compose_stacks.append(compose_stack) app._composed.append(composed) iter_compose = iter(node.compose()) is_generator = hasattr(iter_compose, "throw") try: while True: try: child = next(iter_compose) except StopIteration: break if not isinstance(child, Widget): mount_error = MountError( f"Can't mount {type(child)}; expected a Widget instance." ) if is_generator: iter_compose.throw(mount_error) # type: ignore else: raise mount_error from None try: child.id except AttributeError: mount_error = MountError( "Widget is missing an 'id' attribute; did you forget to call super().__init__()?" ) if is_generator: iter_compose.throw(mount_error) # type: ignore else: raise mount_error from None if composed: nodes.extend(composed) composed.clear() if compose_stack: try: compose_stack[-1].compose_add_child(child) except Exception as error: if is_generator: # So the error is raised inside the generator # This will generate a more sensible traceback for the dev iter_compose.throw(error) # type: ignore else: raise else: nodes.append(child) if composed: nodes.extend(composed) composed.clear() finally: app._compose_stacks.pop() app._composed.pop() return nodes
A superfences formatter to insert an SVG screenshot.
def format_svg(source, language, css_class, options, md, attrs, **kwargs) -> str: """A superfences formatter to insert an SVG screenshot.""" try: cmd: list[str] = shlex.split(attrs["path"]) path = cmd[0] _press = attrs.get("press", None) press = [*_press.split(",")] if _press else [] title = attrs.get("title") print(f"screenshotting {path!r}") cwd = os.getcwd() try: rows = int(attrs.get("lines", 24)) columns = int(attrs.get("columns", 80)) hover = attrs.get("hover", "") svg = take_svg_screenshot( None, path, press, hover=hover, title=title, terminal_size=(columns, rows), wait_for_animation=False, ) finally: os.chdir(cwd) assert svg is not None return svg except Exception as error: import traceback traceback.print_exception(error) return ""
Args: app: An app instance. Must be supplied if app_path is not. app_path: A path to an app. Must be supplied if app is not. press: Key presses to run before taking screenshot. "_" is a short pause. hover: Hover over the given widget. title: The terminal title in the output image. terminal_size: A pair of integers (rows, columns), representing terminal size. run_before: An arbitrary callable that runs arbitrary code before taking the screenshot. Use this to simulate complex user interactions with the app that cannot be simulated by key presses. wait_for_animation: Wait for animation to complete before taking screenshot. Returns: An SVG string, showing the content of the terminal window at the time the screenshot was taken.
def take_svg_screenshot( app: App | None = None, app_path: str | None = None, press: Iterable[str] = (), hover: str = "", title: str | None = None, terminal_size: tuple[int, int] = (80, 24), run_before: Callable[[Pilot], Awaitable[None] | None] | None = None, wait_for_animation: bool = True, ) -> str: """ Args: app: An app instance. Must be supplied if app_path is not. app_path: A path to an app. Must be supplied if app is not. press: Key presses to run before taking screenshot. "_" is a short pause. hover: Hover over the given widget. title: The terminal title in the output image. terminal_size: A pair of integers (rows, columns), representing terminal size. run_before: An arbitrary callable that runs arbitrary code before taking the screenshot. Use this to simulate complex user interactions with the app that cannot be simulated by key presses. wait_for_animation: Wait for animation to complete before taking screenshot. Returns: An SVG string, showing the content of the terminal window at the time the screenshot was taken. """ if app is None: assert app_path is not None app = import_app(app_path) assert app is not None if title is None: title = app.title def get_cache_key(app: App) -> str: hash = hashlib.md5() file_paths = [app_path] + app.css_path for path in file_paths: assert path is not None with open(path, "rb") as source_file: hash.update(source_file.read()) hash.update(f"{press}-{hover}-{title}-{terminal_size}".encode("utf-8")) cache_key = f"{hash.hexdigest()}.svg" return cache_key if app_path is not None and run_before is None: screenshot_cache = Path(SCREENSHOT_CACHE) screenshot_cache.mkdir(exist_ok=True) screenshot_path = screenshot_cache / get_cache_key(app) if screenshot_path.exists(): return screenshot_path.read_text() async def auto_pilot(pilot: Pilot) -> None: app = pilot.app if run_before is not None: result = run_before(pilot) if inspect.isawaitable(result): await result await pilot.pause() await pilot.press(*press) if hover: await pilot.hover(hover) await pilot.pause(0.5) if wait_for_animation: await pilot.wait_for_scheduled_animations() await pilot.pause() await pilot.pause() await pilot.wait_for_scheduled_animations() svg = app.export_screenshot(title=title) app.exit(svg) svg = cast( str, app.run( headless=True, auto_pilot=auto_pilot, size=terminal_size, ), ) if app_path is not None and run_before is None: screenshot_path.write_text(svg) assert svg is not None return svg
A superfences formatter to insert an SVG screenshot.
def rich(source, language, css_class, options, md, attrs, **kwargs) -> str: """A superfences formatter to insert an SVG screenshot.""" import io from rich.console import Console title = attrs.get("title", "Rich") rows = int(attrs.get("lines", 24)) columns = int(attrs.get("columns", 80)) console = Console( file=io.StringIO(), record=True, force_terminal=True, color_system="truecolor", width=columns, height=rows, ) error_console = Console(stderr=True) globals: dict = {} try: exec(source, globals) except Exception: error_console.print_exception() # console.bell() if "output" in globals: console.print(globals["output"]) output_svg = console.export_svg(title=title) return output_svg
Args: duration: A string of the form ``"2s"`` or ``"300ms"``, representing 2 seconds and 300 milliseconds respectively. If no unit is supplied, e.g. ``"2"``, then the duration is assumed to be in seconds. Raises: DurationParseError: If the argument ``duration`` is not a valid duration string. Returns: The duration in seconds.
def _duration_as_seconds(duration: str) -> float: """ Args: duration: A string of the form ``"2s"`` or ``"300ms"``, representing 2 seconds and 300 milliseconds respectively. If no unit is supplied, e.g. ``"2"``, then the duration is assumed to be in seconds. Raises: DurationParseError: If the argument ``duration`` is not a valid duration string. Returns: The duration in seconds. """ match = _match_duration(duration) if match: value, unit_name = match.groups() value = float(value) if unit_name == "ms": duration_secs = value / 1000 else: duration_secs = value else: try: duration_secs = float(duration) except ValueError: raise DurationParseError( f"{duration!r} is not a valid duration." ) from ValueError return duration_secs
https://easings.net/#easeInOutExpo
def _in_out_expo(x: float) -> float: """https://easings.net/#easeInOutExpo""" if 0 < x < 0.5: return pow(2, 20 * x - 10) / 2 elif 0.5 <= x < 1: return (2 - pow(2, -20 * x + 10)) / 2 else: return x
https://easings.net/#easeInOutCirc
def _in_out_circ(x: float) -> float: """https://easings.net/#easeInOutCirc""" if x < 0.5: return (1 - sqrt(1 - pow(2 * x, 2))) / 2 else: return (sqrt(1 - pow(-2 * x + 2, 2)) + 1) / 2
https://easings.net/#easeInOutBack
def _in_out_back(x: float) -> float: """https://easings.net/#easeInOutBack""" c = 1.70158 * 1.525 if x < 0.5: return (pow(2 * x, 2) * ((c + 1) * 2 * x - c)) / 2 else: return (pow(2 * x - 2, 2) * ((c + 1) * (x * 2 - 2) + c) + 2) / 2
https://easings.net/#easeInElastic
def _in_elastic(x: float) -> float: """https://easings.net/#easeInElastic""" c = 2 * pi / 3 if 0 < x < 1: return -pow(2, 10 * x - 10) * sin((x * 10 - 10.75) * c) else: return x
https://easings.net/#easeInOutElastic
def _in_out_elastic(x: float) -> float: """https://easings.net/#easeInOutElastic""" c = 2 * pi / 4.5 if 0 < x < 0.5: return -(pow(2, 20 * x - 10) * sin((20 * x - 11.125) * c)) / 2 elif 0.5 <= x < 1: return (pow(2, -20 * x + 10) * sin((20 * x - 11.125) * c)) / 2 + 1 else: return x
https://easings.net/#easeInOutElastic
def _out_elastic(x: float) -> float: """https://easings.net/#easeInOutElastic""" c = 2 * pi / 3 if 0 < x < 1: return pow(2, -10 * x) * sin((x * 10 - 0.75) * c) + 1 else: return x
https://easings.net/#easeOutBounce
def _out_bounce(x: float) -> float: """https://easings.net/#easeOutBounce""" n, d = 7.5625, 2.75 if x < 1 / d: return n * x * x elif x < 2 / d: x_ = x - 1.5 / d return n * x_ * x_ + 0.75 elif x < 2.5 / d: x_ = x - 2.25 / d return n * x_ * x_ + 0.9375 else: x_ = x - 2.625 / d return n * x_ * x_ + 0.984375
https://easings.net/#easeInBounce
def _in_bounce(x: float) -> float: """https://easings.net/#easeInBounce""" return 1 - _out_bounce(1 - x)
https://easings.net/#easeInOutBounce
def _in_out_bounce(x: float) -> float: """https://easings.net/#easeInOutBounce""" if x < 0.5: return (1 - _out_bounce(1 - 2 * x)) / 2 else: return (1 + _out_bounce(2 * x - 1)) / 2
Does the given file look like it's run with Python? Args: candidate: The candidate file to check. Returns: ``True`` if it looks to #! python, ``False`` if not.
def shebang_python(candidate: Path) -> bool: """Does the given file look like it's run with Python? Args: candidate: The candidate file to check. Returns: ``True`` if it looks to #! python, ``False`` if not. """ try: with candidate.open("rb") as source: first_line = source.readline() except IOError: return False return first_line.startswith(b"#!") and b"python" in first_line
Import an app from a path or import name. Args: import_name: A name to import, such as `foo.bar`, or a path ending with .py. Raises: AppFail: If the app could not be found for any reason. Returns: A Textual application
def import_app(import_name: str) -> App: """Import an app from a path or import name. Args: import_name: A name to import, such as `foo.bar`, or a path ending with .py. Raises: AppFail: If the app could not be found for any reason. Returns: A Textual application """ import importlib import inspect from textual.app import WINDOWS, App import_name, *argv = shlex.split(import_name, posix=not WINDOWS) drive, import_name = os.path.splitdrive(import_name) lib, _colon, name = import_name.partition(":") if drive: lib = os.path.join(drive, os.sep, lib) if lib.endswith(".py") or shebang_python(Path(lib)): path = os.path.abspath(lib) sys.path.append(str(Path(path).parent)) try: global_vars = runpy.run_path(path, {}) except Exception as error: raise AppFail(str(error)) sys.argv[:] = [path, *argv] if name: # User has given a name, use that try: app = global_vars[name] except KeyError: raise AppFail(f"App {name!r} not found in {lib!r}") else: # User has not given a name if "app" in global_vars: # App exists, lets use that try: app = global_vars["app"] except KeyError: raise AppFail(f"App {name!r} not found in {lib!r}") else: # Find an App class or instance that is *not* the base class apps = [ value for value in global_vars.values() if ( isinstance(value, App) or (inspect.isclass(value) and issubclass(value, App)) and value is not App ) ] if not apps: raise AppFail( f'Unable to find app in {lib!r}, try specifying app with "foo.py:app"' ) if len(apps) > 1: raise AppFail( f'Multiple apps found {lib!r}, try specifying app with "foo.py:app"' ) app = apps[0] app._BASE_PATH = path else: # Assuming the user wants to import the file sys.path.append("") try: module = importlib.import_module(lib) except ImportError as error: raise AppFail(str(error)) find_app = name or "app" try: app = getattr(module, find_app or "app") except AttributeError: raise AppFail(f"Unable to find {find_app!r} in {module!r}") sys.argv[:] = [import_name, *argv] if inspect.isclass(app) and issubclass(app, App): app = app() return cast(App, app)
Divide total space to satisfy size, fraction, and min_size, constraints. The returned list of integers should add up to total in most cases, unless it is impossible to satisfy all the constraints. For instance, if there are two edges with a minimum size of 20 each and `total` is 30 then the returned list will be greater than total. In practice, this would mean that a Layout object would clip the rows that would overflow the screen height. Args: total: Total number of characters. edges: Edges within total space. Returns: Number of characters for each edge.
def layout_resolve(total: int, edges: Sequence[EdgeProtocol]) -> list[int]: """Divide total space to satisfy size, fraction, and min_size, constraints. The returned list of integers should add up to total in most cases, unless it is impossible to satisfy all the constraints. For instance, if there are two edges with a minimum size of 20 each and `total` is 30 then the returned list will be greater than total. In practice, this would mean that a Layout object would clip the rows that would overflow the screen height. Args: total: Total number of characters. edges: Edges within total space. Returns: Number of characters for each edge. """ # Size of edge or None for yet to be determined sizes = [(edge.size or None) for edge in edges] if None not in sizes: # No flexible edges return cast("list[int]", sizes) # Get flexible edges and index to map these back on to sizes list flexible_edges = [ (index, edge) for index, (size, edge) in enumerate(zip(sizes, edges)) if size is None ] # Remaining space in total remaining = total - sum([size or 0 for size in sizes]) if remaining <= 0: # No room for flexible edges return [ ((edge.min_size or 1) if size is None else size) for size, edge in zip(sizes, edges) ] # Get the total fraction value for all flexible edges total_flexible = sum([(edge.fraction or 1) for _, edge in flexible_edges]) while flexible_edges: # Calculate number of characters in a ratio portion portion = Fraction(remaining, total_flexible) # If any edges will be less than their minimum, replace size with the minimum for flexible_index, (index, edge) in enumerate(flexible_edges): if portion * edge.fraction < edge.min_size: # This flexible edge will be smaller than its minimum size # We need to fix the size and redistribute the outstanding space sizes[index] = edge.min_size remaining -= edge.min_size total_flexible -= edge.fraction or 1 del flexible_edges[flexible_index] # New fixed size will invalidate calculations, so we need to repeat the process break else: # Distribute flexible space and compensate for rounding error # Since edge sizes can only be integers we need to add the remainder # to the following line remainder = Fraction(0) for index, edge in flexible_edges: sizes[index], remainder = divmod(portion * edge.fraction + remainder, 1) break # Sizes now contains integers only return cast("list[int]", sizes)
Splits an arbitrary string into a list of tuples, where each tuple contains a line of text and its line ending. Args: input_string (str): The string to split. Returns: list[tuple[str, str]]: A list of tuples, where each tuple contains a line of text and its line ending. Example: split_string_to_lines_and_endings("Hello\r\nWorld\nThis is a test\rLast line") >>> [('Hello', '\r\n'), ('World', '\n'), ('This is a test', '\r'), ('Last line', '')]
def line_split(input_string: str) -> list[tuple[str, str]]: r""" Splits an arbitrary string into a list of tuples, where each tuple contains a line of text and its line ending. Args: input_string (str): The string to split. Returns: list[tuple[str, str]]: A list of tuples, where each tuple contains a line of text and its line ending. Example: split_string_to_lines_and_endings("Hello\r\nWorld\nThis is a test\rLast line") >>> [('Hello', '\r\n'), ('World', '\n'), ('This is a test', '\r'), ('Last line', '')] """ return LINE_AND_ENDING_PATTERN.findall(input_string)[:-1] if input_string else []
Iterate and generate a tuple with a flag for first value.
def loop_first(values: Iterable[T]) -> Iterable[tuple[bool, T]]: """Iterate and generate a tuple with a flag for first value.""" iter_values = iter(values) try: value = next(iter_values) except StopIteration: return yield True, value for value in iter_values: yield False, value
Iterate and generate a tuple with a flag for last value.
def loop_last(values: Iterable[T]) -> Iterable[tuple[bool, T]]: """Iterate and generate a tuple with a flag for last value.""" iter_values = iter(values) try: previous_value = next(iter_values) except StopIteration: return for value in iter_values: yield False, previous_value previous_value = value yield True, previous_value
Iterate and generate a tuple with a flag for first and last value.
def loop_first_last(values: Iterable[T]) -> Iterable[tuple[bool, bool, T]]: """Iterate and generate a tuple with a flag for first and last value.""" iter_values = iter(values) try: previous_value = next(iter_values) except StopIteration: return first = True for value in iter_values: yield first, False, previous_value first = False previous_value = value yield first, True, previous_value
Decorator to declare that the method is a message handler. The decorator accepts an optional CSS selector that will be matched against a widget exposed by a `control` property on the message. Example: ```python # Handle the press of buttons with ID "#quit". @on(Button.Pressed, "#quit") def quit_button(self) -> None: self.app.quit() ``` Keyword arguments can be used to match additional selectors for attributes listed in [`ALLOW_SELECTOR_MATCH`][textual.message.Message.ALLOW_SELECTOR_MATCH]. Example: ```python # Handle the activation of the tab "#home" within the `TabbedContent` "#tabs". @on(TabbedContent.TabActivated, "#tabs", pane="#home") def switch_to_home(self) -> None: self.log("Switching back to the home tab.") ... ``` Args: message_type: The message type (i.e. the class). selector: An optional [selector](/guide/CSS#selectors). If supplied, the handler will only be called if `selector` matches the widget from the `control` attribute of the message. **kwargs: Additional selectors for other attributes of the message.
def on( message_type: type[Message], selector: str | None = None, **kwargs: str ) -> Callable[[DecoratedType], DecoratedType]: """Decorator to declare that the method is a message handler. The decorator accepts an optional CSS selector that will be matched against a widget exposed by a `control` property on the message. Example: ```python # Handle the press of buttons with ID "#quit". @on(Button.Pressed, "#quit") def quit_button(self) -> None: self.app.quit() ``` Keyword arguments can be used to match additional selectors for attributes listed in [`ALLOW_SELECTOR_MATCH`][textual.message.Message.ALLOW_SELECTOR_MATCH]. Example: ```python # Handle the activation of the tab "#home" within the `TabbedContent` "#tabs". @on(TabbedContent.TabActivated, "#tabs", pane="#home") def switch_to_home(self) -> None: self.log("Switching back to the home tab.") ... ``` Args: message_type: The message type (i.e. the class). selector: An optional [selector](/guide/CSS#selectors). If supplied, the handler will only be called if `selector` matches the widget from the `control` attribute of the message. **kwargs: Additional selectors for other attributes of the message. """ selectors: dict[str, str] = {} if selector is not None: selectors["control"] = selector if kwargs: selectors.update(kwargs) parsed_selectors: dict[str, tuple[SelectorSet, ...]] = {} for attribute, css_selector in selectors.items(): if attribute == "control": if message_type.control == Message.control: raise OnDecoratorError( "The message class must have a 'control' to match with the on decorator" ) elif attribute not in message_type.ALLOW_SELECTOR_MATCH: raise OnDecoratorError( f"The attribute {attribute!r} can't be matched; have you added it to " + f"{message_type.__name__}.ALLOW_SELECTOR_MATCH?" ) try: parsed_selectors[attribute] = parse_selectors(css_selector) except TokenError: raise OnDecoratorError( f"Unable to parse selector {css_selector!r} for {attribute}; check for syntax errors" ) from None def decorator(method: DecoratedType) -> DecoratedType: """Store message and selector in function attribute, return callable unaltered.""" if not hasattr(method, "_textual_on"): setattr(method, "_textual_on", []) getattr(method, "_textual_on").append((message_type, parsed_selectors)) return method return decorator
Takes an iterable of foreground Segments and blends them into the supplied background color, yielding copies of the Segments with blended foreground and background colors applied. Args: segments: The segments in the foreground. base_background: The background color to blend foreground into. opacity: The blending factor. A value of 1.0 means output segments will have identical foreground and background colors to input segments.
def _apply_opacity( segments: Iterable[Segment], base_background: Color, opacity: float, ) -> Iterable[Segment]: """Takes an iterable of foreground Segments and blends them into the supplied background color, yielding copies of the Segments with blended foreground and background colors applied. Args: segments: The segments in the foreground. base_background: The background color to blend foreground into. opacity: The blending factor. A value of 1.0 means output segments will have identical foreground and background colors to input segments. """ _Segment = Segment from_rich_color = Color.from_rich_color from_color = Style.from_color blend = base_background.blend styled_segments = cast("Iterable[tuple[str, Style, object]]", segments) for text, style, _ in styled_segments: blended_style = style if style.color is not None: color = from_rich_color(style.color) blended_foreground = blend(color, opacity) blended_style += from_color(color=blended_foreground.rich_color) if style.bgcolor is not None: bgcolor = from_rich_color(style.bgcolor) blended_background = blend(bgcolor, opacity) blended_style += from_color(bgcolor=blended_background.rich_color) yield _Segment(text, blended_style)
Partition a sequence in to two list from a given predicate. The first list will contain the values where the predicate is False, the second list will contain the remaining values. Args: predicate: A callable that returns True or False for a given value. iterable: In Iterable of values. Returns: A list of values where the predicate is False, and a list where the predicate is True.
def partition( predicate: Callable[[T], object], iterable: Iterable[T] ) -> tuple[list[T], list[T]]: """Partition a sequence in to two list from a given predicate. The first list will contain the values where the predicate is False, the second list will contain the remaining values. Args: predicate: A callable that returns True or False for a given value. iterable: In Iterable of values. Returns: A list of values where the predicate is False, and a list where the predicate is True. """ result: tuple[list[T], list[T]] = ([], []) appends = (result[0].append, result[1].append) for value in iterable: appends[1 if predicate(value) else 0](value) return result
Normalize the supplied CSSPathType into a list of paths. Args: css_path: Value to be normalized. Raises: CSSPathError: If the argument has the wrong format. Returns: A list of paths.
def _css_path_type_as_list(css_path: CSSPathType) -> list[PurePath]: """Normalize the supplied CSSPathType into a list of paths. Args: css_path: Value to be normalized. Raises: CSSPathError: If the argument has the wrong format. Returns: A list of paths. """ paths: list[PurePath] = [] if isinstance(css_path, str): paths = [Path(css_path)] elif isinstance(css_path, PurePath): paths = [css_path] elif isinstance(css_path, list): paths = [Path(path) for path in css_path] else: raise CSSPathError("Expected a str, Path or list[str | Path] for the CSS_PATH.") return paths
Convert the supplied path to a Path object that is relative to a given Python object. If the supplied path is absolute, it will simply be converted to a Path object. Used, for example, to return the path of a CSS file relative to a Textual App instance. Args: path: A path. obj: A Python object to resolve the path relative to. Returns: A resolved Path object, relative to obj
def _make_path_object_relative(path: str | PurePath, obj: object) -> Path: """Convert the supplied path to a Path object that is relative to a given Python object. If the supplied path is absolute, it will simply be converted to a Path object. Used, for example, to return the path of a CSS file relative to a Textual App instance. Args: path: A path. obj: A Python object to resolve the path relative to. Returns: A resolved Path object, relative to obj """ path = Path(path) # If the path supplied by the user is absolute, we can use it directly if path.is_absolute(): return path # Otherwise (relative path), resolve it relative to obj... base_path = getattr(obj, "_BASE_PATH", None) if base_path is not None: subclass_path = Path(base_path) else: subclass_path = Path(inspect.getfile(obj.__class__)) resolved_path = (subclass_path.parent / path).resolve() return resolved_path
print the elapsed time. (only used in debugging)
def timer(subject: str = "time") -> Generator[None, None, None]: """print the elapsed time. (only used in debugging)""" start = perf_counter() yield elapsed = perf_counter() - start elapsed_ms = elapsed * 1000 log(f"{subject} elapsed {elapsed_ms:.2f}ms")
Resolve a list of dimensions. Args: dimensions: Scalars for column / row sizes. total: Total space to divide. gutter: Gutter between rows / columns. size: Size of container. viewport: Size of viewport. Returns: List of (<OFFSET>, <LENGTH>)
def resolve( dimensions: Sequence[Scalar], total: int, gutter: int, size: Size, viewport: Size, ) -> list[tuple[int, int]]: """Resolve a list of dimensions. Args: dimensions: Scalars for column / row sizes. total: Total space to divide. gutter: Gutter between rows / columns. size: Size of container. viewport: Size of viewport. Returns: List of (<OFFSET>, <LENGTH>) """ resolved: list[tuple[Scalar, Fraction | None]] = [ ( (scalar, None) if scalar.is_fraction else (scalar, scalar.resolve(size, viewport)) ) for scalar in dimensions ] from_float = Fraction.from_float total_fraction = from_float( sum([scalar.value for scalar, fraction in resolved if fraction is None]) ) if total_fraction: total_gutter = gutter * (len(dimensions) - 1) consumed = sum([fraction for _, fraction in resolved if fraction is not None]) remaining = max(Fraction(0), Fraction(total - total_gutter) - consumed) fraction_unit = Fraction(remaining, total_fraction) resolved_fractions = [ from_float(scalar.value) * fraction_unit if fraction is None else fraction for scalar, fraction in resolved ] else: resolved_fractions = cast( "list[Fraction]", [fraction for _, fraction in resolved] ) fraction_gutter = Fraction(gutter) offsets = [0] + [ int(fraction) for fraction in accumulate( value for fraction in resolved_fractions for value in (fraction, fraction_gutter) ) ] results = [ (offset1, offset2 - offset1) for offset1, offset2 in zip(offsets[::2], offsets[1::2]) ] return results
Calculate the fraction. Args: widget_styles: Styles for widgets with fraction units. size: Container size. viewport_size: Viewport size. remaining_space: Remaining space for fr units. resolve_dimension: Which dimension to resolve. Returns: The value of 1fr.
def resolve_fraction_unit( widget_styles: Iterable[RenderStyles], size: Size, viewport_size: Size, remaining_space: Fraction, resolve_dimension: Literal["width", "height"] = "width", ) -> Fraction: """Calculate the fraction. Args: widget_styles: Styles for widgets with fraction units. size: Container size. viewport_size: Viewport size. remaining_space: Remaining space for fr units. resolve_dimension: Which dimension to resolve. Returns: The value of 1fr. """ if not remaining_space or not widget_styles: return Fraction(1) initial_space = remaining_space def resolve_scalar( scalar: Scalar | None, fraction_unit: Fraction = Fraction(1) ) -> Fraction | None: """Resolve a scalar if it is not None. Args: scalar: Optional scalar to resolve. fraction_unit: Size of 1fr. Returns: Fraction if resolved, otherwise None. """ return ( None if scalar is None else scalar.resolve(size, viewport_size, fraction_unit) ) resolve: list[tuple[Scalar, Fraction | None, Fraction | None]] = [] if resolve_dimension == "width": resolve = [ ( cast(Scalar, styles.width), resolve_scalar(styles.min_width), resolve_scalar(styles.max_width), ) for styles in widget_styles if styles.overlay != "screen" ] else: resolve = [ ( cast(Scalar, styles.height), resolve_scalar(styles.min_height), resolve_scalar(styles.max_height), ) for styles in widget_styles if styles.overlay != "screen" ] resolved: list[Fraction | None] = [None] * len(resolve) remaining_fraction = Fraction(sum(scalar.value for scalar, _, _ in resolve)) while remaining_fraction > 0: remaining_space_changed = False resolve_fraction = Fraction(remaining_space, remaining_fraction) for index, (scalar, min_value, max_value) in enumerate(resolve): value = resolved[index] if value is None: resolved_scalar = scalar.resolve(size, viewport_size, resolve_fraction) if min_value is not None and resolved_scalar < min_value: remaining_space -= min_value remaining_fraction -= Fraction(scalar.value) resolved[index] = min_value remaining_space_changed = True elif max_value is not None and resolved_scalar > max_value: remaining_space -= max_value remaining_fraction -= Fraction(scalar.value) resolved[index] = max_value remaining_space_changed = True if not remaining_space_changed: break return ( Fraction(remaining_space, remaining_fraction) if remaining_fraction > 0 else initial_space )
Resolve box models for a list of dimensions Args: dimensions: A list of Scalars or Nones for each dimension. widgets: Widgets in resolve. size: Size of container. viewport_size: Viewport size. margin: Total space occupied by margin resolve_dimension: Which dimension to resolve. Returns: List of resolved box models.
def resolve_box_models( dimensions: list[Scalar | None], widgets: list[Widget], size: Size, viewport_size: Size, margin: Size, resolve_dimension: Literal["width", "height"] = "width", ) -> list[BoxModel]: """Resolve box models for a list of dimensions Args: dimensions: A list of Scalars or Nones for each dimension. widgets: Widgets in resolve. size: Size of container. viewport_size: Viewport size. margin: Total space occupied by margin resolve_dimension: Which dimension to resolve. Returns: List of resolved box models. """ margin_width, margin_height = margin fraction_width = Fraction(max(0, size.width - margin_width)) fraction_height = Fraction(max(0, size.height - margin_height)) margin_size = size - margin # Fixed box models box_models: list[BoxModel | None] = [ ( None if _dimension is not None and _dimension.is_fraction else widget._get_box_model( size, viewport_size, fraction_width, fraction_height ) ) for (_dimension, widget) in zip(dimensions, widgets) ] if None not in box_models: # No fr units, so we're done return cast("list[BoxModel]", box_models) # If all box models have been calculated widget_styles = [widget.styles for widget in widgets] if resolve_dimension == "width": total_remaining = int( sum( [ box_model.width for widget, box_model in zip(widgets, box_models) if (box_model is not None and widget.styles.overlay != "screen") ] ) ) remaining_space = int(max(0, size.width - total_remaining - margin_width)) fraction_unit = resolve_fraction_unit( [ styles for styles in widget_styles if styles.width is not None and styles.width.is_fraction and styles.overlay != "screen" ], size, viewport_size, Fraction(remaining_space), resolve_dimension, ) width_fraction = fraction_unit height_fraction = Fraction(margin_size.height) else: total_remaining = int( sum( [ box_model.height for widget, box_model in zip(widgets, box_models) if (box_model is not None and widget.styles.overlay != "screen") ] ) ) remaining_space = int(max(0, size.height - total_remaining - margin_height)) fraction_unit = resolve_fraction_unit( [ styles for styles in widget_styles if styles.height is not None and styles.height.is_fraction and styles.overlay != "screen" ], size, viewport_size, Fraction(remaining_space), resolve_dimension, ) width_fraction = Fraction(margin_size.width) height_fraction = fraction_unit box_models = [ box_model or widget._get_box_model( size, viewport_size, width_fraction, height_fraction, ) for widget, box_model in zip(widgets, box_models) ] return cast("list[BoxModel]", box_models)
Given a character index, return the cell position of that character within an Iterable of Segments. This is the sum of the cell lengths of all the characters *before* the character at `index`. Args: segments: The segments to find the cell position within. index: The index to convert into a cell position. Returns: The cell position of the character at `index`. Raises: NoCellPositionForIndex: If the supplied index doesn't fall within the given segments.
def index_to_cell_position(segments: Iterable[Segment], index: int) -> int: """Given a character index, return the cell position of that character within an Iterable of Segments. This is the sum of the cell lengths of all the characters *before* the character at `index`. Args: segments: The segments to find the cell position within. index: The index to convert into a cell position. Returns: The cell position of the character at `index`. Raises: NoCellPositionForIndex: If the supplied index doesn't fall within the given segments. """ if not segments: raise NoCellPositionForIndex if index == 0: return 0 cell_position_end = 0 segment_length = 0 segment_end_index = 0 segment_cell_length = 0 text = "" iter_segments = iter(segments) try: while segment_end_index < index: segment = next(iter_segments) text = segment.text segment_length = len(text) segment_cell_length = cell_len(text) cell_position_end += segment_cell_length segment_end_index += segment_length except StopIteration: raise NoCellPositionForIndex # Check how far into this segment the target index is segment_index_start = segment_end_index - segment_length index_within_segment = index - segment_index_start segment_cell_start = cell_position_end - segment_cell_length return segment_cell_start + cell_len(text[:index_within_segment])
Crops a list of segments between two cell offsets. Args: segments: A list of Segments for a line. start: Start offset (cells) end: End offset (cells, exclusive) total: Total cell length of segments. Returns: A new shorter list of segments
def line_crop( segments: list[Segment], start: int, end: int, total: int ) -> list[Segment]: """Crops a list of segments between two cell offsets. Args: segments: A list of Segments for a line. start: Start offset (cells) end: End offset (cells, exclusive) total: Total cell length of segments. Returns: A new shorter list of segments """ # This is essentially a specialized version of Segment.divide # The following line has equivalent functionality (but a little slower) # return list(Segment.divide(segments, [start, end]))[1] _cell_len = cell_len pos = 0 output_segments: list[Segment] = [] add_segment = output_segments.append iter_segments = iter(segments) segment: Segment | None = None for segment in iter_segments: end_pos = pos + _cell_len(segment.text) if end_pos > start: segment = segment.split_cells(start - pos)[1] break pos = end_pos else: return [] if end >= total: # The end crop is the end of the segments, so we can collect all remaining segments if segment: add_segment(segment) output_segments.extend(iter_segments) return output_segments pos = start while segment is not None: end_pos = pos + _cell_len(segment.text) if end_pos < end: add_segment(segment) else: add_segment(segment.split_cells(end - pos)[0]) break pos = end_pos segment = next(iter_segments, None) return output_segments
Optionally remove a cell from the start and / or end of a list of segments. Args: segments: A line (list of Segments) start: Remove cell from start. end: Remove cell from end. Returns: A new list of segments.
def line_trim(segments: list[Segment], start: bool, end: bool) -> list[Segment]: """Optionally remove a cell from the start and / or end of a list of segments. Args: segments: A line (list of Segments) start: Remove cell from start. end: Remove cell from end. Returns: A new list of segments. """ segments = segments.copy() if segments and start: _, first_segment = segments[0].split_cells(1) if first_segment.text: segments[0] = first_segment else: segments.pop(0) if segments and end: last_segment = segments[-1] last_segment, _ = last_segment.split_cells(len(last_segment.text) - 1) if last_segment.text: segments[-1] = last_segment else: segments.pop() return segments
Adds padding to the left and / or right of a list of segments. Args: segments: A line of segments. pad_left: Cells to pad on the left. pad_right: Cells to pad on the right. style: Style of padded cells. Returns: A new line with padding.
def line_pad( segments: Iterable[Segment], pad_left: int, pad_right: int, style: Style ) -> list[Segment]: """Adds padding to the left and / or right of a list of segments. Args: segments: A line of segments. pad_left: Cells to pad on the left. pad_right: Cells to pad on the right. style: Style of padded cells. Returns: A new line with padding. """ if pad_left and pad_right: return [ Segment(" " * pad_left, style), *segments, Segment(" " * pad_right, style), ] elif pad_left: return [ Segment(" " * pad_left, style), *segments, ] elif pad_right: return [ *segments, Segment(" " * pad_right, style), ] return list(segments)
Align lines. Args: lines: A list of lines. style: Background style. size: Size of container. horizontal: Horizontal alignment. vertical: Vertical alignment. Returns: Aligned lines.
def align_lines( lines: list[list[Segment]], style: Style, size: Size, horizontal: AlignHorizontal, vertical: AlignVertical, ) -> Iterable[list[Segment]]: """Align lines. Args: lines: A list of lines. style: Background style. size: Size of container. horizontal: Horizontal alignment. vertical: Vertical alignment. Returns: Aligned lines. """ if not lines: return width, height = size get_line_length = Segment.get_line_length line_lengths = [get_line_length(line) for line in lines] shape_width = max(line_lengths) shape_height = len(line_lengths) def blank_lines(count: int) -> list[list[Segment]]: """Create blank lines. Args: count: Desired number of blank lines. Returns: A list of blank lines. """ return [[Segment(" " * width, style)]] * count top_blank_lines = bottom_blank_lines = 0 vertical_excess_space = max(0, height - shape_height) if vertical == "top": bottom_blank_lines = vertical_excess_space elif vertical == "middle": top_blank_lines = vertical_excess_space // 2 bottom_blank_lines = vertical_excess_space - top_blank_lines elif vertical == "bottom": top_blank_lines = vertical_excess_space if top_blank_lines: yield from blank_lines(top_blank_lines) horizontal_excess_space = max(0, width - shape_width) if horizontal == "left": for cell_length, line in zip(line_lengths, lines): if cell_length == width: yield line else: yield line_pad(line, 0, width - cell_length, style) elif horizontal == "center": left_space = horizontal_excess_space // 2 for cell_length, line in zip(line_lengths, lines): if cell_length == width: yield line else: yield line_pad( line, left_space, width - cell_length - left_space, style ) elif horizontal == "right": for cell_length, line in zip(line_lengths, lines): if width == cell_length: yield line else: yield line_pad(line, width - cell_length, 0, style) if bottom_blank_lines: yield from blank_lines(bottom_blank_lines)
Create a Markdown-friendly slug from the given text. Args: text: The text to generate a slug from. Returns: A slug for the given text. The rules used in generating the slug are based on observations of how GitHub-flavoured Markdown works.
def slug(text: str) -> str: """Create a Markdown-friendly slug from the given text. Args: text: The text to generate a slug from. Returns: A slug for the given text. The rules used in generating the slug are based on observations of how GitHub-flavoured Markdown works. """ result = text.strip().lower() for rule, replacement in ( (STRIP_RE, ""), (WHITESPACE_RE, WHITESPACE_REPLACEMENT), ): result = rule.sub(replacement, result) return quote(result)
Make a blank segment. Args: width: Width of blank. style: Style of blank. Returns: A single segment
def make_blank(width, style: Style) -> Segment: """Make a blank segment. Args: width: Width of blank. style: Style of blank. Returns: A single segment """ return Segment(intern(" " * width), style)
Computes the distance going from `start` to `index` in the given direction. Starting at `start`, this is the number of steps you need to take in the given `direction` to reach `index`, assuming there is wrapping at 0 and `wrap_at`. This is also the smallest non-negative integer solution `d` to `(start + d * direction) % wrap_at == index`. The diagram below illustrates the computation of `d1 = distance(2, 8, 1, 10)` and `d2 = distance(2, 8, -1, 10)`: ``` start ────────────────────┐ index ────────┐ │ indices 0 1 2 3 4 5 6 7 8 9 d1 2 3 4 0 1 > > > > > (direction == 1) d2 6 5 4 3 2 1 0 < < < < < < < (direction == -1) ``` Args: index: The index that we want to reach. start: The starting point to consider when computing the distance. direction: The direction in which we want to compute the distance. wrap_at: Controls at what point wrapping around takes place. Returns: The computed distance.
def get_directed_distance( index: int, start: int, direction: Direction, wrap_at: int ) -> int: """Computes the distance going from `start` to `index` in the given direction. Starting at `start`, this is the number of steps you need to take in the given `direction` to reach `index`, assuming there is wrapping at 0 and `wrap_at`. This is also the smallest non-negative integer solution `d` to `(start + d * direction) % wrap_at == index`. The diagram below illustrates the computation of `d1 = distance(2, 8, 1, 10)` and `d2 = distance(2, 8, -1, 10)`: ``` start ────────────────────┐ index ────────┐ │ indices 0 1 2 3 4 5 6 7 8 9 d1 2 3 4 0 1 > > > > > (direction == 1) d2 6 5 4 3 2 1 0 < < < < < < < (direction == -1) ``` Args: index: The index that we want to reach. start: The starting point to consider when computing the distance. direction: The direction in which we want to compute the distance. wrap_at: Controls at what point wrapping around takes place. Returns: The computed distance. """ return direction * (index - start) % wrap_at
Find the first enabled candidate in a sequence of possibly-disabled objects. Args: candidates: The sequence of candidates to consider. Returns: The first enabled candidate or `None` if none were available.
def find_first_enabled( candidates: Sequence[Disableable], ) -> int | None: """Find the first enabled candidate in a sequence of possibly-disabled objects. Args: candidates: The sequence of candidates to consider. Returns: The first enabled candidate or `None` if none were available. """ return next( (index for index, candidate in enumerate(candidates) if not candidate.disabled), None, )
Find the last enabled candidate in a sequence of possibly-disabled objects. Args: candidates: The sequence of candidates to consider. Returns: The last enabled candidate or `None` if none were available.
def find_last_enabled(candidates: Sequence[Disableable]) -> int | None: """Find the last enabled candidate in a sequence of possibly-disabled objects. Args: candidates: The sequence of candidates to consider. Returns: The last enabled candidate or `None` if none were available. """ total_candidates = len(candidates) return next( ( total_candidates - offset_from_end for offset_from_end, candidate in enumerate(reversed(candidates), start=1) if not candidate.disabled ), None, )
Find the next enabled object if we're currently at the given anchor. The definition of "next" depends on the given direction and this function will wrap around the ends of the sequence of object candidates. Args: candidates: The sequence of object candidates to consider. anchor: The point of the sequence from which we'll start looking for the next enabled object. direction: The direction in which to traverse the candidates when looking for the next enabled candidate. with_anchor: Consider the anchor position as the first valid position instead of the last one. Returns: The next enabled object. If none are available, return the anchor.
def find_next_enabled( candidates: Sequence[Disableable], anchor: int | None, direction: Direction, with_anchor: bool = False, ) -> int | None: """Find the next enabled object if we're currently at the given anchor. The definition of "next" depends on the given direction and this function will wrap around the ends of the sequence of object candidates. Args: candidates: The sequence of object candidates to consider. anchor: The point of the sequence from which we'll start looking for the next enabled object. direction: The direction in which to traverse the candidates when looking for the next enabled candidate. with_anchor: Consider the anchor position as the first valid position instead of the last one. Returns: The next enabled object. If none are available, return the anchor. """ if anchor is None: if candidates: return ( find_first_enabled(candidates) if direction == 1 else find_last_enabled(candidates) ) return None start = anchor + direction if not with_anchor else anchor key_function = partial( get_directed_distance, start=start, direction=direction, wrap_at=len(candidates), ) enabled_candidates = [ index for index, candidate in enumerate(candidates) if not candidate.disabled ] return min(enabled_candidates, key=key_function, default=anchor)
Find the next enabled object starting from the given anchor (without wrapping). The meaning of "next" and "past" depend on the direction specified. Args: candidates: The sequence of object candidates to consider. anchor: The point of the sequence from which we'll start looking for the next enabled object. direction: The direction in which to traverse the candidates when looking for the next enabled candidate. with_anchor: Whether to consider the anchor or not. Returns: The next enabled object. If none are available, return None.
def find_next_enabled_no_wrap( candidates: Sequence[Disableable], anchor: int | None, direction: Direction, with_anchor: bool = False, ) -> int | None: """Find the next enabled object starting from the given anchor (without wrapping). The meaning of "next" and "past" depend on the direction specified. Args: candidates: The sequence of object candidates to consider. anchor: The point of the sequence from which we'll start looking for the next enabled object. direction: The direction in which to traverse the candidates when looking for the next enabled candidate. with_anchor: Whether to consider the anchor or not. Returns: The next enabled object. If none are available, return None. """ if anchor is None: if candidates: return ( find_first_enabled(candidates) if direction == 1 else find_last_enabled(candidates) ) return None start = anchor if with_anchor else anchor + direction counter = count(start, direction) valid_candidates = ( candidates[start:] if direction == 1 else reversed(candidates[: start + 1]) ) for idx, candidate in zip(counter, valid_candidates): if candidate.disabled: continue return idx return None
A decorator used to create [workers](/guide/workers). Args: method: A function or coroutine. name: A short string to identify the worker (in logs and debugging). group: A short string to identify a group of workers. exit_on_error: Exit the app if the worker raises an error. Set to `False` to suppress exceptions. exclusive: Cancel all workers in the same group. description: Readable description of the worker for debugging purposes. By default, it uses a string representation of the decorated method and its arguments. thread: Mark the method as a thread worker.
def work( method: ( Callable[FactoryParamSpec, ReturnType] | Callable[FactoryParamSpec, Coroutine[None, None, ReturnType]] | None ) = None, *, name: str = "", group: str = "default", exit_on_error: bool = True, exclusive: bool = False, description: str | None = None, thread: bool = False, ) -> Callable[FactoryParamSpec, Worker[ReturnType]] | Decorator: """A decorator used to create [workers](/guide/workers). Args: method: A function or coroutine. name: A short string to identify the worker (in logs and debugging). group: A short string to identify a group of workers. exit_on_error: Exit the app if the worker raises an error. Set to `False` to suppress exceptions. exclusive: Cancel all workers in the same group. description: Readable description of the worker for debugging purposes. By default, it uses a string representation of the decorated method and its arguments. thread: Mark the method as a thread worker. """ def decorator( method: ( Callable[DecoratorParamSpec, ReturnType] | Callable[DecoratorParamSpec, Coroutine[None, None, ReturnType]] ) ) -> Callable[DecoratorParamSpec, Worker[ReturnType]]: """The decorator.""" # Methods that aren't async *must* be marked as being a thread # worker. if not iscoroutinefunction(method) and not thread: raise WorkerDeclarationError( "Can not create a worker from a non-async function unless `thread=True` is set on the work decorator." ) @wraps(method) def decorated( *args: DecoratorParamSpec.args, **kwargs: DecoratorParamSpec.kwargs ) -> Worker[ReturnType]: """The replaced callable.""" from .dom import DOMNode self = args[0] assert isinstance(self, DOMNode) if description is not None: debug_description = description else: try: positional_arguments = ", ".join(repr(arg) for arg in args[1:]) keyword_arguments = ", ".join( f"{name}={value!r}" for name, value in kwargs.items() ) tokens = [positional_arguments, keyword_arguments] debug_description = f"{method.__name__}({', '.join(token for token in tokens if token)})" except Exception: debug_description = "<worker>" worker = cast( "Worker[ReturnType]", self.run_worker( partial(method, *args, **kwargs), name=name or method.__name__, group=group, description=debug_description, exclusive=exclusive, exit_on_error=exit_on_error, thread=thread, ), ) return worker return decorated if method is None: return decorator else: return decorator(method)
Yields each "chunk" from the text as a tuple containing (start_index, end_index, chunk_content). A "chunk" in this context refers to a word and any whitespace around it. Args: text: The text to split into chunks. Returns: Yields tuples containing the start, end and content for each chunk.
def chunks(text: str) -> Iterable[tuple[int, int, str]]: """Yields each "chunk" from the text as a tuple containing (start_index, end_index, chunk_content). A "chunk" in this context refers to a word and any whitespace around it. Args: text: The text to split into chunks. Returns: Yields tuples containing the start, end and content for each chunk. """ end = 0 while (chunk_match := re_chunk.match(text, end)) is not None: start, end = chunk_match.span() chunk = chunk_match.group(0) yield start, end, chunk
Given a string of text, and a width (measured in cells), return a list of codepoint indices which the string should be split at in order for it to fit within the given width. Args: text: The text to examine. width: The available cell width. tab_size: The tab stop width. fold: If True, words longer than `width` will be folded onto a new line. precomputed_tab_sections: The output of `get_tab_widths` can be passed here directly, to prevent us from having to recompute the value. Returns: A list of indices to break the line at.
def compute_wrap_offsets( text: str, width: int, tab_size: int, fold: bool = True, precomputed_tab_sections: list[tuple[str, int]] | None = None, ) -> list[int]: """Given a string of text, and a width (measured in cells), return a list of codepoint indices which the string should be split at in order for it to fit within the given width. Args: text: The text to examine. width: The available cell width. tab_size: The tab stop width. fold: If True, words longer than `width` will be folded onto a new line. precomputed_tab_sections: The output of `get_tab_widths` can be passed here directly, to prevent us from having to recompute the value. Returns: A list of indices to break the line at. """ tab_size = min(tab_size, width) if precomputed_tab_sections: tab_sections = precomputed_tab_sections else: tab_sections = get_tab_widths(text, tab_size) break_positions: list[int] = [] # offsets to insert the breaks at append = break_positions.append cell_offset = 0 _cell_len = cell_len tab_section_index = 0 cumulative_width = 0 cumulative_widths: list[int] = [] # prefix sum of tab widths for each codepoint record_widths = cumulative_widths.extend for last, (tab_section, tab_width) in loop_last(tab_sections): # add 1 since the \t character is stripped by get_tab_widths section_codepoint_length = len(tab_section) + int(bool(tab_width)) widths = [cumulative_width] * section_codepoint_length record_widths(widths) cumulative_width += tab_width if last: cumulative_widths.append(cumulative_width) for start, end, chunk in chunks(text): chunk_width = _cell_len(chunk) # this cell len excludes tabs completely tab_width_before_start = cumulative_widths[start] tab_width_before_end = cumulative_widths[end] chunk_tab_width = tab_width_before_end - tab_width_before_start chunk_width += chunk_tab_width remaining_space = width - cell_offset chunk_fits = remaining_space >= chunk_width if chunk_fits: # Simplest case - the word fits within the remaining width for this line. cell_offset += chunk_width else: # Not enough space remaining for this word on the current line. if chunk_width > width: # The word doesn't fit on any line, so we must fold it if fold: _get_character_cell_size = get_character_cell_size lines: list[list[str]] = [[]] append_new_line = lines.append append_to_last_line = lines[-1].append total_width = 0 for character in chunk: if character == "\t": # Tab characters have dynamic width, so look it up cell_width = tab_sections[tab_section_index][1] tab_section_index += 1 else: cell_width = _get_character_cell_size(character) if total_width + cell_width > width: append_new_line([character]) append_to_last_line = lines[-1].append total_width = cell_width else: append_to_last_line(character) total_width += cell_width folded_word = ["".join(line) for line in lines] for last, line in loop_last(folded_word): if start: append(start) if last: # Since cell_len ignores tabs, we need to check the width # of the tabs in this line. The width of tabs within the # line is computed by taking the difference between the # cumulative width of tabs up to the end of the line and the # cumulative width of tabs up to the start of the line. line_tab_widths = ( cumulative_widths[start + len(line)] - cumulative_widths[start] ) cell_offset = _cell_len(line) + line_tab_widths else: start += len(line) else: # Folding isn't allowed, so crop the word. if start: append(start) cell_offset = chunk_width elif cell_offset and start: # The word doesn't fit within the remaining space on the current # line, but it *can* fit on to the next (empty) line. append(start) cell_offset = chunk_width return break_positions
Check if a given node matches any of the given selector sets. Args: selector_sets: Iterable of selector sets. node: DOM node. Returns: True if the node matches the selector, otherwise False.
def match(selector_sets: Iterable[SelectorSet], node: DOMNode) -> bool: """Check if a given node matches any of the given selector sets. Args: selector_sets: Iterable of selector sets. node: DOM node. Returns: True if the node matches the selector, otherwise False. """ return any( _check_selectors(selector_set.selectors, node.css_path_nodes) for selector_set in selector_sets )
Match a list of selectors against DOM nodes. Args: selectors: A list of selectors. css_path_nodes: The DOM nodes to check the selectors against. Returns: True if any node in css_path_nodes matches a selector.
def _check_selectors(selectors: list[Selector], css_path_nodes: list[DOMNode]) -> bool: """Match a list of selectors against DOM nodes. Args: selectors: A list of selectors. css_path_nodes: The DOM nodes to check the selectors against. Returns: True if any node in css_path_nodes matches a selector. """ DESCENDENT = CombinatorType.DESCENDENT node = css_path_nodes[-1] path_count = len(css_path_nodes) selector_count = len(selectors) stack: list[tuple[int, int]] = [(0, 0)] push = stack.append pop = stack.pop selector_index = 0 while stack: selector_index, node_index = stack[-1] if selector_index == selector_count or node_index == path_count: pop() else: path_node = css_path_nodes[node_index] selector = selectors[selector_index] if selector.combinator == DESCENDENT: # Find a matching descendent if selector.check(path_node): if path_node is node and selector_index == selector_count - 1: return True stack[-1] = (selector_index + 1, node_index + selector.advance) push((selector_index, node_index + 1)) else: stack[-1] = (selector_index, node_index + 1) else: # Match the next node if selector.check(path_node): if path_node is node and selector_index == selector_count - 1: return True stack[-1] = (selector_index + 1, node_index + selector.advance) else: pop() return False
Check node matches universal selector. Args: name: Selector name. node: A DOM node. Returns: `True` if the selector matches.
def _check_universal(name: str, node: DOMNode) -> bool: """Check node matches universal selector. Args: name: Selector name. node: A DOM node. Returns: `True` if the selector matches. """ return True
Check node matches a type selector. Args: name: Selector name. node: A DOM node. Returns: `True` if the selector matches.
def _check_type(name: str, node: DOMNode) -> bool: """Check node matches a type selector. Args: name: Selector name. node: A DOM node. Returns: `True` if the selector matches. """ return name in node._css_type_names
Check node matches a class selector. Args: name: Selector name. node: A DOM node. Returns: `True` if the selector matches.
def _check_class(name: str, node: DOMNode) -> bool: """Check node matches a class selector. Args: name: Selector name. node: A DOM node. Returns: `True` if the selector matches. """ return name in node._classes
Check node matches an ID selector. Args: name: Selector name. node: A DOM node. Returns: `True` if the selector matches.
def _check_id(name: str, node: DOMNode) -> bool: """Check node matches an ID selector. Args: name: Selector name. node: A DOM node. Returns: `True` if the selector matches. """ return node.id == name
Add specificity tuples together. Args: specificity1: Specificity triple. specificity2: Specificity triple. Returns: Combined specificity.
def _add_specificity( specificity1: Specificity3, specificity2: Specificity3 ) -> Specificity3: """Add specificity tuples together. Args: specificity1: Specificity triple. specificity2: Specificity triple. Returns: Combined specificity. """ a1, b1, c1 = specificity1 a2, b2, c2 = specificity2 return (a1 + a2, b1 + b2, c1 + c2)
Parse declarations and return a Styles object. Args: css: String containing CSS. read_from: The location where the CSS was read from. Returns: A styles object.
def parse_declarations(css: str, read_from: CSSLocation) -> Styles: """Parse declarations and return a Styles object. Args: css: String containing CSS. read_from: The location where the CSS was read from. Returns: A styles object. """ tokens = iter(tokenize_declarations(css, read_from)) styles_builder = StylesBuilder() declaration: Declaration | None = None errors: list[tuple[Token, str | HelpText]] = [] while True: token = next(tokens, None) if token is None: break token_name = token.name if token_name in ("whitespace", "declaration_end", "eof"): continue if token_name == "declaration_name": if declaration: try: styles_builder.add_declaration(declaration) except DeclarationError as error: errors.append((error.token, error.message)) raise declaration = Declaration(token, "") declaration.name = token.value.rstrip(":") elif token_name == "declaration_set_end": break else: if declaration: declaration.tokens.append(token) if declaration: try: styles_builder.add_declaration(declaration) except DeclarationError as error: errors.append((error.token, error.message)) raise return styles_builder.styles
Raise a TokenError regarding an unresolved variable. Args: variable_name: A variable name. variables: Possible choices used to generate suggestion. token: The Token. Raises: UnresolvedVariableError: Always raises a TokenError.
def _unresolved(variable_name: str, variables: Iterable[str], token: Token) -> NoReturn: """Raise a TokenError regarding an unresolved variable. Args: variable_name: A variable name. variables: Possible choices used to generate suggestion. token: The Token. Raises: UnresolvedVariableError: Always raises a TokenError. """ message = f"reference to undefined variable '${variable_name}'" suggested_variable = get_suggestion(variable_name, list(variables)) if suggested_variable: message += f"; did you mean '${suggested_variable}'?" raise UnresolvedVariableError( token.read_from, token.code, token.start, message, end=token.end, )
Replace variable references with values by substituting variable reference tokens with the tokens representing their values. Args: tokens: Iterator of Tokens which may contain tokens with the name "variable_ref". Returns: Yields Tokens such that any variable references (tokens where token.name == "variable_ref") have been replaced with the tokens representing the value. In other words, an Iterable of Tokens similar to the original input, but with variables resolved. Substituted tokens will have their referenced_by attribute populated with information about where the tokens are being substituted to.
def substitute_references( tokens: Iterable[Token], css_variables: dict[str, list[Token]] | None = None ) -> Iterable[Token]: """Replace variable references with values by substituting variable reference tokens with the tokens representing their values. Args: tokens: Iterator of Tokens which may contain tokens with the name "variable_ref". Returns: Yields Tokens such that any variable references (tokens where token.name == "variable_ref") have been replaced with the tokens representing the value. In other words, an Iterable of Tokens similar to the original input, but with variables resolved. Substituted tokens will have their referenced_by attribute populated with information about where the tokens are being substituted to. """ variables: dict[str, list[Token]] = css_variables.copy() if css_variables else {} iter_tokens = iter(tokens) while True: token = next(iter_tokens, None) if token is None: break if token.name == "variable_name": variable_name = token.value[1:-1] # Trim the $ and the :, i.e. "$x:" -> "x" variable_tokens = variables.setdefault(variable_name, []) yield token while True: token = next(iter_tokens, None) if token is not None and token.name == "whitespace": yield token else: break # Store the tokens for any variable definitions, and substitute # any variable references we encounter with them. while True: if not token: break elif token.name == "whitespace": variable_tokens.append(token) yield token elif token.name == "variable_value_end": yield token break # For variables referring to other variables elif token.name == "variable_ref": ref_name = token.value[1:] if ref_name in variables: reference_tokens = variables[ref_name] variable_tokens.extend(reference_tokens) ref_location = token.location ref_length = len(token.value) for _token in reference_tokens: yield _token.with_reference( ReferencedBy( ref_name, ref_location, ref_length, token.code ) ) else: _unresolved(ref_name, variables.keys(), token) else: variable_tokens.append(token) yield token token = next(iter_tokens, None) elif token.name == "variable_ref": variable_name = token.value[1:] # Trim the $, so $x -> x if variable_name in variables: variable_tokens = variables[variable_name] ref_location = token.location ref_length = len(token.value) ref_code = token.code for _token in variable_tokens: yield _token.with_reference( ReferencedBy(variable_name, ref_location, ref_length, ref_code) ) else: _unresolved(variable_name, variables.keys(), token) else: yield token
Parse CSS by tokenizing it, performing variable substitution, and generating rule sets from it. Args: scope: CSS type name. css: The input CSS. read_from: The source location of the CSS. variables: Substitution variables to substitute tokens for. is_default_rules: True if the rules we're extracting are default (i.e. in Widget.DEFAULT_CSS) rules. False if they're from user defined CSS.
def parse( scope: str, css: str, read_from: CSSLocation, variables: dict[str, str] | None = None, variable_tokens: dict[str, list[Token]] | None = None, is_default_rules: bool = False, tie_breaker: int = 0, ) -> Iterable[RuleSet]: """Parse CSS by tokenizing it, performing variable substitution, and generating rule sets from it. Args: scope: CSS type name. css: The input CSS. read_from: The source location of the CSS. variables: Substitution variables to substitute tokens for. is_default_rules: True if the rules we're extracting are default (i.e. in Widget.DEFAULT_CSS) rules. False if they're from user defined CSS. """ reference_tokens = tokenize_values(variables) if variables is not None else {} if variable_tokens: reference_tokens.update(variable_tokens) tokens = iter(substitute_references(tokenize(css, read_from), variable_tokens)) while True: token = next(tokens, None) if token is None: break if token.name.startswith("selector_start"): yield from parse_rule_set( scope, tokens, token, is_default_rules=is_default_rules, tie_breaker=tie_breaker, )
Resolves explicit cell size, i.e. width: 10 Args: value: Scalar value. size: Size of widget. viewport: Size of viewport. fraction_unit: Size of fraction, i.e. size of 1fr as a Fraction. Returns: Resolved unit.
def _resolve_cells( value: float, size: Size, viewport: Size, fraction_unit: Fraction ) -> Fraction: """Resolves explicit cell size, i.e. width: 10 Args: value: Scalar value. size: Size of widget. viewport: Size of viewport. fraction_unit: Size of fraction, i.e. size of 1fr as a Fraction. Returns: Resolved unit. """ return Fraction(value)
Resolves a fraction unit i.e. width: 2fr Args: value: Scalar value. size: Size of widget. viewport: Size of viewport. fraction_unit: Size of fraction, i.e. size of 1fr as a Fraction. Returns: Resolved unit.
def _resolve_fraction( value: float, size: Size, viewport: Size, fraction_unit: Fraction ) -> Fraction: """Resolves a fraction unit i.e. width: 2fr Args: value: Scalar value. size: Size of widget. viewport: Size of viewport. fraction_unit: Size of fraction, i.e. size of 1fr as a Fraction. Returns: Resolved unit. """ return fraction_unit * Fraction(value)
Resolves width unit i.e. width: 50w. Args: value: Scalar value. size: Size of widget. viewport: Size of viewport. fraction_unit: Size of fraction, i.e. size of 1fr as a Fraction. Returns: Resolved unit.
def _resolve_width( value: float, size: Size, viewport: Size, fraction_unit: Fraction ) -> Fraction: """Resolves width unit i.e. width: 50w. Args: value: Scalar value. size: Size of widget. viewport: Size of viewport. fraction_unit: Size of fraction, i.e. size of 1fr as a Fraction. Returns: Resolved unit. """ return Fraction(value) * Fraction(size.width, 100)
Resolves height unit, i.e. height: 12h. Args: value: Scalar value. size: Size of widget. viewport: Size of viewport. fraction_unit: Size of fraction, i.e. size of 1fr as a Fraction. Returns: Resolved unit.
def _resolve_height( value: float, size: Size, viewport: Size, fraction_unit: Fraction ) -> Fraction: """Resolves height unit, i.e. height: 12h. Args: value: Scalar value. size: Size of widget. viewport: Size of viewport. fraction_unit: Size of fraction, i.e. size of 1fr as a Fraction. Returns: Resolved unit. """ return Fraction(value) * Fraction(size.height, 100)
Resolves view width unit, i.e. width: 25vw. Args: value: Scalar value. size: Size of widget. viewport: Size of viewport. fraction_unit: Size of fraction, i.e. size of 1fr as a Fraction. Returns: Resolved unit.
def _resolve_view_width( value: float, size: Size, viewport: Size, fraction_unit: Fraction ) -> Fraction: """Resolves view width unit, i.e. width: 25vw. Args: value: Scalar value. size: Size of widget. viewport: Size of viewport. fraction_unit: Size of fraction, i.e. size of 1fr as a Fraction. Returns: Resolved unit. """ return Fraction(value) * Fraction(viewport.width, 100)
Resolves view height unit, i.e. height: 25vh. Args: value: Scalar value. size: Size of widget. viewport: Size of viewport. fraction_unit: Size of fraction, i.e. size of 1fr as a Fraction. Returns: Resolved unit.
def _resolve_view_height( value: float, size: Size, viewport: Size, fraction_unit: Fraction ) -> Fraction: """Resolves view height unit, i.e. height: 25vh. Args: value: Scalar value. size: Size of widget. viewport: Size of viewport. fraction_unit: Size of fraction, i.e. size of 1fr as a Fraction. Returns: Resolved unit. """ return Fraction(value) * Fraction(viewport.height, 100)
Get symbols for an iterable of units. Args: units: A number of units. Returns: List of symbols.
def get_symbols(units: Iterable[Unit]) -> list[str]: """Get symbols for an iterable of units. Args: units: A number of units. Returns: List of symbols. """ return [UNIT_SYMBOL[unit] for unit in units]
Convert a string percentage e.g. '20%' to a float e.g. 20.0. Args: string: The percentage string to convert.
def percentage_string_to_float(string: str) -> float: """Convert a string percentage e.g. '20%' to a float e.g. 20.0. Args: string: The percentage string to convert. """ string = string.strip() if string.endswith("%"): float_percentage = clamp(float(string[:-1]) / 100.0, 0.0, 1.0) else: float_percentage = float(string) return float_percentage
Tokenizes the values in a dict of strings. Args: values: A mapping of CSS variable name on to a value, to be added to the CSS context. Returns: A mapping of name on to a list of tokens,
def tokenize_values(values: dict[str, str]) -> dict[str, list[Token]]: """Tokenizes the values in a dict of strings. Args: values: A mapping of CSS variable name on to a value, to be added to the CSS context. Returns: A mapping of name on to a list of tokens, """ value_tokens = { name: list(tokenize_value(value, ("__name__", ""))) for name, value in values.items() } return value_tokens
Generate a list of words as readable prose. >>> friendly_list(["foo", "bar", "baz"]) "'foo', 'bar', or 'baz'" Args: words: A list of words. joiner: The last joiner word. Returns: List as prose.
def friendly_list( words: Iterable[str], joiner: str = "or", omit_empty: bool = True ) -> str: """Generate a list of words as readable prose. >>> friendly_list(["foo", "bar", "baz"]) "'foo', 'bar', or 'baz'" Args: words: A list of words. joiner: The last joiner word. Returns: List as prose. """ words = [ repr(word) for word in sorted(words, key=str.lower) if word or not omit_empty ] if len(words) == 1: return words[0] elif len(words) == 2: word1, word2 = words return f"{word1} {joiner} {word2}" else: return f'{", ".join(words[:-1])}, {joiner} {words[-1]}'
Highlight and render markup in a string of text, returning a styled Text object. Args: text: The text to highlight and markup. Returns: The Text, with highlighting and markup applied.
def _markup_and_highlight(text: str) -> Text: """Highlight and render markup in a string of text, returning a styled Text object. Args: text: The text to highlight and markup. Returns: The Text, with highlighting and markup applied. """ return _highlighter(render(text))
Convert a CSS property name to the corresponding Python attribute name Args: property_name: The CSS property name Returns: The Python attribute name as found on the Styles object
def _python_name(property_name: str) -> str: """Convert a CSS property name to the corresponding Python attribute name Args: property_name: The CSS property name Returns: The Python attribute name as found on the Styles object """ return property_name.replace("-", "_")
Convert a Python style attribute name to the corresponding CSS property name Args: property_name: The Python property name Returns: The CSS property name
def _css_name(property_name: str) -> str: """Convert a Python style attribute name to the corresponding CSS property name Args: property_name: The Python property name Returns: The CSS property name """ return property_name.replace("_", "-")
Convert a property name to CSS or inline by replacing '-' with '_' or vice-versa Args: property_name: The name of the property context: The context the property is being used in. Returns: The property name converted to the given context.
def _contextualize_property_name( property_name: str, context: StylingContext, ) -> str: """Convert a property name to CSS or inline by replacing '-' with '_' or vice-versa Args: property_name: The name of the property context: The context the property is being used in. Returns: The property name converted to the given context. """ return _css_name(property_name) if context == "css" else _python_name(property_name)
Returns examples for spacing properties
def _spacing_examples(property_name: str) -> ContextSpecificBullets: """Returns examples for spacing properties""" return ContextSpecificBullets( inline=[ Bullet( f"Set [i]{property_name}[/] to a tuple to assign spacing to each edge", examples=[ Example( f"widget.styles.{property_name} = (1, 2) [dim]# Vertical, horizontal" ), Example( f"widget.styles.{property_name} = (1, 2, 3, 4) [dim]# Top, right, bottom, left" ), ], ), Bullet( "Or to an integer to assign a single value to all edges", examples=[Example(f"widget.styles.{property_name} = 2")], ), ], css=[ Bullet( "Supply 1, 2 or 4 integers separated by a space", examples=[ Example(f"{property_name}: 1;"), Example(f"{property_name}: 1 2; [dim]# Vertical, horizontal"), Example( f"{property_name}: 1 2 3 4; [dim]# Top, right, bottom, left" ), ], ), ], )
Help text to show when the user supplies an invalid value for CSS property property. Args: property_name: The name of the property. context: The context the spacing property is being used in. Keyword Args: suggested_property_name: A suggested name for the property (e.g. "width" for "wdth"). Returns: Renderable for displaying the help text for this property.
def property_invalid_value_help_text( property_name: str, context: StylingContext, *, suggested_property_name: str | None = None, ) -> HelpText: """Help text to show when the user supplies an invalid value for CSS property property. Args: property_name: The name of the property. context: The context the spacing property is being used in. Keyword Args: suggested_property_name: A suggested name for the property (e.g. "width" for "wdth"). Returns: Renderable for displaying the help text for this property. """ property_name = _contextualize_property_name(property_name, context) summary = f"Invalid CSS property {property_name!r}" if suggested_property_name: suggested_property_name = _contextualize_property_name( suggested_property_name, context ) summary += f". Did you mean '{suggested_property_name}'?" return HelpText(summary)
Help text to show when the user supplies the wrong number of values for a spacing property (e.g. padding or margin). Args: property_name: The name of the property. num_values_supplied: The number of values the user supplied (a number other than 1, 2 or 4). context: The context the spacing property is being used in. Returns: Renderable for displaying the help text for this property.
def spacing_wrong_number_of_values_help_text( property_name: str, num_values_supplied: int, context: StylingContext, ) -> HelpText: """Help text to show when the user supplies the wrong number of values for a spacing property (e.g. padding or margin). Args: property_name: The name of the property. num_values_supplied: The number of values the user supplied (a number other than 1, 2 or 4). context: The context the spacing property is being used in. Returns: Renderable for displaying the help text for this property. """ property_name = _contextualize_property_name(property_name, context) return HelpText( summary=f"Invalid number of values for the [i]{property_name}[/] property", bullets=[ Bullet( f"You supplied {num_values_supplied} values for the [i]{property_name}[/] property" ), Bullet( "Spacing properties like [i]margin[/] and [i]padding[/] require either 1, 2 or 4 integer values" ), *_spacing_examples(property_name).get_by_context(context), ], )
Help text to show when the user supplies an invalid value for a spacing property. Args: property_name: The name of the property. context: The context the spacing property is being used in. Returns: Renderable for displaying the help text for this property.
def spacing_invalid_value_help_text( property_name: str, context: StylingContext, ) -> HelpText: """Help text to show when the user supplies an invalid value for a spacing property. Args: property_name: The name of the property. context: The context the spacing property is being used in. Returns: Renderable for displaying the help text for this property. """ property_name = _contextualize_property_name(property_name, context) return HelpText( summary=f"Invalid value for the [i]{property_name}[/] property", bullets=_spacing_examples(property_name).get_by_context(context), )
Help text to show when the user supplies an invalid value for a scalar property. Args: property_name: The name of the property. num_values_supplied: The number of values the user supplied (a number other than 1, 2 or 4). context: The context the scalar property is being used in. Returns: Renderable for displaying the help text for this property.
def scalar_help_text( property_name: str, context: StylingContext, ) -> HelpText: """Help text to show when the user supplies an invalid value for a scalar property. Args: property_name: The name of the property. num_values_supplied: The number of values the user supplied (a number other than 1, 2 or 4). context: The context the scalar property is being used in. Returns: Renderable for displaying the help text for this property. """ property_name = _contextualize_property_name(property_name, context) return HelpText( summary=f"Invalid value for the [i]{property_name}[/] property", bullets=[ Bullet( f"Scalar properties like [i]{property_name}[/] require numerical values and an optional unit" ), Bullet(f"Valid units are {friendly_list(SYMBOL_UNIT)}"), *ContextSpecificBullets( inline=[ Bullet( "Assign a string, int or Scalar object itself", examples=[ Example(f'widget.styles.{property_name} = "50%"'), Example(f"widget.styles.{property_name} = 10"), Example(f"widget.styles.{property_name} = Scalar(...)"), ], ), ], css=[ Bullet( "Write the number followed by the unit", examples=[ Example(f"{property_name}: 50%;"), Example(f"{property_name}: 5;"), ], ), ], ).get_by_context(context), ], )
Help text to show when the user supplies an invalid value for a string enum property. Args: property_name: The name of the property. valid_values: A list of the values that are considered valid. context: The context the property is being used in. Returns: Renderable for displaying the help text for this property.
def string_enum_help_text( property_name: str, valid_values: Iterable[str], context: StylingContext, ) -> HelpText: """Help text to show when the user supplies an invalid value for a string enum property. Args: property_name: The name of the property. valid_values: A list of the values that are considered valid. context: The context the property is being used in. Returns: Renderable for displaying the help text for this property. """ property_name = _contextualize_property_name(property_name, context) return HelpText( summary=f"Invalid value for the [i]{property_name}[/] property", bullets=[ Bullet( f"The [i]{property_name}[/] property can only be set to {friendly_list(valid_values)}" ), *ContextSpecificBullets( inline=[ Bullet( "Assign any of the valid strings to the property", examples=[ Example(f'widget.styles.{property_name} = "{valid_value}"') for valid_value in sorted(valid_values) ], ) ], css=[ Bullet( "Assign any of the valid strings to the property", examples=[ Example(f"{property_name}: {valid_value};") for valid_value in sorted(valid_values) ], ) ], ).get_by_context(context), ], )
Help text to show when the user supplies an invalid value for a color property. For example, an unparseable color string. Args: property_name: The name of the property. context: The context the property is being used in. error: The error that caused this help text to be displayed. Returns: Renderable for displaying the help text for this property.
def color_property_help_text( property_name: str, context: StylingContext, *, error: Exception | None = None, ) -> HelpText: """Help text to show when the user supplies an invalid value for a color property. For example, an unparseable color string. Args: property_name: The name of the property. context: The context the property is being used in. error: The error that caused this help text to be displayed. Returns: Renderable for displaying the help text for this property. """ property_name = _contextualize_property_name(property_name, context) summary = f"Invalid value for the [i]{property_name}[/] property" suggested_color = ( error.suggested_color if error and isinstance(error, ColorParseError) else None ) if suggested_color: summary += f". Did you mean '{suggested_color}'?" return HelpText( summary=summary, bullets=[ Bullet( f"The [i]{property_name}[/] property can only be set to a valid color" ), Bullet("Colors can be specified using hex, RGB, or ANSI color names"), *ContextSpecificBullets( inline=[ Bullet( "Assign colors using strings or Color objects", examples=[ Example(f'widget.styles.{property_name} = "#ff00aa"'), Example( f'widget.styles.{property_name} = "rgb(12,231,45)"' ), Example(f'widget.styles.{property_name} = "red"'), Example( f"widget.styles.{property_name} = Color(1, 5, 29, a=0.5)" ), ], ) ], css=[ Bullet( "Colors can be set as follows", examples=[ Example(f"{property_name}: [#ff00aa]#ff00aa[/];"), Example(f"{property_name}: rgb(12,231,45);"), Example(f"{property_name}: [rgb(255,0,0)]red[/];"), ], ) ], ).get_by_context(context), ], )
Help text to show when the user supplies an invalid value for a border property (such as border, border-right, outline). Args: property_name: The name of the property. context: The context the property is being used in. Returns: Renderable for displaying the help text for this property.
def border_property_help_text(property_name: str, context: StylingContext) -> HelpText: """Help text to show when the user supplies an invalid value for a border property (such as border, border-right, outline). Args: property_name: The name of the property. context: The context the property is being used in. Returns: Renderable for displaying the help text for this property. """ property_name = _contextualize_property_name(property_name, context) return HelpText( summary=f"Invalid value for [i]{property_name}[/] property", bullets=[ *ContextSpecificBullets( inline=[ Bullet( f"Set [i]{property_name}[/] using a tuple of the form (<bordertype>, <color>)", examples=[ Example( f'widget.styles.{property_name} = ("solid", "red")' ), Example( f'widget.styles.{property_name} = ("round", "#f0f0f0")' ), Example( f'widget.styles.{property_name} = [("dashed", "#f0f0f0"), ("solid", "blue")] [dim]# Vertical, horizontal' ), ], ), Bullet( f"Valid values for <bordertype> are:\n{friendly_list(VALID_BORDER)}" ), Bullet( "Colors can be specified using hex, RGB, or ANSI color names" ), ], css=[ Bullet( f"Set [i]{property_name}[/] using a value of the form [i]<bordertype> <color>[/]", examples=[ Example(f"{property_name}: solid red;"), Example(f"{property_name}: dashed #00ee22;"), ], ), Bullet( f"Valid values for <bordertype> are:\n{friendly_list(VALID_BORDER)}" ), Bullet( "Colors can be specified using hex, RGB, or ANSI color names" ), ], ).get_by_context(context), ], )
Help text to show when the user supplies an invalid value for a layout property. Args: property_name: The name of the property. context: The context the property is being used in. Returns: Renderable for displaying the help text for this property.
def layout_property_help_text(property_name: str, context: StylingContext) -> HelpText: """Help text to show when the user supplies an invalid value for a layout property. Args: property_name: The name of the property. context: The context the property is being used in. Returns: Renderable for displaying the help text for this property. """ property_name = _contextualize_property_name(property_name, context) return HelpText( summary=f"Invalid value for [i]{property_name}[/] property", bullets=[ Bullet( f"The [i]{property_name}[/] property expects a value of {friendly_list(VALID_LAYOUT)}" ), ], )
Help text to show when the user supplies an invalid value for dock. Args: property_name: The name of the property. context: The context the property is being used in. Returns: Renderable for displaying the help text for this property.
def dock_property_help_text(property_name: str, context: StylingContext) -> HelpText: """Help text to show when the user supplies an invalid value for dock. Args: property_name: The name of the property. context: The context the property is being used in. Returns: Renderable for displaying the help text for this property. """ property_name = _contextualize_property_name(property_name, context) return HelpText( summary=f"Invalid value for [i]{property_name}[/] property", bullets=[ Bullet("The value must be one of 'top', 'right', 'bottom' or 'left'"), *ContextSpecificBullets( inline=[ Bullet( "The 'dock' rule aligns a widget relative to the screen.", examples=[Example('header.styles.dock = "top"')], ) ], css=[ Bullet( "The 'dock' rule aligns a widget relative to the screen.", examples=[Example("dock: top")], ) ], ).get_by_context(context), ], )
Help text to show when the user supplies an invalid value for a fractional property. Args: property_name: The name of the property. context: The context the property is being used in. Returns: Renderable for displaying the help text for this property.
def fractional_property_help_text( property_name: str, context: StylingContext ) -> HelpText: """Help text to show when the user supplies an invalid value for a fractional property. Args: property_name: The name of the property. context: The context the property is being used in. Returns: Renderable for displaying the help text for this property. """ property_name = _contextualize_property_name(property_name, context) return HelpText( summary=f"Invalid value for [i]{property_name}[/] property", bullets=[ *ContextSpecificBullets( inline=[ Bullet( f"Set [i]{property_name}[/] to a string or float value", examples=[ Example(f'widget.styles.{property_name} = "50%"'), Example(f"widget.styles.{property_name} = 0.25"), ], ) ], css=[ Bullet( f"Set [i]{property_name}[/] to a string or float", examples=[ Example(f"{property_name}: 50%;"), Example(f"{property_name}: 0.25;"), ], ) ], ).get_by_context(context) ], )
Help text to show when the user supplies an invalid value for the offset property. Args: context: The context the property is being used in. Returns: Renderable for displaying the help text for this property.
def offset_property_help_text(context: StylingContext) -> HelpText: """Help text to show when the user supplies an invalid value for the offset property. Args: context: The context the property is being used in. Returns: Renderable for displaying the help text for this property. """ return HelpText( summary="Invalid value for [i]offset[/] property", bullets=[ *ContextSpecificBullets( inline=[ Bullet( markup="The [i]offset[/] property expects a tuple of 2 values [i](<horizontal>, <vertical>)[/]", examples=[ Example("widget.styles.offset = (2, '50%')"), ], ), ], css=[ Bullet( markup="The [i]offset[/] property expects a value of the form [i]<horizontal> <vertical>[/]", examples=[ Example( "offset: 2 3; [dim]# Horizontal offset of 2, vertical offset of 3" ), Example( "offset: 2 50%; [dim]# Horizontal offset of 2, vertical offset of 50%" ), ], ), ], ).get_by_context(context), Bullet("<horizontal> and <vertical> can be a number or scalar value"), ], )
Help text to show when the user supplies an invalid value for the scrollbar-size property. Args: context: The context the property is being used in. Returns: Renderable for displaying the help text for this property.
def scrollbar_size_property_help_text(context: StylingContext) -> HelpText: """Help text to show when the user supplies an invalid value for the scrollbar-size property. Args: context: The context the property is being used in. Returns: Renderable for displaying the help text for this property. """ return HelpText( summary="Invalid value for [i]scrollbar-size[/] property", bullets=[ *ContextSpecificBullets( inline=[ Bullet( markup="The [i]scrollbar_size[/] property expects a tuple of 2 values [i](<horizontal>, <vertical>)[/]", examples=[ Example("widget.styles.scrollbar_size = (2, 1)"), ], ), ], css=[ Bullet( markup="The [i]scrollbar-size[/] property expects a value of the form [i]<horizontal> <vertical>[/]", examples=[ Example( "scrollbar-size: 2 3; [dim]# Horizontal size of 2, vertical size of 3" ), ], ), ], ).get_by_context(context), Bullet("<horizontal> and <vertical> must be non-negative integers."), ], )
Help text to show when the user supplies an invalid value for a scrollbar-size-* property. Args: property_name: The name of the property. Returns: Renderable for displaying the help text for this property.
def scrollbar_size_single_axis_help_text(property_name: str) -> HelpText: """Help text to show when the user supplies an invalid value for a scrollbar-size-* property. Args: property_name: The name of the property. Returns: Renderable for displaying the help text for this property. """ return HelpText( summary=f"Invalid value for [i]{property_name}[/]", bullets=[ Bullet( markup=f"The [i]{property_name}[/] property can only be set to a positive integer, greater than zero", examples=[ Example(f"{property_name}: 2;"), ], ), ], )
Help text to show when the user supplies an invalid integer value. Args: property_name: The name of the property. Returns: Renderable for displaying the help text for this property.
def integer_help_text(property_name: str) -> HelpText: """Help text to show when the user supplies an invalid integer value. Args: property_name: The name of the property. Returns: Renderable for displaying the help text for this property. """ return HelpText( summary=f"Invalid value for [i]{property_name}[/]", bullets=[ Bullet( markup="An integer value is expected here", examples=[ Example(f"{property_name}: 2;"), ], ), ], )
Help text to show when the user supplies an invalid value for a `align`. Returns: Renderable for displaying the help text for this property.
def align_help_text() -> HelpText: """Help text to show when the user supplies an invalid value for a `align`. Returns: Renderable for displaying the help text for this property. """ return HelpText( summary="Invalid value for [i]align[/] property", bullets=[ Bullet( markup="The [i]align[/] property expects exactly 2 values", examples=[ Example("align: <horizontal> <vertical>"), Example( "align: center middle; [dim]# Center vertically & horizontally within parent" ), Example( "align: left middle; [dim]# Align on the middle left of the parent" ), ], ), Bullet( f"Valid values for <horizontal> are {friendly_list(VALID_ALIGN_HORIZONTAL)}" ), Bullet( f"Valid values for <vertical> are {friendly_list(VALID_ALIGN_VERTICAL)}", ), ], )
Help text to show when the user supplies an invalid value for a `keyline`. Returns: Renderable for displaying the help text for this property.
def keyline_help_text() -> HelpText: """Help text to show when the user supplies an invalid value for a `keyline`. Returns: Renderable for displaying the help text for this property. """ return HelpText( summary="Invalid value for [i]keyline[/] property", bullets=[ Bullet( markup="The [i]keyline[/] property expects exactly 2 values", examples=[ Example("keyline: <type> <color>"), ], ), Bullet(f"Valid values for <type> are {friendly_list(VALID_KEYLINE)}"), ], )
Help text to show when the user supplies an invalid value for the text-align property. Returns: Renderable for displaying the help text for this property.
def text_align_help_text() -> HelpText: """Help text to show when the user supplies an invalid value for the text-align property. Returns: Renderable for displaying the help text for this property. """ return HelpText( summary="Invalid value for the [i]text-align[/] property.", bullets=[ Bullet( f"The [i]text-align[/] property must be one of {friendly_list(VALID_TEXT_ALIGN)}", examples=[ Example("text-align: center;"), Example("text-align: right;"), ], ) ], )
Help text to show when the user supplies an invalid value for an offset-* property. Args: property_name: The name of the property. Returns: Renderable for displaying the help text for this property.
def offset_single_axis_help_text(property_name: str) -> HelpText: """Help text to show when the user supplies an invalid value for an offset-* property. Args: property_name: The name of the property. Returns: Renderable for displaying the help text for this property. """ return HelpText( summary=f"Invalid value for [i]{property_name}[/]", bullets=[ Bullet( markup=f"The [i]{property_name}[/] property can be set to a number or scalar value", examples=[ Example(f"{property_name}: 10;"), Example(f"{property_name}: 50%;"), ], ), Bullet(f"Valid scalar units are {friendly_list(SYMBOL_UNIT)}"), ], )
Help text to show when the user supplies an invalid value for a style flags property. Args: property_name: The name of the property. context: The context the property is being used in. Returns: Renderable for displaying the help text for this property.
def style_flags_property_help_text( property_name: str, value: str, context: StylingContext ) -> HelpText: """Help text to show when the user supplies an invalid value for a style flags property. Args: property_name: The name of the property. context: The context the property is being used in. Returns: Renderable for displaying the help text for this property. """ property_name = _contextualize_property_name(property_name, context) return HelpText( summary=f"Invalid value '{value}' in [i]{property_name}[/] property", bullets=[ Bullet( f"Style flag values such as [i]{property_name}[/] expect space-separated values" ), Bullet(f"Permitted values are {friendly_list(VALID_STYLE_FLAGS)}"), Bullet("The value 'none' cannot be mixed with others"), *ContextSpecificBullets( inline=[ Bullet( markup="Supply a string or Style object", examples=[ Example( f'widget.styles.{property_name} = "bold italic underline"' ) ], ), ], css=[ Bullet( markup="Supply style flags separated by spaces", examples=[Example(f"{property_name}: bold italic underline;")], ) ], ).get_by_context(context), ], )
Encode the input text as utf-8 bytes. The returned encoded bytes may be retrieved from a cache. Args: text: The text to encode. Returns: The utf-8 bytes representing the input string.
def _utf8_encode(text: str) -> bytes: """Encode the input text as utf-8 bytes. The returned encoded bytes may be retrieved from a cache. Args: text: The text to encode. Returns: The utf-8 bytes representing the input string. """ return text.encode("utf-8")
Return the newline type used in this document. Args: text: The text to inspect. Returns: The Newline used in the file.
def _detect_newline_style(text: str) -> Newline: """Return the newline type used in this document. Args: text: The text to inspect. Returns: The Newline used in the file. """ if "\r\n" in text: # Windows newline return "\r\n" elif "\n" in text: # Unix/Linux/MacOS newline return "\n" elif "\r" in text: # Old MacOS newline return "\r" else: return "\n"