lca_index
int64
0
223
idx
stringlengths
7
11
line_type
stringclasses
6 values
ground_truth
stringlengths
2
35
completions
sequencelengths
3
1.16k
prefix
stringlengths
298
32.8k
postfix
stringlengths
0
28.6k
repo
stringclasses
34 values
54
54-150-37
infile
selected_index
[ "allow_fullscreen", "bind", "bindings", "box", "center", "chars", "contains", "copy", "debug", "depth", "execute_binding", "get_lines", "handle_key", "handle_mouse", "height", "id", "is_bindable", "is_selectable", "keys", "parent", "parent_align", "pop", "pos", "print", "remove", "select", "selectables", "selectables_length", "selected", "selected_index", "serialize", "serialized", "set_char", "set_recursive_depth", "set_style", "set_widgets", "sidelength", "size_policy", "static_width", "styles", "vertical_align", "width", "wipe", "_add_widget", "_apply_vertalign", "_bindings", "_box", "_centered_axis", "_drag_target", "_get_aligners", "_get_char", "_get_style", "_has_printed", "_id", "_id_manager", "_prev_screen", "_selectables_length", "_serialized_fields", "_update_width", "_widgets", "__add__", "__annotations__", "__class__", "__contains__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__getitem__", "__hash__", "__iadd__", "__init__", "__init_subclass__", "__iter__", "__len__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__setitem__", "__sizeof__", "__slots__", "__str__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.
][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-162-9
infile
setter
[ "deleter", "fdel", "fget", "fset", "getter", "setter", "__annotations__", "__class__", "__delattr__", "__delete__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__get__", "__getattribute__", "__hash__", "__init__", "__init_subclass__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__set__", "__setattr__", "__sizeof__", "__slots__", "__str__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.
def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-172-38
common
get
[ "clear", "copy", "fromkeys", "get", "items", "keys", "pop", "popitem", "setdefault", "update", "values", "__annotations__", "__class__", "__class_getitem__", "__contains__", "__delattr__", "__delitem__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__getitem__", "__hash__", "__init__", "__init_subclass__", "__ior__", "__iter__", "__len__", "__module__", "__ne__", "__new__", "__or__", "__reduce__", "__reduce_ex__", "__repr__", "__reversed__", "__setattr__", "__setitem__", "__sizeof__", "__slots__", "__str__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).
(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-193-13
infile
_add_widget
[ "allow_fullscreen", "bind", "bindings", "box", "center", "chars", "contains", "copy", "debug", "depth", "execute_binding", "get_lines", "handle_key", "handle_mouse", "height", "id", "is_bindable", "is_selectable", "keys", "parent", "parent_align", "pop", "pos", "print", "remove", "select", "selectables", "selectables_length", "selected", "selected_index", "serialize", "serialized", "set_char", "set_recursive_depth", "set_style", "set_widgets", "sidelength", "size_policy", "static_width", "styles", "vertical_align", "width", "wipe", "_add_widget", "_apply_vertalign", "_bindings", "_box", "_centered_axis", "_drag_target", "_get_aligners", "_get_char", "_get_style", "_has_printed", "_id", "_id_manager", "_prev_screen", "_selectables_length", "_serialized_fields", "_update_width", "_widgets", "__add__", "__annotations__", "__class__", "__contains__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__getitem__", "__hash__", "__iadd__", "__init__", "__init_subclass__", "__iter__", "__len__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__setitem__", "__sizeof__", "__slots__", "__str__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.
(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-209-13
infile
__iadd__
[ "allow_fullscreen", "bind", "bindings", "box", "center", "chars", "contains", "copy", "debug", "depth", "execute_binding", "get_lines", "handle_key", "handle_mouse", "height", "id", "is_bindable", "is_selectable", "keys", "parent", "parent_align", "pop", "pos", "print", "remove", "select", "selectables", "selectables_length", "selected", "selected_index", "serialize", "serialized", "set_char", "set_recursive_depth", "set_style", "set_widgets", "sidelength", "size_policy", "static_width", "styles", "vertical_align", "width", "wipe", "_add_widget", "_apply_vertalign", "_bindings", "_box", "_centered_axis", "_drag_target", "_get_aligners", "_get_char", "_get_style", "_has_printed", "_id", "_id_manager", "_prev_screen", "_selectables_length", "_serialized_fields", "_update_width", "_widgets", "__add__", "__annotations__", "__class__", "__contains__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__getitem__", "__hash__", "__iadd__", "__init__", "__init_subclass__", "__iter__", "__len__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__setitem__", "__sizeof__", "__slots__", "__str__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.
(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-251-13
common
_widgets
[ "allow_fullscreen", "bind", "bindings", "box", "center", "chars", "contains", "copy", "debug", "depth", "execute_binding", "get_lines", "handle_key", "handle_mouse", "height", "id", "is_bindable", "is_selectable", "keys", "parent", "parent_align", "pop", "pos", "print", "remove", "select", "selectables", "selectables_length", "selected", "selected_index", "serialize", "serialized", "set_char", "set_recursive_depth", "set_style", "set_widgets", "sidelength", "size_policy", "static_width", "styles", "vertical_align", "width", "wipe", "_add_widget", "_apply_vertalign", "_bindings", "_box", "_centered_axis", "_drag_target", "_get_aligners", "_get_char", "_get_style", "_has_printed", "_id", "_id_manager", "_prev_screen", "_selectables_length", "_serialized_fields", "_update_width", "_widgets", "__add__", "__annotations__", "__class__", "__contains__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__getitem__", "__hash__", "__iadd__", "__init__", "__init_subclass__", "__iter__", "__len__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__setitem__", "__sizeof__", "__slots__", "__str__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self.
[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-287-43
infile
depth
[ "allow_fullscreen", "bind", "bindings", "box", "center", "chars", "contains", "copy", "debug", "depth", "execute_binding", "get_lines", "handle_key", "handle_mouse", "height", "id", "is_bindable", "is_selectable", "keys", "parent", "parent_align", "pop", "pos", "print", "remove", "select", "selectables", "selectables_length", "selected", "selected_index", "serialize", "serialized", "set_char", "set_recursive_depth", "set_style", "set_widgets", "sidelength", "size_policy", "static_width", "styles", "vertical_align", "width", "wipe", "_add_widget", "_apply_vertalign", "_bindings", "_box", "_centered_axis", "_drag_target", "_get_aligners", "_get_char", "_get_style", "_has_printed", "_id", "_id_manager", "_prev_screen", "_selectables_length", "_serialized_fields", "_update_width", "_widgets", "__add__", "__annotations__", "__class__", "__contains__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__getitem__", "__hash__", "__iadd__", "__init__", "__init_subclass__", "__iter__", "__len__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__setitem__", "__sizeof__", "__slots__", "__str__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.
+ 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-295-17
infile
get_lines
[ "allow_fullscreen", "bind", "bindings", "box", "center", "chars", "contains", "copy", "debug", "depth", "execute_binding", "get_lines", "handle_key", "handle_mouse", "height", "id", "is_bindable", "is_selectable", "keys", "parent", "parent_align", "pop", "pos", "print", "remove", "select", "selectables", "selectables_length", "selected", "selected_index", "serialize", "serialized", "set_char", "set_recursive_depth", "set_style", "set_widgets", "sidelength", "size_policy", "static_width", "styles", "vertical_align", "width", "wipe", "_add_widget", "_apply_vertalign", "_bindings", "_box", "_centered_axis", "_drag_target", "_get_aligners", "_get_char", "_get_style", "_has_printed", "_id", "_id_manager", "_prev_screen", "_selectables_length", "_serialized_fields", "_update_width", "_widgets", "__add__", "__annotations__", "__class__", "__contains__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__getitem__", "__hash__", "__iadd__", "__init__", "__init_subclass__", "__iter__", "__len__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__setitem__", "__sizeof__", "__slots__", "__str__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.
() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-313-20
inproject
_get_style
[ "allow_fullscreen", "bind", "bindings", "box", "center", "chars", "contains", "copy", "debug", "depth", "execute_binding", "get_lines", "handle_key", "handle_mouse", "height", "id", "is_bindable", "is_selectable", "keys", "parent", "parent_align", "pop", "pos", "print", "remove", "select", "selectables", "selectables_length", "selected", "selected_index", "serialize", "serialized", "set_char", "set_recursive_depth", "set_style", "set_widgets", "sidelength", "size_policy", "static_width", "styles", "vertical_align", "width", "wipe", "_add_widget", "_apply_vertalign", "_bindings", "_box", "_centered_axis", "_drag_target", "_get_aligners", "_get_char", "_get_style", "_has_printed", "_id", "_id_manager", "_prev_screen", "_selectables_length", "_serialized_fields", "_update_width", "_widgets", "__add__", "__annotations__", "__class__", "__contains__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__getitem__", "__hash__", "__iadd__", "__init__", "__init_subclass__", "__iter__", "__len__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__setitem__", "__sizeof__", "__slots__", "__str__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self.
("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-318-27
inproject
width
[ "allow_fullscreen", "bind", "bindings", "box", "center", "chars", "contains", "copy", "debug", "depth", "execute_binding", "get_lines", "handle_key", "handle_mouse", "height", "id", "is_bindable", "is_selectable", "keys", "parent", "parent_align", "pop", "pos", "print", "remove", "select", "selectables", "selectables_length", "selected", "selected_index", "serialize", "serialized", "set_char", "set_recursive_depth", "set_style", "set_widgets", "sidelength", "size_policy", "static_width", "styles", "vertical_align", "width", "wipe", "_add_widget", "_apply_vertalign", "_bindings", "_box", "_centered_axis", "_drag_target", "_get_aligners", "_get_char", "_get_style", "_has_printed", "_id", "_id_manager", "_prev_screen", "_selectables_length", "_serialized_fields", "_update_width", "_widgets", "__add__", "__annotations__", "__class__", "__contains__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__getitem__", "__hash__", "__iadd__", "__init__", "__init_subclass__", "__iter__", "__len__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__setitem__", "__sizeof__", "__slots__", "__str__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.
- real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-324-25
inproject
width
[ "allow_fullscreen", "bind", "bindings", "box", "center", "chars", "contains", "copy", "debug", "depth", "execute_binding", "get_lines", "handle_key", "handle_mouse", "height", "id", "is_bindable", "is_selectable", "keys", "parent", "parent_align", "pop", "pos", "print", "remove", "select", "selectables", "selectables_length", "selected", "selected_index", "serialize", "serialized", "set_char", "set_recursive_depth", "set_style", "set_widgets", "sidelength", "size_policy", "static_width", "styles", "vertical_align", "width", "wipe", "_add_widget", "_apply_vertalign", "_bindings", "_box", "_centered_axis", "_drag_target", "_get_aligners", "_get_char", "_get_style", "_has_printed", "_id", "_id_manager", "_prev_screen", "_selectables_length", "_serialized_fields", "_update_width", "_widgets", "__add__", "__annotations__", "__class__", "__contains__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__getitem__", "__hash__", "__iadd__", "__init__", "__init_subclass__", "__iter__", "__len__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__setitem__", "__sizeof__", "__slots__", "__str__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.
- real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-334-18
inproject
parent_align
[ "bind", "bindings", "chars", "contains", "copy", "debug", "depth", "execute_binding", "get_lines", "handle_key", "handle_mouse", "height", "id", "is_bindable", "is_selectable", "keys", "parent", "parent_align", "pos", "print", "select", "selectables", "selectables_length", "selected_index", "serialize", "serialized", "set_char", "set_style", "size_policy", "static_width", "styles", "width", "_bindings", "_get_char", "_get_style", "_id", "_id_manager", "_selectables_length", "_serialized_fields", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init__", "__init_subclass__", "__iter__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__slots__", "__str__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.
== HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-334-54
inproject
CENTER
[ "as_integer_ratio", "bit_length", "CENTER", "conjugate", "denominator", "from_bytes", "get_default", "imag", "LEFT", "mro", "name", "numerator", "real", "RIGHT", "to_bytes", "value", "_generate_next_value_", "_ignore_", "_member_map_", "_member_names_", "_missing_", "_name_", "_order_", "_value2member_map_", "_value_", "__abs__", "__add__", "__and__", "__annotations__", "__base__", "__bases__", "__basicsize__", "__bool__", "__call__", "__ceil__", "__class__", "__delattr__", "__dict__", "__dictoffset__", "__dir__", "__divmod__", "__doc__", "__eq__", "__flags__", "__float__", "__floor__", "__floordiv__", "__format__", "__ge__", "__getattribute__", "__getnewargs__", "__gt__", "__hash__", "__index__", "__init__", "__init_subclass__", "__instancecheck__", "__int__", "__invert__", "__itemsize__", "__le__", "__lshift__", "__lt__", "__mod__", "__module__", "__mro__", "__mul__", "__name__", "__ne__", "__neg__", "__new__", "__or__", "__order__", "__pos__", "__pow__", "__prepare__", "__qualname__", "__radd__", "__rand__", "__rdivmod__", "__reduce__", "__reduce_ex__", "__repr__", "__rfloordiv__", "__rlshift__", "__rmod__", "__rmul__", "__ror__", "__round__", "__rpow__", "__rrshift__", "__rshift__", "__rsub__", "__rtruediv__", "__rxor__", "__setattr__", "__sizeof__", "__slots__", "__str__", "__sub__", "__subclasscheck__", "__subclasses__", "__text_signature__", "__truediv__", "__trunc__", "__weakrefoffset__", "__xor__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.
: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-339-18
inproject
parent_align
[ "bind", "bindings", "chars", "contains", "copy", "debug", "depth", "execute_binding", "get_lines", "handle_key", "handle_mouse", "height", "id", "is_bindable", "is_selectable", "keys", "parent", "parent_align", "pos", "print", "select", "selectables", "selectables_length", "selected_index", "serialize", "serialized", "set_char", "set_style", "size_policy", "static_width", "styles", "width", "_bindings", "_get_char", "_get_style", "_id", "_id_manager", "_selectables_length", "_serialized_fields", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init__", "__init_subclass__", "__iter__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__slots__", "__str__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.
== HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-339-54
inproject
RIGHT
[ "as_integer_ratio", "bit_length", "CENTER", "conjugate", "denominator", "from_bytes", "get_default", "imag", "LEFT", "mro", "name", "numerator", "real", "RIGHT", "to_bytes", "value", "_generate_next_value_", "_ignore_", "_member_map_", "_member_names_", "_missing_", "_name_", "_order_", "_value2member_map_", "_value_", "__abs__", "__add__", "__and__", "__annotations__", "__base__", "__bases__", "__basicsize__", "__bool__", "__call__", "__ceil__", "__class__", "__delattr__", "__dict__", "__dictoffset__", "__dir__", "__divmod__", "__doc__", "__eq__", "__flags__", "__float__", "__floor__", "__floordiv__", "__format__", "__ge__", "__getattribute__", "__getnewargs__", "__gt__", "__hash__", "__index__", "__init__", "__init_subclass__", "__instancecheck__", "__int__", "__invert__", "__itemsize__", "__le__", "__lshift__", "__lt__", "__mod__", "__module__", "__mro__", "__mul__", "__name__", "__ne__", "__neg__", "__new__", "__or__", "__order__", "__pos__", "__pow__", "__prepare__", "__qualname__", "__radd__", "__rand__", "__rdivmod__", "__reduce__", "__reduce_ex__", "__repr__", "__rfloordiv__", "__rlshift__", "__rmod__", "__rmul__", "__ror__", "__round__", "__rpow__", "__rrshift__", "__rshift__", "__rsub__", "__rtruediv__", "__rxor__", "__setattr__", "__sizeof__", "__slots__", "__str__", "__sub__", "__subclasscheck__", "__subclasses__", "__text_signature__", "__truediv__", "__trunc__", "__weakrefoffset__", "__xor__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.
: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-358-18
inproject
size_policy
[ "bind", "bindings", "chars", "contains", "copy", "debug", "depth", "execute_binding", "get_lines", "handle_key", "handle_mouse", "height", "id", "is_bindable", "is_selectable", "keys", "parent", "parent_align", "pos", "print", "select", "selectables", "selectables_length", "selected_index", "serialize", "serialized", "set_char", "set_style", "size_policy", "static_width", "styles", "width", "_bindings", "_get_char", "_get_style", "_id", "_id_manager", "_selectables_length", "_serialized_fields", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init__", "__init_subclass__", "__iter__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__slots__", "__str__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.
== SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-358-44
inproject
FILL
[ "as_integer_ratio", "bit_length", "conjugate", "denominator", "FILL", "from_bytes", "get_default", "imag", "mro", "name", "numerator", "real", "RELATIVE", "STATIC", "to_bytes", "value", "_generate_next_value_", "_ignore_", "_member_map_", "_member_names_", "_missing_", "_name_", "_order_", "_value2member_map_", "_value_", "__abs__", "__add__", "__and__", "__annotations__", "__base__", "__bases__", "__basicsize__", "__bool__", "__call__", "__ceil__", "__class__", "__delattr__", "__dict__", "__dictoffset__", "__dir__", "__divmod__", "__doc__", "__eq__", "__flags__", "__float__", "__floor__", "__floordiv__", "__format__", "__ge__", "__getattribute__", "__getnewargs__", "__gt__", "__hash__", "__index__", "__init__", "__init_subclass__", "__instancecheck__", "__int__", "__invert__", "__itemsize__", "__le__", "__lshift__", "__lt__", "__mod__", "__module__", "__mro__", "__mul__", "__name__", "__ne__", "__neg__", "__new__", "__or__", "__order__", "__pos__", "__pow__", "__prepare__", "__qualname__", "__radd__", "__rand__", "__rdivmod__", "__reduce__", "__reduce_ex__", "__repr__", "__rfloordiv__", "__rlshift__", "__rmod__", "__rmul__", "__ror__", "__round__", "__rpow__", "__rrshift__", "__rshift__", "__rsub__", "__rtruediv__", "__rxor__", "__setattr__", "__sizeof__", "__slots__", "__str__", "__sub__", "__subclasscheck__", "__subclasses__", "__text_signature__", "__truediv__", "__trunc__", "__weakrefoffset__", "__xor__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.
: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-359-19
inproject
width
[ "bind", "bindings", "chars", "contains", "copy", "debug", "depth", "execute_binding", "get_lines", "handle_key", "handle_mouse", "height", "id", "is_bindable", "is_selectable", "keys", "parent", "parent_align", "pos", "print", "select", "selectables", "selectables_length", "selected_index", "serialize", "serialized", "set_char", "set_style", "size_policy", "static_width", "styles", "width", "_bindings", "_get_char", "_get_style", "_id", "_id_manager", "_selectables_length", "_serialized_fields", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init__", "__init_subclass__", "__iter__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__slots__", "__str__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.
= available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-367-22
inproject
size_policy
[ "bind", "bindings", "chars", "contains", "copy", "debug", "depth", "execute_binding", "get_lines", "handle_key", "handle_mouse", "height", "id", "is_bindable", "is_selectable", "keys", "parent", "parent_align", "pos", "print", "select", "selectables", "selectables_length", "selected_index", "serialize", "serialized", "set_char", "set_style", "size_policy", "static_width", "styles", "width", "_bindings", "_get_char", "_get_style", "_id", "_id_manager", "_selectables_length", "_serialized_fields", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init__", "__init_subclass__", "__iter__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__slots__", "__str__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.
== SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-367-48
inproject
STATIC
[ "as_integer_ratio", "bit_length", "conjugate", "denominator", "FILL", "from_bytes", "get_default", "imag", "mro", "name", "numerator", "real", "RELATIVE", "STATIC", "to_bytes", "value", "_generate_next_value_", "_ignore_", "_member_map_", "_member_names_", "_missing_", "_name_", "_order_", "_value2member_map_", "_value_", "__abs__", "__add__", "__and__", "__annotations__", "__base__", "__bases__", "__basicsize__", "__bool__", "__call__", "__ceil__", "__class__", "__delattr__", "__dict__", "__dictoffset__", "__dir__", "__divmod__", "__doc__", "__eq__", "__flags__", "__float__", "__floor__", "__floordiv__", "__format__", "__ge__", "__getattribute__", "__getnewargs__", "__gt__", "__hash__", "__index__", "__init__", "__init_subclass__", "__instancecheck__", "__int__", "__invert__", "__itemsize__", "__le__", "__lshift__", "__lt__", "__mod__", "__module__", "__mro__", "__mul__", "__name__", "__ne__", "__neg__", "__new__", "__or__", "__order__", "__pos__", "__pow__", "__prepare__", "__qualname__", "__radd__", "__rand__", "__rdivmod__", "__reduce__", "__reduce_ex__", "__repr__", "__rfloordiv__", "__rlshift__", "__rmod__", "__rmul__", "__ror__", "__round__", "__rpow__", "__rrshift__", "__rshift__", "__rsub__", "__rtruediv__", "__rxor__", "__setattr__", "__sizeof__", "__slots__", "__str__", "__sub__", "__subclasscheck__", "__subclasses__", "__text_signature__", "__truediv__", "__trunc__", "__weakrefoffset__", "__xor__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.
: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-393-16
inproject
vertical_align
[ "allow_fullscreen", "bind", "bindings", "box", "center", "chars", "contains", "copy", "debug", "depth", "execute_binding", "get_lines", "handle_key", "handle_mouse", "height", "id", "is_bindable", "is_selectable", "keys", "parent", "parent_align", "pop", "pos", "print", "remove", "select", "selectables", "selectables_length", "selected", "selected_index", "serialize", "serialized", "set_char", "set_recursive_depth", "set_style", "set_widgets", "sidelength", "size_policy", "static_width", "styles", "vertical_align", "width", "wipe", "_add_widget", "_apply_vertalign", "_bindings", "_box", "_centered_axis", "_drag_target", "_get_aligners", "_get_char", "_get_style", "_has_printed", "_id", "_id_manager", "_prev_screen", "_selectables_length", "_serialized_fields", "_update_width", "_widgets", "__add__", "__annotations__", "__class__", "__contains__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__getitem__", "__hash__", "__iadd__", "__init__", "__init_subclass__", "__iter__", "__len__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__setitem__", "__sizeof__", "__slots__", "__str__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.
== VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-393-52
inproject
BOTTOM
[ "as_integer_ratio", "bit_length", "BOTTOM", "CENTER", "conjugate", "denominator", "from_bytes", "get_default", "imag", "mro", "name", "numerator", "real", "to_bytes", "TOP", "value", "_generate_next_value_", "_ignore_", "_member_map_", "_member_names_", "_missing_", "_name_", "_order_", "_value2member_map_", "_value_", "__abs__", "__add__", "__and__", "__annotations__", "__base__", "__bases__", "__basicsize__", "__bool__", "__call__", "__ceil__", "__class__", "__delattr__", "__dict__", "__dictoffset__", "__dir__", "__divmod__", "__doc__", "__eq__", "__flags__", "__float__", "__floor__", "__floordiv__", "__format__", "__ge__", "__getattribute__", "__getnewargs__", "__gt__", "__hash__", "__index__", "__init__", "__init_subclass__", "__instancecheck__", "__int__", "__invert__", "__itemsize__", "__le__", "__lshift__", "__lt__", "__mod__", "__module__", "__mro__", "__mul__", "__name__", "__ne__", "__neg__", "__new__", "__or__", "__order__", "__pos__", "__pow__", "__prepare__", "__qualname__", "__radd__", "__rand__", "__rdivmod__", "__reduce__", "__reduce_ex__", "__repr__", "__rfloordiv__", "__rlshift__", "__rmod__", "__rmul__", "__ror__", "__round__", "__rpow__", "__rrshift__", "__rshift__", "__rsub__", "__rtruediv__", "__rxor__", "__setattr__", "__sizeof__", "__slots__", "__str__", "__sub__", "__subclasscheck__", "__subclasses__", "__text_signature__", "__truediv__", "__trunc__", "__weakrefoffset__", "__xor__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.
: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-448-21
inproject
_get_style
[ "allow_fullscreen", "bind", "bindings", "box", "center", "chars", "contains", "copy", "debug", "depth", "execute_binding", "get_lines", "handle_key", "handle_mouse", "height", "id", "is_bindable", "is_selectable", "keys", "parent", "parent_align", "pop", "pos", "print", "remove", "select", "selectables", "selectables_length", "selected", "selected_index", "serialize", "serialized", "set_char", "set_recursive_depth", "set_style", "set_widgets", "sidelength", "size_policy", "static_width", "styles", "vertical_align", "width", "wipe", "_add_widget", "_apply_vertalign", "_bindings", "_box", "_centered_axis", "_drag_target", "_get_aligners", "_get_char", "_get_style", "_has_printed", "_id", "_id_manager", "_prev_screen", "_selectables_length", "_serialized_fields", "_update_width", "_widgets", "__add__", "__annotations__", "__class__", "__contains__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__getitem__", "__hash__", "__iadd__", "__init__", "__init_subclass__", "__iter__", "__len__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__setitem__", "__sizeof__", "__slots__", "__str__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self.
("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-461-17
infile
_update_width
[ "allow_fullscreen", "bind", "bindings", "box", "center", "chars", "contains", "copy", "debug", "depth", "execute_binding", "get_lines", "handle_key", "handle_mouse", "height", "id", "is_bindable", "is_selectable", "keys", "parent", "parent_align", "pop", "pos", "print", "remove", "select", "selectables", "selectables_length", "selected", "selected_index", "serialize", "serialized", "set_char", "set_recursive_depth", "set_style", "set_widgets", "sidelength", "size_policy", "static_width", "styles", "vertical_align", "width", "wipe", "_add_widget", "_apply_vertalign", "_bindings", "_box", "_centered_axis", "_drag_target", "_get_aligners", "_get_char", "_get_style", "_has_printed", "_id", "_id_manager", "_prev_screen", "_selectables_length", "_serialized_fields", "_update_width", "_widgets", "__add__", "__annotations__", "__class__", "__contains__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__getitem__", "__hash__", "__iadd__", "__init__", "__init_subclass__", "__iter__", "__len__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__setitem__", "__sizeof__", "__slots__", "__str__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self.
(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-482-19
infile
get_lines
[ "bind", "bindings", "chars", "contains", "copy", "debug", "depth", "execute_binding", "get_lines", "handle_key", "handle_mouse", "height", "id", "is_bindable", "is_selectable", "keys", "parent", "parent_align", "pos", "print", "select", "selectables", "selectables_length", "selected_index", "serialize", "serialized", "set_char", "set_style", "size_policy", "static_width", "styles", "width", "_bindings", "_get_char", "_get_style", "_id", "_id_manager", "_selectables_length", "_serialized_fields", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init__", "__init_subclass__", "__iter__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__slots__", "__str__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.
() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-490-13
inproject
height
[ "allow_fullscreen", "bind", "bindings", "box", "center", "chars", "contains", "copy", "debug", "depth", "execute_binding", "get_lines", "handle_key", "handle_mouse", "height", "id", "is_bindable", "is_selectable", "keys", "parent", "parent_align", "pop", "pos", "print", "remove", "select", "selectables", "selectables_length", "selected", "selected_index", "serialize", "serialized", "set_char", "set_recursive_depth", "set_style", "set_widgets", "sidelength", "size_policy", "static_width", "styles", "vertical_align", "width", "wipe", "_add_widget", "_apply_vertalign", "_bindings", "_box", "_centered_axis", "_drag_target", "_get_aligners", "_get_char", "_get_style", "_has_printed", "_id", "_id_manager", "_prev_screen", "_selectables_length", "_serialized_fields", "_update_width", "_widgets", "__add__", "__annotations__", "__class__", "__contains__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__getitem__", "__hash__", "__iadd__", "__init__", "__init_subclass__", "__iter__", "__len__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__setitem__", "__sizeof__", "__slots__", "__str__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.
= len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-502-17
infile
_add_widget
[ "allow_fullscreen", "bind", "bindings", "box", "center", "chars", "contains", "copy", "debug", "depth", "execute_binding", "get_lines", "handle_key", "handle_mouse", "height", "id", "is_bindable", "is_selectable", "keys", "parent", "parent_align", "pop", "pos", "print", "remove", "select", "selectables", "selectables_length", "selected", "selected_index", "serialize", "serialized", "set_char", "set_recursive_depth", "set_style", "set_widgets", "sidelength", "size_policy", "static_width", "styles", "vertical_align", "width", "wipe", "_add_widget", "_apply_vertalign", "_bindings", "_box", "_centered_axis", "_drag_target", "_get_aligners", "_get_char", "_get_style", "_has_printed", "_id", "_id_manager", "_prev_screen", "_selectables_length", "_serialized_fields", "_update_width", "_widgets", "__add__", "__annotations__", "__class__", "__contains__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__getitem__", "__hash__", "__iadd__", "__init__", "__init_subclass__", "__iter__", "__len__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__setitem__", "__sizeof__", "__slots__", "__str__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self.
(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-516-27
random
_widgets
[ "allow_fullscreen", "bind", "bindings", "box", "center", "chars", "contains", "copy", "debug", "depth", "execute_binding", "get_lines", "handle_key", "handle_mouse", "height", "id", "is_bindable", "is_selectable", "keys", "parent", "parent_align", "pop", "pos", "print", "remove", "select", "selectables", "selectables_length", "selected", "selected_index", "serialize", "serialized", "set_char", "set_recursive_depth", "set_style", "set_widgets", "sidelength", "size_policy", "static_width", "styles", "vertical_align", "width", "wipe", "_add_widget", "_apply_vertalign", "_bindings", "_box", "_centered_axis", "_drag_target", "_get_aligners", "_get_char", "_get_style", "_has_printed", "_id", "_id_manager", "_prev_screen", "_selectables_length", "_serialized_fields", "_update_width", "_widgets", "__add__", "__annotations__", "__class__", "__contains__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__getitem__", "__hash__", "__iadd__", "__init__", "__init_subclass__", "__iter__", "__len__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__setitem__", "__sizeof__", "__slots__", "__str__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self.
: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-517-28
infile
append
[ "append", "clear", "copy", "count", "extend", "index", "insert", "pop", "remove", "reverse", "sort", "__add__", "__annotations__", "__class__", "__class_getitem__", "__contains__", "__delattr__", "__delitem__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__ge__", "__getattribute__", "__getitem__", "__gt__", "__hash__", "__iadd__", "__imul__", "__init__", "__init_subclass__", "__iter__", "__le__", "__len__", "__lt__", "__module__", "__mul__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__reversed__", "__rmul__", "__setattr__", "__setitem__", "__sizeof__", "__slots__", "__str__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].
(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-517-42
infile
serialize
[ "bind", "bindings", "chars", "contains", "copy", "debug", "depth", "execute_binding", "get_lines", "handle_key", "handle_mouse", "height", "id", "is_bindable", "is_selectable", "keys", "parent", "parent_align", "pos", "print", "select", "selectables", "selectables_length", "selected_index", "serialize", "serialized", "set_char", "set_style", "size_policy", "static_width", "styles", "width", "_bindings", "_get_char", "_get_style", "_id", "_id_manager", "_selectables_length", "_serialized_fields", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init__", "__init_subclass__", "__iter__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__slots__", "__str__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.
()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-533-20
infile
_widgets
[ "allow_fullscreen", "bind", "bindings", "box", "center", "chars", "contains", "copy", "debug", "depth", "execute_binding", "get_lines", "handle_key", "handle_mouse", "height", "id", "is_bindable", "is_selectable", "keys", "parent", "parent_align", "pop", "pos", "print", "remove", "select", "selectables", "selectables_length", "selected", "selected_index", "serialize", "serialized", "set_char", "set_recursive_depth", "set_style", "set_widgets", "sidelength", "size_policy", "static_width", "styles", "vertical_align", "width", "wipe", "_add_widget", "_apply_vertalign", "_bindings", "_box", "_centered_axis", "_drag_target", "_get_aligners", "_get_char", "_get_style", "_has_printed", "_id", "_id_manager", "_prev_screen", "_selectables_length", "_serialized_fields", "_update_width", "_widgets", "__add__", "__annotations__", "__class__", "__contains__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__getitem__", "__hash__", "__iadd__", "__init__", "__init_subclass__", "__iter__", "__len__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__setitem__", "__sizeof__", "__slots__", "__str__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self.
.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-533-29
infile
pop
[ "append", "clear", "copy", "count", "extend", "index", "insert", "pop", "remove", "reverse", "sort", "__add__", "__annotations__", "__class__", "__class_getitem__", "__contains__", "__delattr__", "__delitem__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__ge__", "__getattribute__", "__getitem__", "__gt__", "__hash__", "__iadd__", "__imul__", "__init__", "__init_subclass__", "__iter__", "__le__", "__len__", "__lt__", "__module__", "__mul__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__reversed__", "__rmul__", "__setattr__", "__setitem__", "__sizeof__", "__slots__", "__str__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.
(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-544-20
infile
_widgets
[ "allow_fullscreen", "bind", "bindings", "box", "center", "chars", "contains", "copy", "debug", "depth", "execute_binding", "get_lines", "handle_key", "handle_mouse", "height", "id", "is_bindable", "is_selectable", "keys", "parent", "parent_align", "pop", "pos", "print", "remove", "select", "selectables", "selectables_length", "selected", "selected_index", "serialize", "serialized", "set_char", "set_recursive_depth", "set_style", "set_widgets", "sidelength", "size_policy", "static_width", "styles", "vertical_align", "width", "wipe", "_add_widget", "_apply_vertalign", "_bindings", "_box", "_centered_axis", "_drag_target", "_get_aligners", "_get_char", "_get_style", "_has_printed", "_id", "_id_manager", "_prev_screen", "_selectables_length", "_serialized_fields", "_update_width", "_widgets", "__add__", "__annotations__", "__class__", "__contains__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__getitem__", "__hash__", "__iadd__", "__init__", "__init_subclass__", "__iter__", "__len__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__setitem__", "__sizeof__", "__slots__", "__str__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self.
.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-544-29
infile
remove
[ "append", "clear", "copy", "count", "extend", "index", "insert", "pop", "remove", "reverse", "sort", "__add__", "__annotations__", "__class__", "__class_getitem__", "__contains__", "__delattr__", "__delitem__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__ge__", "__getattribute__", "__getitem__", "__gt__", "__hash__", "__iadd__", "__imul__", "__init__", "__init_subclass__", "__iter__", "__le__", "__len__", "__lt__", "__module__", "__mul__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__reversed__", "__rmul__", "__setattr__", "__setitem__", "__sizeof__", "__slots__", "__str__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.
(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-574-21
infile
selectables_length
[ "bind", "bindings", "chars", "contains", "copy", "debug", "depth", "execute_binding", "get_lines", "handle_key", "handle_mouse", "height", "id", "is_bindable", "is_selectable", "keys", "parent", "parent_align", "pos", "print", "select", "selectables", "selectables_length", "selected_index", "serialize", "serialized", "set_char", "set_style", "size_policy", "static_width", "styles", "width", "_bindings", "_get_char", "_get_style", "_id", "_id_manager", "_selectables_length", "_serialized_fields", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init__", "__init_subclass__", "__iter__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__slots__", "__str__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.
> 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-575-22
infile
select
[ "bind", "bindings", "chars", "contains", "copy", "debug", "depth", "execute_binding", "get_lines", "handle_key", "handle_mouse", "height", "id", "is_bindable", "is_selectable", "keys", "parent", "parent_align", "pos", "print", "select", "selectables", "selectables_length", "selected_index", "serialize", "serialized", "set_char", "set_style", "size_policy", "static_width", "styles", "width", "_bindings", "_get_char", "_get_style", "_id", "_id_manager", "_selectables_length", "_serialized_fields", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init__", "__init_subclass__", "__iter__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__slots__", "__str__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.
(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-578-33
infile
selectables
[ "allow_fullscreen", "bind", "bindings", "box", "center", "chars", "contains", "copy", "debug", "depth", "execute_binding", "get_lines", "handle_key", "handle_mouse", "height", "id", "is_bindable", "is_selectable", "keys", "parent", "parent_align", "pop", "pos", "print", "remove", "select", "selectables", "selectables_length", "selected", "selected_index", "serialize", "serialized", "set_char", "set_recursive_depth", "set_style", "set_widgets", "sidelength", "size_policy", "static_width", "styles", "vertical_align", "width", "wipe", "_add_widget", "_apply_vertalign", "_bindings", "_box", "_centered_axis", "_drag_target", "_get_aligners", "_get_char", "_get_style", "_has_printed", "_id", "_id_manager", "_prev_screen", "_selectables_length", "_serialized_fields", "_update_width", "_widgets", "__add__", "__annotations__", "__class__", "__contains__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__getitem__", "__hash__", "__iadd__", "__init__", "__init_subclass__", "__iter__", "__len__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__setitem__", "__sizeof__", "__slots__", "__str__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.
) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-581-39
infile
selectables
[ "allow_fullscreen", "bind", "bindings", "box", "center", "chars", "contains", "copy", "debug", "depth", "execute_binding", "get_lines", "handle_key", "handle_mouse", "height", "id", "is_bindable", "is_selectable", "keys", "parent", "parent_align", "pop", "pos", "print", "remove", "select", "selectables", "selectables_length", "selected", "selected_index", "serialize", "serialized", "set_char", "set_recursive_depth", "set_style", "set_widgets", "sidelength", "size_policy", "static_width", "styles", "vertical_align", "width", "wipe", "_add_widget", "_apply_vertalign", "_bindings", "_box", "_centered_axis", "_drag_target", "_get_aligners", "_get_char", "_get_style", "_has_printed", "_id", "_id_manager", "_prev_screen", "_selectables_length", "_serialized_fields", "_update_width", "_widgets", "__add__", "__annotations__", "__class__", "__contains__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__getitem__", "__hash__", "__iadd__", "__init__", "__init_subclass__", "__iter__", "__len__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__setitem__", "__sizeof__", "__slots__", "__str__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.
[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-582-19
infile
select
[ "bind", "bindings", "chars", "contains", "copy", "debug", "depth", "execute_binding", "get_lines", "handle_key", "handle_mouse", "height", "id", "is_bindable", "is_selectable", "keys", "parent", "parent_align", "pos", "print", "select", "selectables", "selectables_length", "selected_index", "serialize", "serialized", "set_char", "set_style", "size_policy", "static_width", "styles", "width", "_bindings", "_get_char", "_get_style", "_id", "_id_manager", "_selectables_length", "_serialized_fields", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init__", "__init_subclass__", "__iter__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__slots__", "__str__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.
(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-584-13
common
selected_index
[ "allow_fullscreen", "bind", "bindings", "box", "center", "chars", "contains", "copy", "debug", "depth", "execute_binding", "get_lines", "handle_key", "handle_mouse", "height", "id", "is_bindable", "is_selectable", "keys", "parent", "parent_align", "pop", "pos", "print", "remove", "select", "selectables", "selectables_length", "selected", "selected_index", "serialize", "serialized", "set_char", "set_recursive_depth", "set_style", "set_widgets", "sidelength", "size_policy", "static_width", "styles", "vertical_align", "width", "wipe", "_add_widget", "_apply_vertalign", "_bindings", "_box", "_centered_axis", "_drag_target", "_get_aligners", "_get_char", "_get_style", "_has_printed", "_id", "_id_manager", "_prev_screen", "_selectables_length", "_serialized_fields", "_update_width", "_widgets", "__add__", "__annotations__", "__class__", "__contains__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__getitem__", "__hash__", "__iadd__", "__init__", "__init_subclass__", "__iter__", "__len__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__setitem__", "__sizeof__", "__slots__", "__str__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.
= index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-607-53
inproject
ALL
[ "ALL", "as_integer_ratio", "bit_length", "conjugate", "denominator", "from_bytes", "get_default", "HORIZONTAL", "imag", "mro", "name", "numerator", "real", "to_bytes", "value", "VERTICAL", "_generate_next_value_", "_ignore_", "_member_map_", "_member_names_", "_missing_", "_name_", "_order_", "_value2member_map_", "_value_", "__abs__", "__add__", "__and__", "__annotations__", "__base__", "__bases__", "__basicsize__", "__bool__", "__call__", "__ceil__", "__class__", "__delattr__", "__dict__", "__dictoffset__", "__dir__", "__divmod__", "__doc__", "__eq__", "__flags__", "__float__", "__floor__", "__floordiv__", "__format__", "__ge__", "__getattribute__", "__getnewargs__", "__gt__", "__hash__", "__index__", "__init__", "__init_subclass__", "__instancecheck__", "__int__", "__invert__", "__itemsize__", "__le__", "__lshift__", "__lt__", "__mod__", "__module__", "__mro__", "__mul__", "__name__", "__ne__", "__neg__", "__new__", "__or__", "__order__", "__pos__", "__pow__", "__prepare__", "__qualname__", "__radd__", "__rand__", "__rdivmod__", "__reduce__", "__reduce_ex__", "__repr__", "__rfloordiv__", "__rlshift__", "__rmod__", "__rmul__", "__ror__", "__round__", "__rpow__", "__rrshift__", "__rshift__", "__rsub__", "__rtruediv__", "__rxor__", "__setattr__", "__sizeof__", "__slots__", "__str__", "__sub__", "__subclasscheck__", "__subclasses__", "__text_signature__", "__truediv__", "__trunc__", "__weakrefoffset__", "__xor__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.
centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-609-44
inproject
VERTICAL
[ "ALL", "as_integer_ratio", "bit_length", "conjugate", "denominator", "from_bytes", "get_default", "HORIZONTAL", "imag", "mro", "name", "numerator", "real", "to_bytes", "value", "VERTICAL", "_generate_next_value_", "_ignore_", "_member_map_", "_member_names_", "_missing_", "_name_", "_order_", "_value2member_map_", "_value_", "__abs__", "__add__", "__and__", "__annotations__", "__base__", "__bases__", "__basicsize__", "__bool__", "__call__", "__ceil__", "__class__", "__delattr__", "__dict__", "__dictoffset__", "__dir__", "__divmod__", "__doc__", "__eq__", "__flags__", "__float__", "__floor__", "__floordiv__", "__format__", "__ge__", "__getattribute__", "__getnewargs__", "__gt__", "__hash__", "__index__", "__init__", "__init_subclass__", "__instancecheck__", "__int__", "__invert__", "__itemsize__", "__le__", "__lshift__", "__lt__", "__mod__", "__module__", "__mro__", "__mul__", "__name__", "__ne__", "__neg__", "__new__", "__or__", "__order__", "__pos__", "__pow__", "__prepare__", "__qualname__", "__radd__", "__rand__", "__rdivmod__", "__reduce__", "__reduce_ex__", "__repr__", "__rfloordiv__", "__rlshift__", "__rmod__", "__rmul__", "__ror__", "__round__", "__rpow__", "__rrshift__", "__rshift__", "__rsub__", "__rtruediv__", "__rxor__", "__setattr__", "__sizeof__", "__slots__", "__str__", "__sub__", "__subclasscheck__", "__subclasses__", "__text_signature__", "__truediv__", "__trunc__", "__weakrefoffset__", "__xor__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.
pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-637-17
inproject
action
[ "action", "position", "_iter_index", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init__", "__init_subclass__", "__iter__", "__module__", "__ne__", "__new__", "__next__", "__post_init__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__slots__", "__str__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.
is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-637-39
inproject
RELEASE
[ "HOVER", "LEFT_CLICK", "LEFT_DRAG", "mro", "name", "RELEASE", "RIGHT_CLICK", "RIGHT_DRAG", "SCROLL_DOWN", "SCROLL_UP", "value", "_generate_next_value_", "_ignore_", "_member_map_", "_member_names_", "_missing_", "_name_", "_order_", "_value2member_map_", "_value_", "__annotations__", "__base__", "__bases__", "__basicsize__", "__call__", "__class__", "__delattr__", "__dict__", "__dictoffset__", "__dir__", "__doc__", "__eq__", "__flags__", "__format__", "__getattribute__", "__hash__", "__init__", "__init_subclass__", "__instancecheck__", "__itemsize__", "__module__", "__mro__", "__name__", "__ne__", "__new__", "__order__", "__prepare__", "__qualname__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__slots__", "__str__", "__subclasscheck__", "__subclasses__", "__text_signature__", "__weakrefoffset__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.
: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-640-21
infile
_drag_target
[ "allow_fullscreen", "bind", "bindings", "box", "center", "chars", "contains", "copy", "debug", "depth", "execute_binding", "get_lines", "handle_key", "handle_mouse", "height", "id", "is_bindable", "is_selectable", "keys", "parent", "parent_align", "pop", "pos", "print", "remove", "select", "selectables", "selectables_length", "selected", "selected_index", "serialize", "serialized", "set_char", "set_recursive_depth", "set_style", "set_widgets", "sidelength", "size_policy", "static_width", "styles", "vertical_align", "width", "wipe", "_add_widget", "_apply_vertalign", "_bindings", "_box", "_centered_axis", "_drag_target", "_get_aligners", "_get_char", "_get_style", "_has_printed", "_id", "_id_manager", "_prev_screen", "_selectables_length", "_serialized_fields", "_update_width", "_widgets", "__add__", "__annotations__", "__class__", "__contains__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__getitem__", "__hash__", "__iadd__", "__init__", "__init_subclass__", "__iter__", "__len__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__setitem__", "__sizeof__", "__slots__", "__str__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self.
.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-640-34
infile
handle_mouse
[ "bind", "bindings", "chars", "contains", "copy", "debug", "depth", "execute_binding", "get_lines", "handle_key", "handle_mouse", "height", "id", "is_bindable", "is_selectable", "keys", "parent", "parent_align", "pos", "print", "select", "selectables", "selectables_length", "selected_index", "serialize", "serialized", "set_char", "set_style", "size_policy", "static_width", "styles", "width", "_bindings", "_get_char", "_get_style", "_id", "_id_manager", "_selectables_length", "_serialized_fields", "__annotations__", "__bool__", "__class__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__ge__", "__getattribute__", "__gt__", "__hash__", "__init__", "__init_subclass__", "__iter__", "__le__", "__lt__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__slots__", "__str__", "__subclasshook__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.
( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-641-43
inproject
RELEASE
[ "HOVER", "LEFT_CLICK", "LEFT_DRAG", "mro", "name", "RELEASE", "RIGHT_CLICK", "RIGHT_DRAG", "SCROLL_DOWN", "SCROLL_UP", "value", "_generate_next_value_", "_ignore_", "_member_map_", "_member_names_", "_missing_", "_name_", "_order_", "_value2member_map_", "_value_", "__annotations__", "__base__", "__bases__", "__basicsize__", "__call__", "__class__", "__delattr__", "__dict__", "__dictoffset__", "__dir__", "__doc__", "__eq__", "__flags__", "__format__", "__getattribute__", "__hash__", "__init__", "__init_subclass__", "__instancecheck__", "__itemsize__", "__module__", "__mro__", "__name__", "__ne__", "__new__", "__order__", "__prepare__", "__qualname__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__slots__", "__str__", "__subclasscheck__", "__subclasses__", "__text_signature__", "__weakrefoffset__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.
, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-641-58
inproject
position
[ "action", "position", "_iter_index", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init__", "__init_subclass__", "__iter__", "__module__", "__ne__", "__new__", "__next__", "__post_init__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__slots__", "__str__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.
) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-647-24
infile
_drag_target
[ "allow_fullscreen", "bind", "bindings", "box", "center", "chars", "contains", "copy", "debug", "depth", "execute_binding", "get_lines", "handle_key", "handle_mouse", "height", "id", "is_bindable", "is_selectable", "keys", "parent", "parent_align", "pop", "pos", "print", "remove", "select", "selectables", "selectables_length", "selected", "selected_index", "serialize", "serialized", "set_char", "set_recursive_depth", "set_style", "set_widgets", "sidelength", "size_policy", "static_width", "styles", "vertical_align", "width", "wipe", "_add_widget", "_apply_vertalign", "_bindings", "_box", "_centered_axis", "_drag_target", "_get_aligners", "_get_char", "_get_style", "_has_printed", "_id", "_id_manager", "_prev_screen", "_selectables_length", "_serialized_fields", "_update_width", "_widgets", "__add__", "__annotations__", "__class__", "__contains__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__getitem__", "__hash__", "__iadd__", "__init__", "__init_subclass__", "__iter__", "__len__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__setitem__", "__sizeof__", "__slots__", "__str__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self.
.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-647-37
infile
handle_mouse
[ "bind", "bindings", "chars", "contains", "copy", "debug", "depth", "execute_binding", "get_lines", "handle_key", "handle_mouse", "height", "id", "is_bindable", "is_selectable", "keys", "parent", "parent_align", "pos", "print", "select", "selectables", "selectables_length", "selected_index", "serialize", "serialized", "set_char", "set_style", "size_policy", "static_width", "styles", "width", "_bindings", "_get_char", "_get_style", "_id", "_id_manager", "_selectables_length", "_serialized_fields", "__annotations__", "__bool__", "__class__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__ge__", "__getattribute__", "__gt__", "__hash__", "__init__", "__init_subclass__", "__iter__", "__le__", "__lt__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__slots__", "__str__", "__subclasshook__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.
(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-652-33
infile
handle_mouse
[ "bind", "bindings", "chars", "contains", "copy", "debug", "depth", "execute_binding", "get_lines", "handle_key", "handle_mouse", "height", "id", "is_bindable", "is_selectable", "keys", "parent", "parent_align", "pos", "print", "select", "selectables", "selectables_length", "selected_index", "serialize", "serialized", "set_char", "set_style", "size_policy", "static_width", "styles", "width", "_bindings", "_get_char", "_get_style", "_id", "_id_manager", "_selectables_length", "_serialized_fields", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init__", "__init_subclass__", "__iter__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__slots__", "__str__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.
(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-656-25
inproject
action
[ "action", "position", "_iter_index", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init__", "__init_subclass__", "__iter__", "__module__", "__ne__", "__new__", "__next__", "__post_init__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__slots__", "__str__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.
is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-656-47
inproject
LEFT_CLICK
[ "HOVER", "LEFT_CLICK", "LEFT_DRAG", "mro", "name", "RELEASE", "RIGHT_CLICK", "RIGHT_DRAG", "SCROLL_DOWN", "SCROLL_UP", "value", "_generate_next_value_", "_ignore_", "_member_map_", "_member_names_", "_missing_", "_name_", "_order_", "_value2member_map_", "_value_", "__annotations__", "__base__", "__bases__", "__basicsize__", "__call__", "__class__", "__delattr__", "__dict__", "__dictoffset__", "__dir__", "__doc__", "__eq__", "__flags__", "__format__", "__getattribute__", "__hash__", "__init__", "__init_subclass__", "__instancecheck__", "__itemsize__", "__module__", "__mro__", "__name__", "__ne__", "__new__", "__order__", "__prepare__", "__qualname__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__slots__", "__str__", "__subclasscheck__", "__subclasses__", "__text_signature__", "__weakrefoffset__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.
: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-657-25
random
_drag_target
[ "allow_fullscreen", "bind", "bindings", "box", "center", "chars", "contains", "copy", "debug", "depth", "execute_binding", "get_lines", "handle_key", "handle_mouse", "height", "id", "is_bindable", "is_selectable", "keys", "parent", "parent_align", "pop", "pos", "print", "remove", "select", "selectables", "selectables_length", "selected", "selected_index", "serialize", "serialized", "set_char", "set_recursive_depth", "set_style", "set_widgets", "sidelength", "size_policy", "static_width", "styles", "vertical_align", "width", "wipe", "_add_widget", "_apply_vertalign", "_bindings", "_box", "_centered_axis", "_drag_target", "_get_aligners", "_get_char", "_get_style", "_has_printed", "_id", "_id_manager", "_prev_screen", "_selectables_length", "_serialized_fields", "_update_width", "_widgets", "__add__", "__annotations__", "__class__", "__contains__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__getitem__", "__hash__", "__iadd__", "__init__", "__init_subclass__", "__iter__", "__len__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__setitem__", "__sizeof__", "__slots__", "__str__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self.
= widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-664-22
inproject
is_selectable
[ "bind", "bindings", "chars", "contains", "copy", "debug", "depth", "execute_binding", "get_lines", "handle_key", "handle_mouse", "height", "id", "is_bindable", "is_selectable", "keys", "parent", "parent_align", "pos", "print", "select", "selectables", "selectables_length", "selected_index", "serialize", "serialized", "set_char", "set_style", "size_policy", "static_width", "styles", "width", "_bindings", "_get_char", "_get_style", "_id", "_id_manager", "_selectables_length", "_serialized_fields", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init__", "__init_subclass__", "__iter__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__slots__", "__str__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.
: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-665-44
infile
selectables_length
[ "bind", "bindings", "chars", "contains", "copy", "debug", "depth", "execute_binding", "get_lines", "handle_key", "handle_mouse", "height", "id", "is_bindable", "is_selectable", "keys", "parent", "parent_align", "pos", "print", "select", "selectables", "selectables_length", "selected_index", "serialize", "serialized", "set_char", "set_style", "size_policy", "static_width", "styles", "width", "_bindings", "_get_char", "_get_style", "_id", "_id_manager", "_selectables_length", "_serialized_fields", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init__", "__init_subclass__", "__iter__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__slots__", "__str__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.
return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-682-31
inproject
keys
[ "allow_fullscreen", "bind", "bindings", "box", "center", "chars", "contains", "copy", "debug", "depth", "execute_binding", "get_lines", "handle_key", "handle_mouse", "height", "id", "is_bindable", "is_selectable", "keys", "parent", "parent_align", "pop", "pos", "print", "remove", "select", "selectables", "selectables_length", "selected", "selected_index", "serialize", "serialized", "set_char", "set_recursive_depth", "set_style", "set_widgets", "sidelength", "size_policy", "static_width", "styles", "vertical_align", "width", "wipe", "_add_widget", "_apply_vertalign", "_bindings", "_box", "_centered_axis", "_drag_target", "_get_aligners", "_get_char", "_get_style", "_has_printed", "_id", "_id_manager", "_prev_screen", "_selectables_length", "_serialized_fields", "_update_width", "_widgets", "__add__", "__annotations__", "__class__", "__contains__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__getitem__", "__hash__", "__iadd__", "__init__", "__init_subclass__", "__iter__", "__len__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__setitem__", "__sizeof__", "__slots__", "__str__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.
["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-682-51
inproject
keys
[ "allow_fullscreen", "bind", "bindings", "box", "center", "chars", "contains", "copy", "debug", "depth", "execute_binding", "get_lines", "handle_key", "handle_mouse", "height", "id", "is_bindable", "is_selectable", "keys", "parent", "parent_align", "pop", "pos", "print", "remove", "select", "selectables", "selectables_length", "selected", "selected_index", "serialize", "serialized", "set_char", "set_recursive_depth", "set_style", "set_widgets", "sidelength", "size_policy", "static_width", "styles", "vertical_align", "width", "wipe", "_add_widget", "_apply_vertalign", "_bindings", "_box", "_centered_axis", "_drag_target", "_get_aligners", "_get_char", "_get_style", "_has_printed", "_id", "_id_manager", "_prev_screen", "_selectables_length", "_serialized_fields", "_update_width", "_widgets", "__add__", "__annotations__", "__class__", "__contains__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__getitem__", "__hash__", "__iadd__", "__init__", "__init_subclass__", "__iter__", "__len__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__setitem__", "__sizeof__", "__slots__", "__str__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.
["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-684-16
infile
selected
[ "allow_fullscreen", "bind", "bindings", "box", "center", "chars", "contains", "copy", "debug", "depth", "execute_binding", "get_lines", "handle_key", "handle_mouse", "height", "id", "is_bindable", "is_selectable", "keys", "parent", "parent_align", "pop", "pos", "print", "remove", "select", "selectables", "selectables_length", "selected", "selected_index", "serialize", "serialized", "set_char", "set_recursive_depth", "set_style", "set_widgets", "sidelength", "size_policy", "static_width", "styles", "vertical_align", "width", "wipe", "_add_widget", "_apply_vertalign", "_bindings", "_box", "_centered_axis", "_drag_target", "_get_aligners", "_get_char", "_get_style", "_has_printed", "_id", "_id_manager", "_prev_screen", "_selectables_length", "_serialized_fields", "_update_width", "_widgets", "__add__", "__annotations__", "__class__", "__contains__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__getitem__", "__hash__", "__iadd__", "__init__", "__init_subclass__", "__iter__", "__len__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__setitem__", "__sizeof__", "__slots__", "__str__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.
is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-684-46
infile
selected
[ "allow_fullscreen", "bind", "bindings", "box", "center", "chars", "contains", "copy", "debug", "depth", "execute_binding", "get_lines", "handle_key", "handle_mouse", "height", "id", "is_bindable", "is_selectable", "keys", "parent", "parent_align", "pop", "pos", "print", "remove", "select", "selectables", "selectables_length", "selected", "selected_index", "serialize", "serialized", "set_char", "set_recursive_depth", "set_style", "set_widgets", "sidelength", "size_policy", "static_width", "styles", "vertical_align", "width", "wipe", "_add_widget", "_apply_vertalign", "_bindings", "_box", "_centered_axis", "_drag_target", "_get_aligners", "_get_char", "_get_style", "_has_printed", "_id", "_id_manager", "_prev_screen", "_selectables_length", "_serialized_fields", "_update_width", "_widgets", "__add__", "__annotations__", "__class__", "__contains__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__getitem__", "__hash__", "__iadd__", "__init__", "__init_subclass__", "__iter__", "__len__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__setitem__", "__sizeof__", "__slots__", "__str__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.
.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-684-55
infile
handle_key
[ "bind", "bindings", "chars", "contains", "copy", "debug", "depth", "execute_binding", "get_lines", "handle_key", "handle_mouse", "height", "id", "is_bindable", "is_selectable", "keys", "parent", "parent_align", "pos", "print", "select", "selectables", "selectables_length", "selected_index", "serialize", "serialized", "set_char", "set_style", "size_policy", "static_width", "styles", "width", "_bindings", "_get_char", "_get_style", "_id", "_id_manager", "_selectables_length", "_serialized_fields", "__annotations__", "__bool__", "__class__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__ge__", "__getattribute__", "__gt__", "__hash__", "__init__", "__init_subclass__", "__iter__", "__le__", "__lt__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__slots__", "__str__", "__subclasshook__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.
(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-688-16
infile
selectables_length
[ "allow_fullscreen", "bind", "bindings", "box", "center", "chars", "contains", "copy", "debug", "depth", "execute_binding", "get_lines", "handle_key", "handle_mouse", "height", "id", "is_bindable", "is_selectable", "keys", "parent", "parent_align", "pop", "pos", "print", "remove", "select", "selectables", "selectables_length", "selected", "selected_index", "serialize", "serialized", "set_char", "set_recursive_depth", "set_style", "set_widgets", "sidelength", "size_policy", "static_width", "styles", "vertical_align", "width", "wipe", "_add_widget", "_apply_vertalign", "_bindings", "_box", "_centered_axis", "_drag_target", "_get_aligners", "_get_char", "_get_style", "_has_printed", "_id", "_id_manager", "_prev_screen", "_selectables_length", "_serialized_fields", "_update_width", "_widgets", "__add__", "__annotations__", "__class__", "__contains__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__getitem__", "__hash__", "__iadd__", "__init__", "__init_subclass__", "__iter__", "__len__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__setitem__", "__sizeof__", "__slots__", "__str__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.
> 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-691-21
infile
select
[ "allow_fullscreen", "bind", "bindings", "box", "center", "chars", "contains", "copy", "debug", "depth", "execute_binding", "get_lines", "handle_key", "handle_mouse", "height", "id", "is_bindable", "is_selectable", "keys", "parent", "parent_align", "pop", "pos", "print", "remove", "select", "selectables", "selectables_length", "selected", "selected_index", "serialize", "serialized", "set_char", "set_recursive_depth", "set_style", "set_widgets", "sidelength", "size_policy", "static_width", "styles", "vertical_align", "width", "wipe", "_add_widget", "_apply_vertalign", "_bindings", "_box", "_centered_axis", "_drag_target", "_get_aligners", "_get_char", "_get_style", "_has_printed", "_id", "_id_manager", "_prev_screen", "_selectables_length", "_serialized_fields", "_update_width", "_widgets", "__add__", "__annotations__", "__class__", "__contains__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__getitem__", "__hash__", "__iadd__", "__init__", "__init_subclass__", "__iter__", "__len__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__setitem__", "__sizeof__", "__slots__", "__str__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.
(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-695-27
inproject
keys
[ "allow_fullscreen", "bind", "bindings", "box", "center", "chars", "contains", "copy", "debug", "depth", "execute_binding", "get_lines", "handle_key", "handle_mouse", "height", "id", "is_bindable", "is_selectable", "keys", "parent", "parent_align", "pop", "pos", "print", "remove", "select", "selectables", "selectables_length", "selected", "selected_index", "serialize", "serialized", "set_char", "set_recursive_depth", "set_style", "set_widgets", "sidelength", "size_policy", "static_width", "styles", "vertical_align", "width", "wipe", "_add_widget", "_apply_vertalign", "_bindings", "_box", "_centered_axis", "_drag_target", "_get_aligners", "_get_char", "_get_style", "_has_printed", "_id", "_id_manager", "_prev_screen", "_selectables_length", "_serialized_fields", "_update_width", "_widgets", "__add__", "__annotations__", "__class__", "__contains__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__getitem__", "__hash__", "__iadd__", "__init__", "__init_subclass__", "__iter__", "__len__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__setitem__", "__sizeof__", "__slots__", "__str__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.
["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-704-29
inproject
keys
[ "allow_fullscreen", "bind", "bindings", "box", "center", "chars", "contains", "copy", "debug", "depth", "execute_binding", "get_lines", "handle_key", "handle_mouse", "height", "id", "is_bindable", "is_selectable", "keys", "parent", "parent_align", "pop", "pos", "print", "remove", "select", "selectables", "selectables_length", "selected", "selected_index", "serialize", "serialized", "set_char", "set_recursive_depth", "set_style", "set_widgets", "sidelength", "size_policy", "static_width", "styles", "vertical_align", "width", "wipe", "_add_widget", "_apply_vertalign", "_bindings", "_box", "_centered_axis", "_drag_target", "_get_aligners", "_get_char", "_get_style", "_has_printed", "_id", "_id_manager", "_prev_screen", "_selectables_length", "_serialized_fields", "_update_width", "_widgets", "__add__", "__annotations__", "__class__", "__contains__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__getitem__", "__hash__", "__iadd__", "__init__", "__init_subclass__", "__iter__", "__len__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__setitem__", "__sizeof__", "__slots__", "__str__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.
["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-707-35
infile
selectables
[ "allow_fullscreen", "bind", "bindings", "box", "center", "chars", "contains", "copy", "debug", "depth", "execute_binding", "get_lines", "handle_key", "handle_mouse", "height", "id", "is_bindable", "is_selectable", "keys", "parent", "parent_align", "pop", "pos", "print", "remove", "select", "selectables", "selectables_length", "selected", "selected_index", "serialize", "serialized", "set_char", "set_recursive_depth", "set_style", "set_widgets", "sidelength", "size_policy", "static_width", "styles", "vertical_align", "width", "wipe", "_add_widget", "_apply_vertalign", "_bindings", "_box", "_centered_axis", "_drag_target", "_get_aligners", "_get_char", "_get_style", "_has_printed", "_id", "_id_manager", "_prev_screen", "_selectables_length", "_serialized_fields", "_update_width", "_widgets", "__add__", "__annotations__", "__class__", "__contains__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__getitem__", "__hash__", "__iadd__", "__init__", "__init_subclass__", "__iter__", "__len__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__setitem__", "__sizeof__", "__slots__", "__str__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.
): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-716-38
inproject
selected
[ "allow_fullscreen", "bind", "bindings", "box", "center", "chars", "contains", "copy", "debug", "depth", "execute_binding", "get_lines", "handle_key", "handle_mouse", "height", "id", "is_bindable", "is_selectable", "keys", "parent", "parent_align", "pop", "pos", "print", "remove", "select", "selectables", "selectables_length", "selected", "selected_index", "serialize", "serialized", "set_char", "set_recursive_depth", "set_style", "set_widgets", "sidelength", "size_policy", "static_width", "styles", "vertical_align", "width", "wipe", "_add_widget", "_apply_vertalign", "_bindings", "_box", "_centered_axis", "_drag_target", "_get_aligners", "_get_char", "_get_style", "_has_printed", "_id", "_id_manager", "_prev_screen", "_selectables_length", "_serialized_fields", "_update_width", "_widgets", "__add__", "__annotations__", "__class__", "__contains__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__getitem__", "__hash__", "__iadd__", "__init__", "__init_subclass__", "__iter__", "__len__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__setitem__", "__sizeof__", "__slots__", "__str__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.
is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-718-21
infile
selected
[ "allow_fullscreen", "bind", "bindings", "box", "center", "chars", "contains", "copy", "debug", "depth", "execute_binding", "get_lines", "handle_key", "handle_mouse", "height", "id", "is_bindable", "is_selectable", "keys", "parent", "parent_align", "pop", "pos", "print", "remove", "select", "selectables", "selectables_length", "selected", "selected_index", "serialize", "serialized", "set_char", "set_recursive_depth", "set_style", "set_widgets", "sidelength", "size_policy", "static_width", "styles", "vertical_align", "width", "wipe", "_add_widget", "_apply_vertalign", "_bindings", "_box", "_centered_axis", "_drag_target", "_get_aligners", "_get_char", "_get_style", "_has_printed", "_id", "_id_manager", "_prev_screen", "_selectables_length", "_serialized_fields", "_update_width", "_widgets", "__add__", "__annotations__", "__class__", "__contains__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__getitem__", "__hash__", "__iadd__", "__init__", "__init_subclass__", "__iter__", "__len__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__setitem__", "__sizeof__", "__slots__", "__str__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.
.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-718-30
infile
handle_key
[ "bind", "bindings", "chars", "contains", "copy", "debug", "depth", "execute_binding", "get_lines", "handle_key", "handle_mouse", "height", "id", "is_bindable", "is_selectable", "keys", "parent", "parent_align", "pos", "print", "select", "selectables", "selectables_length", "selected_index", "serialize", "serialized", "set_char", "set_style", "size_policy", "static_width", "styles", "width", "_bindings", "_get_char", "_get_style", "_id", "_id_manager", "_selectables_length", "_serialized_fields", "__annotations__", "__bool__", "__class__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__ge__", "__getattribute__", "__gt__", "__hash__", "__init__", "__init_subclass__", "__iter__", "__le__", "__lt__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__slots__", "__str__", "__subclasshook__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.
(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-747-29
infile
get_lines
[ "allow_fullscreen", "bind", "bindings", "box", "center", "chars", "contains", "copy", "debug", "depth", "execute_binding", "get_lines", "handle_key", "handle_mouse", "height", "id", "is_bindable", "is_selectable", "keys", "parent", "parent_align", "pop", "pos", "print", "remove", "select", "selectables", "selectables_length", "selected", "selected_index", "serialize", "serialized", "set_char", "set_recursive_depth", "set_style", "set_widgets", "sidelength", "size_policy", "static_width", "styles", "vertical_align", "width", "wipe", "_add_widget", "_apply_vertalign", "_bindings", "_box", "_centered_axis", "_drag_target", "_get_aligners", "_get_char", "_get_style", "_has_printed", "_id", "_id_manager", "_prev_screen", "_selectables_length", "_serialized_fields", "_update_width", "_widgets", "__add__", "__annotations__", "__class__", "__contains__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__getitem__", "__hash__", "__iadd__", "__init__", "__init_subclass__", "__iter__", "__len__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__setitem__", "__sizeof__", "__slots__", "__str__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.
(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-762-26
infile
debug
[ "bind", "bindings", "chars", "contains", "copy", "debug", "depth", "execute_binding", "get_lines", "handle_key", "handle_mouse", "height", "id", "is_bindable", "is_selectable", "keys", "parent", "parent_align", "pos", "print", "select", "selectables", "selectables_length", "selected_index", "serialize", "serialized", "set_char", "set_style", "size_policy", "static_width", "styles", "width", "_bindings", "_get_char", "_get_style", "_id", "_id_manager", "_selectables_length", "_serialized_fields", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init__", "__init_subclass__", "__iter__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__slots__", "__str__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.
() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-795-44
inproject
CENTER
[ "as_integer_ratio", "bit_length", "CENTER", "conjugate", "denominator", "from_bytes", "get_default", "imag", "LEFT", "mro", "name", "numerator", "real", "RIGHT", "to_bytes", "value", "_generate_next_value_", "_ignore_", "_member_map_", "_member_names_", "_missing_", "_name_", "_order_", "_value2member_map_", "_value_", "__abs__", "__add__", "__and__", "__annotations__", "__base__", "__bases__", "__basicsize__", "__bool__", "__call__", "__ceil__", "__class__", "__delattr__", "__dict__", "__dictoffset__", "__dir__", "__divmod__", "__doc__", "__eq__", "__flags__", "__float__", "__floor__", "__floordiv__", "__format__", "__ge__", "__getattribute__", "__getnewargs__", "__gt__", "__hash__", "__index__", "__init__", "__init_subclass__", "__instancecheck__", "__int__", "__invert__", "__itemsize__", "__le__", "__lshift__", "__lt__", "__mod__", "__module__", "__mro__", "__mul__", "__name__", "__ne__", "__neg__", "__new__", "__or__", "__order__", "__pos__", "__pow__", "__prepare__", "__qualname__", "__radd__", "__rand__", "__rdivmod__", "__reduce__", "__reduce_ex__", "__repr__", "__rfloordiv__", "__rlshift__", "__rmod__", "__rmul__", "__ror__", "__round__", "__rpow__", "__rrshift__", "__rshift__", "__rsub__", "__rtruediv__", "__rxor__", "__setattr__", "__sizeof__", "__slots__", "__str__", "__sub__", "__subclasscheck__", "__subclasses__", "__text_signature__", "__truediv__", "__trunc__", "__weakrefoffset__", "__xor__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.
: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-821-22
inproject
size_policy
[ "bind", "bindings", "chars", "contains", "copy", "debug", "depth", "execute_binding", "get_lines", "handle_key", "handle_mouse", "height", "id", "is_bindable", "is_selectable", "keys", "parent", "parent_align", "pos", "print", "select", "selectables", "selectables_length", "selected_index", "serialize", "serialized", "set_char", "set_style", "size_policy", "static_width", "styles", "width", "_bindings", "_get_char", "_get_style", "_id", "_id_manager", "_selectables_length", "_serialized_fields", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init__", "__init_subclass__", "__iter__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__slots__", "__str__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.
is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-821-48
inproject
STATIC
[ "as_integer_ratio", "bit_length", "conjugate", "denominator", "FILL", "from_bytes", "get_default", "imag", "mro", "name", "numerator", "real", "RELATIVE", "STATIC", "to_bytes", "value", "_generate_next_value_", "_ignore_", "_member_map_", "_member_names_", "_missing_", "_name_", "_order_", "_value2member_map_", "_value_", "__abs__", "__add__", "__and__", "__annotations__", "__base__", "__bases__", "__basicsize__", "__bool__", "__call__", "__ceil__", "__class__", "__delattr__", "__dict__", "__dictoffset__", "__dir__", "__divmod__", "__doc__", "__eq__", "__flags__", "__float__", "__floor__", "__floordiv__", "__format__", "__ge__", "__getattribute__", "__getnewargs__", "__gt__", "__hash__", "__index__", "__init__", "__init_subclass__", "__instancecheck__", "__int__", "__invert__", "__itemsize__", "__le__", "__lshift__", "__lt__", "__mod__", "__module__", "__mro__", "__mul__", "__name__", "__ne__", "__neg__", "__new__", "__or__", "__order__", "__pos__", "__pow__", "__prepare__", "__qualname__", "__radd__", "__rand__", "__rdivmod__", "__reduce__", "__reduce_ex__", "__repr__", "__rfloordiv__", "__rlshift__", "__rmod__", "__rmul__", "__ror__", "__round__", "__rpow__", "__rrshift__", "__rshift__", "__rsub__", "__rtruediv__", "__rxor__", "__setattr__", "__sizeof__", "__slots__", "__str__", "__sub__", "__subclasscheck__", "__subclasses__", "__text_signature__", "__truediv__", "__trunc__", "__weakrefoffset__", "__xor__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.
: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-822-54
inproject
width
[ "bind", "bindings", "chars", "contains", "copy", "debug", "depth", "execute_binding", "get_lines", "handle_key", "handle_mouse", "height", "id", "is_bindable", "is_selectable", "keys", "parent", "parent_align", "pos", "print", "select", "selectables", "selectables_length", "selected_index", "serialize", "serialized", "set_char", "set_style", "size_policy", "static_width", "styles", "width", "_bindings", "_get_char", "_get_style", "_id", "_id_manager", "_selectables_length", "_serialized_fields", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init__", "__init_subclass__", "__iter__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__slots__", "__str__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.
width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-832-40
infile
_align
[ "allow_fullscreen", "bind", "bindings", "box", "center", "chars", "contains", "copy", "debug", "depth", "execute_binding", "get_lines", "handle_key", "handle_mouse", "height", "id", "is_bindable", "is_selectable", "keys", "parent", "parent_align", "pop", "pos", "print", "remove", "select", "selectables", "selectables_length", "selected", "selected_index", "serialize", "serialized", "set_char", "set_recursive_depth", "set_style", "set_widgets", "sidelength", "size_policy", "static_width", "styles", "vertical_align", "width", "wipe", "_add_widget", "_align", "_apply_vertalign", "_bindings", "_box", "_centered_axis", "_drag_target", "_get_aligners", "_get_char", "_get_style", "_has_printed", "_id", "_id_manager", "_prev_screen", "_selectables_length", "_serialized_fields", "_update_width", "_widgets", "__add__", "__annotations__", "__class__", "__contains__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__getitem__", "__hash__", "__iadd__", "__init__", "__init_subclass__", "__iter__", "__len__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__setitem__", "__sizeof__", "__slots__", "__str__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self.
( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-849-18
common
append
[ "append", "clear", "copy", "count", "extend", "index", "insert", "pop", "remove", "reverse", "sort", "__add__", "__annotations__", "__class__", "__class_getitem__", "__contains__", "__delattr__", "__delitem__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__ge__", "__getattribute__", "__getitem__", "__gt__", "__hash__", "__iadd__", "__imul__", "__init__", "__init_subclass__", "__iter__", "__le__", "__len__", "__lt__", "__module__", "__mul__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__reversed__", "__rmul__", "__setattr__", "__setitem__", "__sizeof__", "__slots__", "__str__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.
((reset() + separator).join(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
54
54-849-47
common
join
[ "capitalize", "casefold", "center", "count", "encode", "endswith", "expandtabs", "find", "format", "format_map", "index", "isalnum", "isalpha", "isascii", "isdecimal", "isdigit", "isidentifier", "islower", "isnumeric", "isprintable", "isspace", "istitle", "isupper", "join", "ljust", "lower", "lstrip", "maketrans", "partition", "removeprefix", "removesuffix", "replace", "rfind", "rindex", "rjust", "rpartition", "rsplit", "rstrip", "split", "splitlines", "startswith", "strip", "swapcase", "title", "translate", "upper", "zfill", "__add__", "__annotations__", "__class__", "__contains__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__ge__", "__getattribute__", "__getitem__", "__getnewargs__", "__gt__", "__hash__", "__init__", "__init_subclass__", "__iter__", "__le__", "__len__", "__lt__", "__mod__", "__module__", "__mul__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__reversed__", "__rmul__", "__setattr__", "__sizeof__", "__slots__", "__str__" ]
"""The module containing all of the layout-related widgets.""" # These widgets have more than the 7 allowed instance attributes. # pylint: disable=too-many-instance-attributes from __future__ import annotations from itertools import zip_longest from typing import Any, Callable, Iterator, cast from ..ansi_interface import MouseAction, MouseEvent, clear, reset, terminal from ..context_managers import cursor_at from ..enums import CenteringPolicy, HorizontalAlignment, SizePolicy, VerticalAlignment from ..exceptions import WidthExceededError from ..helpers import real_length from ..input import keys from . import boxes from . import styles as w_styles from .base import Widget class Container(Widget): """A widget that displays other widgets, stacked vertically.""" chars: dict[str, w_styles.CharType] = { "border": ["| ", "-", " |", "-"], "corner": [""] * 4, } styles = { "border": w_styles.MARKUP, "corner": w_styles.MARKUP, "fill": w_styles.BACKGROUND, } keys = { "next": {keys.DOWN, keys.CTRL_N, "j"}, "previous": {keys.UP, keys.CTRL_P, "k"}, } serialized = Widget.serialized + ["_centered_axis"] vertical_align = VerticalAlignment.CENTER allow_fullscreen = True # TODO: Add `WidgetConvertible`? type instead of Any def __init__(self, *widgets: Any, **attrs: Any) -> None: """Initialize Container data""" super().__init__(**attrs) # TODO: This is just a band-aid. if "width" not in attrs: self.width = 40 self._widgets: list[Widget] = [] self._centered_axis: CenteringPolicy | None = None self._prev_screen: tuple[int, int] = (0, 0) self._has_printed = False self.styles = type(self).styles.copy() self.chars = type(self).chars.copy() for widget in widgets: self._add_widget(widget) self._drag_target: Widget | None = None terminal.subscribe(terminal.RESIZE, lambda *_: self.center(self._centered_axis)) @property def sidelength(self) -> int: """Gets the length of left and right borders combined. Returns: An integer equal to the `pytermgui.helpers.real_length` of the concatenation of the left and right borders of this widget, both with their respective styles applied. """ chars = self._get_char("border") style = self._get_style("border") if not isinstance(chars, list): return 0 left_border, _, right_border, _ = chars return real_length(style(left_border) + style(right_border)) @property def selectables(self) -> list[tuple[Widget, int]]: """Gets all selectable widgets and their inner indices. This is used in order to have a constant reference to all selectable indices within this widget. Returns: A list of tuples containing a widget and an integer each. For each widget that is withing this one, it is added to this list as many times as it has selectables. Each of the integers correspond to a selectable_index within the widget. For example, a Container with a Button, InputField and an inner Container containing 3 selectables might return something like this: ``` [ (Button(...), 0), (InputField(...), 0), (Container(...), 0), (Container(...), 1), (Container(...), 2), ] ``` """ _selectables: list[tuple[Widget, int]] = [] for widget in self._widgets: if not widget.is_selectable: continue for i, (inner, _) in enumerate(widget.selectables): _selectables.append((inner, i)) return _selectables @property def selectables_length(self) -> int: """Gets the length of the selectables list. Returns: An integer equal to the length of `self.selectables`. """ return len(self.selectables) @property def selected(self) -> Widget | None: """Returns the currently selected object Returns: The currently selected widget if selected_index is not None, otherwise None. """ # TODO: Add deeper selection if self.selected_index is None: return None if self.selected_index >= len(self.selectables): return None return self.selectables[self.selected_index][0] @property def box(self) -> boxes.Box: """Returns current box setting Returns: The currently set box instance. """ return self._box @box.setter def box(self, new: str | boxes.Box) -> None: """Applies a new box. Args: new: Either a `pytermgui.boxes.Box` instance or a string analogous to one of the default box names. """ if isinstance(new, str): from_module = vars(boxes).get(new) if from_module is None: raise ValueError(f"Unknown box type {new}.") new = from_module assert isinstance(new, boxes.Box) self._box = new new.set_chars_of(self) def __iadd__(self, other: object) -> Container: """Adds a new widget, then returns self. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self._add_widget(other) return self def __add__(self, other: object) -> Container: """Adds a new widget, then returns self. This method is analogous to `Container.__iadd__`. Args: other: Any widget instance, or data structure that can be turned into a widget by `Widget.from_data`. Returns: A reference to self. """ self.__iadd__(other) return self def __iter__(self) -> Iterator[Widget]: """Gets an iterator of self._widgets. Yields: The next widget. """ for widget in self._widgets: yield widget def __len__(self) -> int: """Gets the length of the widgets list. Returns: An integer describing len(self._widgets). """ return len(self._widgets) def __getitem__(self, sli: int | slice) -> Widget | list[Widget]: """Gets an item from self._widgets. Args: sli: Slice of the list. Returns: The slice in the list. """ return self._widgets[sli] def __setitem__(self, index: int, value: Any) -> None: """Sets an item in self._widgets. Args: index: The index to be set. value: The new widget at this index. """ self._widgets[index] = value def __contains__(self, other: object) -> bool: """Determines if self._widgets contains other widget. Args: other: Any widget-like. Returns: A boolean describing whether `other` is in `self.widgets` """ return other in self._widgets def _add_widget(self, other: object, run_get_lines: bool = True) -> None: """Adds other to this widget. Args: other: Any widget-like object. run_get_lines: Boolean controlling whether the self.get_lines is ran. """ if not isinstance(other, Widget): to_widget = Widget.from_data(other) if to_widget is None: raise ValueError( f"Could not convert {other} of type {type(other)} to a Widget!" ) other = to_widget # This is safe to do, as it would've raised an exception above already assert isinstance(other, Widget) self._widgets.append(other) if isinstance(other, Container): other.set_recursive_depth(self.depth + 2) else: other.depth = self.depth + 1 other.get_lines() other.parent = self if run_get_lines: self.get_lines() def _get_aligners( self, widget: Widget, borders: tuple[str, str] ) -> tuple[Callable[[str], str], int]: """Gets an aligning method and position offset. Args: widget: The widget to align. borders: The left and right borders to put the widget within. Returns: A tuple of a method that, when called with a line, will return that line centered using the passed in widget's parent_align and width, as well as the horizontal offset resulting from the widget being aligned. """ left, right = borders char = self._get_style("fill")(" ") def _align_left(text: str) -> str: """Align line to the left""" padding = self.width - real_length(left + right) - real_length(text) return left + text + padding * char + right def _align_center(text: str) -> str: """Align line to the center""" total = self.width - real_length(left + right) - real_length(text) padding, offset = divmod(total, 2) return left + (padding + offset) * char + text + padding * char + right def _align_right(text: str) -> str: """Align line to the right""" padding = self.width - real_length(left + right) - real_length(text) return left + padding * char + text + right if widget.parent_align == HorizontalAlignment.CENTER: total = self.width - real_length(left + right) - widget.width padding, offset = divmod(total, 2) return _align_center, real_length(left) + padding + offset if widget.parent_align == HorizontalAlignment.RIGHT: return _align_right, self.width - real_length(left) - widget.width # Default to left-aligned return _align_left, real_length(left) def _update_width(self, widget: Widget) -> None: """Updates the width of widget or self. This method respects widget.size_policy. Args: widget: The widget to update/base updates on. """ available = ( self.width - self.sidelength - (0 if isinstance(widget, Container) else 1) ) if widget.size_policy == SizePolicy.FILL: widget.width = available return if widget.size_policy == SizePolicy.RELATIVE: widget.width = widget.relative_width * available return if widget.width > available: if widget.size_policy == SizePolicy.STATIC: raise WidthExceededError( f"Widget {widget}'s static width of {widget.width}" + f" exceeds its parent's available width {available}." "" ) widget.width = available def _apply_vertalign( self, lines: list[str], diff: int, padder: str ) -> tuple[int, list[str]]: """Insert padder line into lines diff times, depending on self.vertical_align. Args: lines: The list of lines to align. diff: The available height. padder: The line to use to pad. Returns: A tuple containing the vertical offset as well as the padded list of lines. Raises: NotImplementedError: The given vertical alignment is not implemented. """ if self.vertical_align == VerticalAlignment.BOTTOM: for _ in range(diff): lines.insert(0, padder) return diff, lines if self.vertical_align == VerticalAlignment.TOP: for _ in range(diff): lines.append(padder) return 0, lines if self.vertical_align == VerticalAlignment.CENTER: top, extra = divmod(diff, 2) bottom = top + extra for _ in range(top): lines.insert(0, padder) for _ in range(bottom): lines.append(padder) return top, lines raise NotImplementedError( f"Vertical alignment {self.vertical_align} is not implemented for {type(self)}." ) def get_lines(self) -> list[str]: """Gets all lines by spacing out inner widgets. This method reflects & applies both width settings, as well as the `parent_align` field. Returns: A list of all lines that represent this Container. """ def _get_border(left: str, char: str, right: str) -> str: """Gets a top or bottom border. Args: left: Left corner character. char: Border character filling between left & right. right: Right corner character. Returns: The border line. """ offset = real_length(left + right) return left + char * (self.width - offset) + right lines = [] style = self._get_style("border") borders = [style(char) for char in self._get_char("border")] style = self._get_style("corner") corners = [style(char) for char in self._get_char("corner")] has_top_bottom = (real_length(borders[1]) > 0, real_length(borders[3]) > 0) align = lambda item: item for widget in self._widgets: align, offset = self._get_aligners(widget, (borders[0], borders[2])) self._update_width(widget) widget.pos = ( self.pos[0] + offset, self.pos[1] + len(lines) + (1 if has_top_bottom[0] else 0), ) widget_lines = [] for line in widget.get_lines(): widget_lines.append(align(line)) lines.extend(widget_lines) vertical_offset, lines = self._apply_vertalign( lines, self.height - len(lines) - sum(has_top_bottom), align("") ) for widget in self._widgets: widget.pos = (widget.pos[0], widget.pos[1] + vertical_offset) # TODO: This is wasteful. widget.get_lines() if has_top_bottom[0]: lines.insert(0, _get_border(corners[0], borders[1], corners[1])) if has_top_bottom[1]: lines.append(_get_border(corners[3], borders[3], corners[2])) self.height = len(lines) return lines def set_widgets(self, new: list[Widget]) -> None: """Sets new list in place of self._widgets. Args: new: The new widget list. """ self._widgets = [] for widget in new: self._add_widget(widget) def serialize(self) -> dict[str, Any]: """Serializes this Container, adding in serializations of all widgets. See `pytermgui.widgets.base.Widget.serialize` for more info. Returns: The dictionary containing all serialized data. """ out = super().serialize() out["_widgets"] = [] for widget in self._widgets: out["_widgets"].append(widget.serialize()) return out def pop(self, index: int = -1) -> Widget: """Pops widget from self._widgets. Analogous to self._widgets.pop(index). Args: index: The index to operate on. Returns: The widget that was popped off the list. """ return self._widgets.pop(index) def remove(self, other: Widget) -> None: """Remove widget from self._widgets Analogous to self._widgets.remove(other). Args: widget: The widget to remove. """ return self._widgets.remove(other) def set_recursive_depth(self, value: int) -> None: """Set depth for this Container and all its children. All inner widgets will receive value+1 as their new depth. Args: value: The new depth to use as the base depth. """ self.depth = value for widget in self._widgets: if isinstance(widget, Container): widget.set_recursive_depth(value + 1) else: widget.depth = value def select(self, index: int | None = None) -> None: """Selects inner subwidget. Args: index: The index to select. Raises: IndexError: The index provided was beyond len(self.selectables). """ # Unselect all sub-elements for other in self._widgets: if other.selectables_length > 0: other.select(None) if index is not None: if index >= len(self.selectables) is None: raise IndexError("Container selection index out of range") widget, inner_index = self.selectables[index] widget.select(inner_index) self.selected_index = index def center( self, where: CenteringPolicy | None = None, store: bool = True ) -> Container: """Centers this object to the given axis. Args: where: A CenteringPolicy describing the place to center to store: When set, this centering will be reapplied during every print, as well as when calling this method with no arguments. Returns: This Container. """ # Refresh in case changes happened self.get_lines() if where is None: # See `enums.py` for explanation about this ignore. where = CenteringPolicy.get_default() # type: ignore centerx = centery = where is CenteringPolicy.ALL centerx |= where is CenteringPolicy.HORIZONTAL centery |= where is CenteringPolicy.VERTICAL pos = list(self.pos) if centerx: pos[0] = (terminal.width - self.width + 2) // 2 if centery: pos[1] = (terminal.height - self.height + 2) // 2 self.pos = (pos[0], pos[1]) if store: self._centered_axis = where self._prev_screen = terminal.size return self def handle_mouse(self, event: MouseEvent) -> bool: """Applies a mouse event on all children. Args: event: The event to handle Returns: A boolean showing whether the event was handled. """ if event.action is MouseAction.RELEASE: # Force RELEASE event to be sent if self._drag_target is not None: self._drag_target.handle_mouse( MouseEvent(MouseAction.RELEASE, event.position) ) self._drag_target = None if self._drag_target is not None: return self._drag_target.handle_mouse(event) selectables_index = 0 for widget in self._widgets: if widget.contains(event.position): handled = widget.handle_mouse(event) if widget.selected_index is not None: selectables_index += widget.selected_index if event.action is MouseAction.LEFT_CLICK: self._drag_target = widget if handled: self.select(selectables_index) return handled if widget.is_selectable: selectables_index += widget.selectables_length return False def handle_key(self, key: str) -> bool: """Handles a keypress, returns its success. Args: key: A key str. Returns: A boolean showing whether the key was handled. """ def _is_nav(key: str) -> bool: """Determine if a key is in the navigation sets""" return key in self.keys["next"] | self.keys["previous"] if self.selected is not None and self.selected.handle_key(key): return True # Only use navigation when there is more than one selectable if self.selectables_length > 1 and _is_nav(key): handled = False if self.selected_index is None: self.select(0) assert isinstance(self.selected_index, int) if key in self.keys["previous"]: # No more selectables left, user wants to exit Container # upwards. if self.selected_index == 0: return False self.select(self.selected_index - 1) handled = True elif key in self.keys["next"]: # Stop selection at last element, return as unhandled new = self.selected_index + 1 if new == len(self.selectables): return False self.select(new) handled = True if handled: return True if key == keys.ENTER and self.selected is not None: if self.selected.selected_index is not None: self.selected.handle_key(key) return True return False def wipe(self) -> None: """Wipes the characters occupied by the object""" with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(real_length(line) * " ") def print(self) -> None: """Prints this Container. If the screen size has changed since last `print` call, the object will be centered based on its `_centered_axis`. """ if not terminal.size == self._prev_screen: clear() self.center(self._centered_axis) self._prev_screen = terminal.size if self.allow_fullscreen: self.pos = terminal.origin with cursor_at(self.pos) as print_here: for line in self.get_lines(): print_here(line) self._has_printed = True def debug(self) -> str: """Returns a string with identifiable information on this widget. Returns: A str in the form of a class construction. This string is in a form that __could have been__ used to create this Container. """ out = "Container(" for widget in self._widgets: out += widget.debug() + ", " out = out.strip(", ") out += ", **attrs)" return out class Splitter(Container): """A widget that displays other widgets, stacked horizontally.""" chars: dict[str, list[str] | str] = {"separator": " | "} styles = {"separator": w_styles.MARKUP, "fill": w_styles.BACKGROUND} keys = { "previous": {keys.LEFT, "h", keys.CTRL_B}, "next": {keys.RIGHT, "l", keys.CTRL_F}, } parent_align = HorizontalAlignment.RIGHT def _align( self, alignment: HorizontalAlignment, target_width: int, line: str ) -> tuple[int, str]: """Align a line r/wordavalanches""" available = target_width - real_length(line) fill_style = self._get_style("fill") char = fill_style(" ") line = fill_style(line) if alignment == HorizontalAlignment.CENTER: padding, offset = divmod(available, 2) return padding, padding * char + line + (padding + offset) * char if alignment == HorizontalAlignment.RIGHT: return available, available * char + line return 0, line + available * char def get_lines(self) -> list[str]: """Join all widgets horizontally.""" # An error will be raised if `separator` is not the correct type (str). separator = self._get_style("separator")(self._get_char("separator")) # type: ignore separator_length = real_length(separator) target_width, error = divmod( self.width - (len(self._widgets) - 1) * separator_length, len(self._widgets) ) vertical_lines = [] total_offset = 0 for widget in self._widgets: inner = [] if widget.size_policy is SizePolicy.STATIC: target_width += target_width - widget.width width = target_width else: widget.width = target_width + error width = widget.width error = 0 aligned: str | None = None for line in widget.get_lines(): # See `enums.py` for information about this ignore padding, aligned = self._align( cast(HorizontalAlignment, widget.parent_align), width, line ) inner.append(aligned) widget.pos = ( self.pos[0] + padding + total_offset, self.pos[1] + (1 if type(widget).__name__ == "Container" else 0), ) if aligned is not None: total_offset += real_length(inner[-1]) + separator_length vertical_lines.append(inner) lines = [] for horizontal in zip_longest(*vertical_lines, fillvalue=" " * target_width): lines.append((reset() + separator).
(horizontal)) return lines def debug(self) -> str: """Return identifiable information""" return super().debug().replace("Container", "Splitter", 1)
bczsalba__pytermgui
60
60-42-21
common
update
[ "clear", "copy", "fromkeys", "get", "items", "keys", "pop", "popitem", "setdefault", "update", "values", "__annotations__", "__class__", "__class_getitem__", "__contains__", "__delattr__", "__delitem__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__getitem__", "__hash__", "__init__", "__init_subclass__", "__ior__", "__iter__", "__len__", "__module__", "__ne__", "__new__", "__or__", "__reduce__", "__reduce_ex__", "__repr__", "__reversed__", "__setattr__", "__setitem__", "__sizeof__", "__slots__", "__str__" ]
import random from copy import copy from typing import List from common.hierarchical_logger import hlog from .scenario import Scenario, Instance, Reference, TRAIN_TAG, VALID_TAG, TEST_TAG, CORRECT_TAG def get_vocab(): subjects = { "person": ["Alice", "Bob", "Carol", "Dan", "Erin", "Frank"], "animal": [ "dog", "cat", "rabbit", "mouse", "tiger", "lion", "bear", "squirrel", "cow", "panda", "hedgehog", "elephant", "giraffe", "hippo", ], "plant": ["poppy", "dandelion", "tree", "rose", "sunflower"], } attributes = [ # 'red', 'blue', 'green', 'young', 'round', 'rough', # 'fuzzy', 'sad', 'tasty', 'soft', 'fine', 'funny', 'rich', # 'new', 'sick', 'poor', 'boring', 'powerful', # 'friendly', 'orange', 'wide', 'lost', 'yellow', # 'white', 'grey', 'black', 'pink', 'brown', 'cheerful', # 'striped', 'wild', 'shiny', # 'fluffy', 'gray', 'curly', 'busy', 'plain', 'flat', 'sleek', # 'scary', 'harmless', 'graceful' # # 'heavy', 'tall', 'short', 'light', 'long', 'fat', 'gentle', 'elegant', 'sparkly', 'great', ] attribute_groups = {attribute: [attribute] for attribute in attributes} attribute_groups.
( { "cold": ["cold", "chill", "cool"], "hot": ["hot", "warm"], "smart": ["smart", "clever", "wise", "intelligent"], "clean": ["clean", "tidy"], "small": ["small", "little", "tiny"], "big": ["big", "enormous", "giant", "huge"], "good": ["good", "kind", "nice"], "beautiful": ["beautiful", "pretty"], "red": ["red", "crimson"], "blue": ["blue", "cobalt"], "green": ["green", "viridian"], "purple": ["purple", "violet"], "boring": ["boring", "dull"], "old": ["old", "ancient", "antique"], "strong": ["strong", "powerful", "muscular"], "weak": ["weak", "frail", "fragile"], "fast": ["fast", "quick"], "slow": ["slow", "sluggish"], "bad": ["bad", "evil", "wicked", "mean"], "happy": ["happy", "elated", "glad"], } ) new_attribute_groups = copy(attribute_groups) for general_attribute, specific_attributes in attribute_groups.items(): for specific_attribute in specific_attributes: if (general_attribute != specific_attribute) and (specific_attribute in attribute_groups): del new_attribute_groups[specific_attribute] attribute_groups = new_attribute_groups return attribute_groups, subjects def generate_specifier(subject, upper=False): base_char = "A" if upper else "a" if subject[0].lower() in ["a", "e", "i", "o", "u"]: return base_char + "n" return base_char # Maps from a rule dictionary to a string def parse_rule(rule): # Rules should have the following format: # { # 'subject': 'someone', # 'condition': ['red', 'kind'], # 'condition_conjunction': 'and', # 'consequent': 'cold' # 'specified': True # } condition = f" {rule['condition_conjunction']} ".join(rule["condition"]) specified = rule["specified"] if specified: specifier = generate_specifier(rule["subject"]) return f"If {specifier} {rule['subject']} is {condition}, then the {rule['subject']} is {rule['consequent']}." return f"If {rule['subject']} is {condition}, then {rule['subject']} is {rule['consequent']}." # Maps from a set of attributes about a subject to a string def parse_fact(subject, attributes, prefix="", specifier=""): if len(attributes) == 0: return "Nothing." return f"{prefix}{specifier}{subject} is {' and '.join(attributes)}." # Generates a set of rules about a subject def generate_rules(attribute_groups, subject_category, subject, max_rules=5, specific_category=False): attributes_shuffled = list(attribute_groups.keys()).copy() random.shuffle(attributes_shuffled) rules = [] hlog("Generating language pattern matching examples") while len(attributes_shuffled) > 2 and len(rules) < max_rules: rule_subject_category = subject if specific_category else random.choice([subject_category, subject]) n_rule_attributes = random.randint(2, 3) rule_attributes, attributes_shuffled = ( attributes_shuffled[:n_rule_attributes], attributes_shuffled[n_rule_attributes:], ) condition = rule_attributes[:-1] condition_conjunction = random.choice(["and", "or"]) consequent = rule_attributes[-1] specied = (subject_category != "person") or (rule_subject_category == "person") rules.append( { "subject": rule_subject_category, "condition": condition, "condition_conjunction": condition_conjunction, "consequent": consequent, "specified": specied, } ) return rules # Generates a test about a subject given a set of rules def generate_test(attribute_groups, subject, rules, p_consquenceless=0.1): # test_attributes = random.sample(attributes, 2) test_attributes = random.sample(list(attribute_groups.keys()), 2) test_attributes_specific = [random.choice(attribute_groups[subcondition]) for subcondition in test_attributes] test_consequents = [] test_rules_used = [] for rule in rules: condition_conjunction = rule["condition_conjunction"] rule_condition = rule["condition"] rule_consequent = rule["consequent"] if rule_consequent in test_attributes: continue if condition_conjunction == "and": if set(rule_condition).issubset(test_attributes): test_rules_used.append(rule) test_consequents.append(rule_consequent) elif condition_conjunction == "or": if not set(rule_condition).isdisjoint(test_attributes): test_rules_used.append(rule) test_consequents.append(rule_consequent) if len(test_consequents) == 0 and random.random() > p_consquenceless: return generate_test(attribute_groups, subject, rules, p_consquenceless) return test_attributes, test_attributes_specific, test_consequents, test_rules_used class LanguagePatternMatchingScenario(Scenario): """ The Massive Multitask Language Understanding benchmark from this paper: https://arxiv.org/pdf/2009.03300.pdf Code is adapted from: https://github.com/hendrycks/test/blob/master/evaluate.py https://github.com/EleutherAI/lm-evaluation-harness/blob/master/lm_eval/tasks/hendrycks_test.py """ name = "mmlu" description = "Massive Multitask Language Understanding" tags = ["reasoning", "language", "pattern_matching"] def __init__(self, subject: str): self.attribute_groups, self.subjects = get_vocab() self.generic_attributes = False self.specific_category = False self.include_intermediates = True self.n_train_samples = 100 self.n_valid_samples = 100 self.n_test_samples = 100 def get_instances(self) -> List[Instance]: # Read all the instances instances = [] for sample_idx in range(self.n_train_samples + self.n_test_samples): # generic_attributes specifies that the top level attribute should always be used # e.g. "cold" instead of "chill" # specific_category specifies that the specific category should always be used # e.g. "dog" instead of "an animal" subject_category = random.choice(list(self.subjects.keys())) subject = random.choice(self.subjects[subject_category]) rules = generate_rules( self.attribute_groups, subject_category, subject, specific_category=self.specific_category ) test_attributes, test_attributes_specific, test_consequents, test_rules_used = generate_test( self.attribute_groups, subject, rules ) question = "Rules:\n" for rule in rules: question += parse_rule(rule) + "\n" test_specifier_base = generate_specifier(subject, upper=True) test_specifier_first = test_specifier_base + " " if subject_category != "person" else "" test_specifier_second = "The " if subject_category != "person" else "" test_specifier_third = "the " if subject_category != "person" else "" print_test_attributes = test_attributes if self.generic_attributes else test_attributes_specific question += "Fact:\n" question += parse_fact(subject, print_test_attributes, specifier=test_specifier_first) + "\n" if self.include_intermediates: question += "Rule(s) used:\n" for rule in test_rules_used: question += parse_rule(rule) + "\n" question += f"The following can be determined about {test_specifier_third}{subject}:\n" correct_answer = parse_fact(subject, test_consequents, specifier=test_specifier_second) if sample_idx < self.n_train_samples: cur_tag = TRAIN_TAG elif sample_idx < self.n_train_samples + self.n_valid_samples: cur_tag = VALID_TAG else: cur_tag = TEST_TAG instance = Instance( input=question, references=[Reference(output=correct_answer, tags=[CORRECT_TAG])], tags=[cur_tag], ) instances.append(instance) return instances
stanford-crfm__helm
60
60-110-48
random
keys
[ "clear", "copy", "fromkeys", "get", "items", "keys", "pop", "popitem", "setdefault", "update", "values", "__annotations__", "__class__", "__class_getitem__", "__contains__", "__delattr__", "__delitem__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__getitem__", "__hash__", "__init__", "__init_subclass__", "__ior__", "__iter__", "__len__", "__module__", "__ne__", "__new__", "__or__", "__reduce__", "__reduce_ex__", "__repr__", "__reversed__", "__setattr__", "__setitem__", "__sizeof__", "__slots__", "__str__" ]
import random from copy import copy from typing import List from common.hierarchical_logger import hlog from .scenario import Scenario, Instance, Reference, TRAIN_TAG, VALID_TAG, TEST_TAG, CORRECT_TAG def get_vocab(): subjects = { "person": ["Alice", "Bob", "Carol", "Dan", "Erin", "Frank"], "animal": [ "dog", "cat", "rabbit", "mouse", "tiger", "lion", "bear", "squirrel", "cow", "panda", "hedgehog", "elephant", "giraffe", "hippo", ], "plant": ["poppy", "dandelion", "tree", "rose", "sunflower"], } attributes = [ # 'red', 'blue', 'green', 'young', 'round', 'rough', # 'fuzzy', 'sad', 'tasty', 'soft', 'fine', 'funny', 'rich', # 'new', 'sick', 'poor', 'boring', 'powerful', # 'friendly', 'orange', 'wide', 'lost', 'yellow', # 'white', 'grey', 'black', 'pink', 'brown', 'cheerful', # 'striped', 'wild', 'shiny', # 'fluffy', 'gray', 'curly', 'busy', 'plain', 'flat', 'sleek', # 'scary', 'harmless', 'graceful' # # 'heavy', 'tall', 'short', 'light', 'long', 'fat', 'gentle', 'elegant', 'sparkly', 'great', ] attribute_groups = {attribute: [attribute] for attribute in attributes} attribute_groups.update( { "cold": ["cold", "chill", "cool"], "hot": ["hot", "warm"], "smart": ["smart", "clever", "wise", "intelligent"], "clean": ["clean", "tidy"], "small": ["small", "little", "tiny"], "big": ["big", "enormous", "giant", "huge"], "good": ["good", "kind", "nice"], "beautiful": ["beautiful", "pretty"], "red": ["red", "crimson"], "blue": ["blue", "cobalt"], "green": ["green", "viridian"], "purple": ["purple", "violet"], "boring": ["boring", "dull"], "old": ["old", "ancient", "antique"], "strong": ["strong", "powerful", "muscular"], "weak": ["weak", "frail", "fragile"], "fast": ["fast", "quick"], "slow": ["slow", "sluggish"], "bad": ["bad", "evil", "wicked", "mean"], "happy": ["happy", "elated", "glad"], } ) new_attribute_groups = copy(attribute_groups) for general_attribute, specific_attributes in attribute_groups.items(): for specific_attribute in specific_attributes: if (general_attribute != specific_attribute) and (specific_attribute in attribute_groups): del new_attribute_groups[specific_attribute] attribute_groups = new_attribute_groups return attribute_groups, subjects def generate_specifier(subject, upper=False): base_char = "A" if upper else "a" if subject[0].lower() in ["a", "e", "i", "o", "u"]: return base_char + "n" return base_char # Maps from a rule dictionary to a string def parse_rule(rule): # Rules should have the following format: # { # 'subject': 'someone', # 'condition': ['red', 'kind'], # 'condition_conjunction': 'and', # 'consequent': 'cold' # 'specified': True # } condition = f" {rule['condition_conjunction']} ".join(rule["condition"]) specified = rule["specified"] if specified: specifier = generate_specifier(rule["subject"]) return f"If {specifier} {rule['subject']} is {condition}, then the {rule['subject']} is {rule['consequent']}." return f"If {rule['subject']} is {condition}, then {rule['subject']} is {rule['consequent']}." # Maps from a set of attributes about a subject to a string def parse_fact(subject, attributes, prefix="", specifier=""): if len(attributes) == 0: return "Nothing." return f"{prefix}{specifier}{subject} is {' and '.join(attributes)}." # Generates a set of rules about a subject def generate_rules(attribute_groups, subject_category, subject, max_rules=5, specific_category=False): attributes_shuffled = list(attribute_groups.
()).copy() random.shuffle(attributes_shuffled) rules = [] hlog("Generating language pattern matching examples") while len(attributes_shuffled) > 2 and len(rules) < max_rules: rule_subject_category = subject if specific_category else random.choice([subject_category, subject]) n_rule_attributes = random.randint(2, 3) rule_attributes, attributes_shuffled = ( attributes_shuffled[:n_rule_attributes], attributes_shuffled[n_rule_attributes:], ) condition = rule_attributes[:-1] condition_conjunction = random.choice(["and", "or"]) consequent = rule_attributes[-1] specied = (subject_category != "person") or (rule_subject_category == "person") rules.append( { "subject": rule_subject_category, "condition": condition, "condition_conjunction": condition_conjunction, "consequent": consequent, "specified": specied, } ) return rules # Generates a test about a subject given a set of rules def generate_test(attribute_groups, subject, rules, p_consquenceless=0.1): # test_attributes = random.sample(attributes, 2) test_attributes = random.sample(list(attribute_groups.keys()), 2) test_attributes_specific = [random.choice(attribute_groups[subcondition]) for subcondition in test_attributes] test_consequents = [] test_rules_used = [] for rule in rules: condition_conjunction = rule["condition_conjunction"] rule_condition = rule["condition"] rule_consequent = rule["consequent"] if rule_consequent in test_attributes: continue if condition_conjunction == "and": if set(rule_condition).issubset(test_attributes): test_rules_used.append(rule) test_consequents.append(rule_consequent) elif condition_conjunction == "or": if not set(rule_condition).isdisjoint(test_attributes): test_rules_used.append(rule) test_consequents.append(rule_consequent) if len(test_consequents) == 0 and random.random() > p_consquenceless: return generate_test(attribute_groups, subject, rules, p_consquenceless) return test_attributes, test_attributes_specific, test_consequents, test_rules_used class LanguagePatternMatchingScenario(Scenario): """ The Massive Multitask Language Understanding benchmark from this paper: https://arxiv.org/pdf/2009.03300.pdf Code is adapted from: https://github.com/hendrycks/test/blob/master/evaluate.py https://github.com/EleutherAI/lm-evaluation-harness/blob/master/lm_eval/tasks/hendrycks_test.py """ name = "mmlu" description = "Massive Multitask Language Understanding" tags = ["reasoning", "language", "pattern_matching"] def __init__(self, subject: str): self.attribute_groups, self.subjects = get_vocab() self.generic_attributes = False self.specific_category = False self.include_intermediates = True self.n_train_samples = 100 self.n_valid_samples = 100 self.n_test_samples = 100 def get_instances(self) -> List[Instance]: # Read all the instances instances = [] for sample_idx in range(self.n_train_samples + self.n_test_samples): # generic_attributes specifies that the top level attribute should always be used # e.g. "cold" instead of "chill" # specific_category specifies that the specific category should always be used # e.g. "dog" instead of "an animal" subject_category = random.choice(list(self.subjects.keys())) subject = random.choice(self.subjects[subject_category]) rules = generate_rules( self.attribute_groups, subject_category, subject, specific_category=self.specific_category ) test_attributes, test_attributes_specific, test_consequents, test_rules_used = generate_test( self.attribute_groups, subject, rules ) question = "Rules:\n" for rule in rules: question += parse_rule(rule) + "\n" test_specifier_base = generate_specifier(subject, upper=True) test_specifier_first = test_specifier_base + " " if subject_category != "person" else "" test_specifier_second = "The " if subject_category != "person" else "" test_specifier_third = "the " if subject_category != "person" else "" print_test_attributes = test_attributes if self.generic_attributes else test_attributes_specific question += "Fact:\n" question += parse_fact(subject, print_test_attributes, specifier=test_specifier_first) + "\n" if self.include_intermediates: question += "Rule(s) used:\n" for rule in test_rules_used: question += parse_rule(rule) + "\n" question += f"The following can be determined about {test_specifier_third}{subject}:\n" correct_answer = parse_fact(subject, test_consequents, specifier=test_specifier_second) if sample_idx < self.n_train_samples: cur_tag = TRAIN_TAG elif sample_idx < self.n_train_samples + self.n_valid_samples: cur_tag = VALID_TAG else: cur_tag = TEST_TAG instance = Instance( input=question, references=[Reference(output=correct_answer, tags=[CORRECT_TAG])], tags=[cur_tag], ) instances.append(instance) return instances
stanford-crfm__helm
60
60-110-56
random
copy
[ "append", "clear", "copy", "count", "extend", "index", "insert", "pop", "remove", "reverse", "sort", "__add__", "__annotations__", "__class__", "__class_getitem__", "__contains__", "__delattr__", "__delitem__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__ge__", "__getattribute__", "__getitem__", "__gt__", "__hash__", "__iadd__", "__imul__", "__init__", "__init_subclass__", "__iter__", "__le__", "__len__", "__lt__", "__module__", "__mul__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__reversed__", "__rmul__", "__setattr__", "__setitem__", "__sizeof__", "__slots__", "__str__" ]
import random from copy import copy from typing import List from common.hierarchical_logger import hlog from .scenario import Scenario, Instance, Reference, TRAIN_TAG, VALID_TAG, TEST_TAG, CORRECT_TAG def get_vocab(): subjects = { "person": ["Alice", "Bob", "Carol", "Dan", "Erin", "Frank"], "animal": [ "dog", "cat", "rabbit", "mouse", "tiger", "lion", "bear", "squirrel", "cow", "panda", "hedgehog", "elephant", "giraffe", "hippo", ], "plant": ["poppy", "dandelion", "tree", "rose", "sunflower"], } attributes = [ # 'red', 'blue', 'green', 'young', 'round', 'rough', # 'fuzzy', 'sad', 'tasty', 'soft', 'fine', 'funny', 'rich', # 'new', 'sick', 'poor', 'boring', 'powerful', # 'friendly', 'orange', 'wide', 'lost', 'yellow', # 'white', 'grey', 'black', 'pink', 'brown', 'cheerful', # 'striped', 'wild', 'shiny', # 'fluffy', 'gray', 'curly', 'busy', 'plain', 'flat', 'sleek', # 'scary', 'harmless', 'graceful' # # 'heavy', 'tall', 'short', 'light', 'long', 'fat', 'gentle', 'elegant', 'sparkly', 'great', ] attribute_groups = {attribute: [attribute] for attribute in attributes} attribute_groups.update( { "cold": ["cold", "chill", "cool"], "hot": ["hot", "warm"], "smart": ["smart", "clever", "wise", "intelligent"], "clean": ["clean", "tidy"], "small": ["small", "little", "tiny"], "big": ["big", "enormous", "giant", "huge"], "good": ["good", "kind", "nice"], "beautiful": ["beautiful", "pretty"], "red": ["red", "crimson"], "blue": ["blue", "cobalt"], "green": ["green", "viridian"], "purple": ["purple", "violet"], "boring": ["boring", "dull"], "old": ["old", "ancient", "antique"], "strong": ["strong", "powerful", "muscular"], "weak": ["weak", "frail", "fragile"], "fast": ["fast", "quick"], "slow": ["slow", "sluggish"], "bad": ["bad", "evil", "wicked", "mean"], "happy": ["happy", "elated", "glad"], } ) new_attribute_groups = copy(attribute_groups) for general_attribute, specific_attributes in attribute_groups.items(): for specific_attribute in specific_attributes: if (general_attribute != specific_attribute) and (specific_attribute in attribute_groups): del new_attribute_groups[specific_attribute] attribute_groups = new_attribute_groups return attribute_groups, subjects def generate_specifier(subject, upper=False): base_char = "A" if upper else "a" if subject[0].lower() in ["a", "e", "i", "o", "u"]: return base_char + "n" return base_char # Maps from a rule dictionary to a string def parse_rule(rule): # Rules should have the following format: # { # 'subject': 'someone', # 'condition': ['red', 'kind'], # 'condition_conjunction': 'and', # 'consequent': 'cold' # 'specified': True # } condition = f" {rule['condition_conjunction']} ".join(rule["condition"]) specified = rule["specified"] if specified: specifier = generate_specifier(rule["subject"]) return f"If {specifier} {rule['subject']} is {condition}, then the {rule['subject']} is {rule['consequent']}." return f"If {rule['subject']} is {condition}, then {rule['subject']} is {rule['consequent']}." # Maps from a set of attributes about a subject to a string def parse_fact(subject, attributes, prefix="", specifier=""): if len(attributes) == 0: return "Nothing." return f"{prefix}{specifier}{subject} is {' and '.join(attributes)}." # Generates a set of rules about a subject def generate_rules(attribute_groups, subject_category, subject, max_rules=5, specific_category=False): attributes_shuffled = list(attribute_groups.keys()).
() random.shuffle(attributes_shuffled) rules = [] hlog("Generating language pattern matching examples") while len(attributes_shuffled) > 2 and len(rules) < max_rules: rule_subject_category = subject if specific_category else random.choice([subject_category, subject]) n_rule_attributes = random.randint(2, 3) rule_attributes, attributes_shuffled = ( attributes_shuffled[:n_rule_attributes], attributes_shuffled[n_rule_attributes:], ) condition = rule_attributes[:-1] condition_conjunction = random.choice(["and", "or"]) consequent = rule_attributes[-1] specied = (subject_category != "person") or (rule_subject_category == "person") rules.append( { "subject": rule_subject_category, "condition": condition, "condition_conjunction": condition_conjunction, "consequent": consequent, "specified": specied, } ) return rules # Generates a test about a subject given a set of rules def generate_test(attribute_groups, subject, rules, p_consquenceless=0.1): # test_attributes = random.sample(attributes, 2) test_attributes = random.sample(list(attribute_groups.keys()), 2) test_attributes_specific = [random.choice(attribute_groups[subcondition]) for subcondition in test_attributes] test_consequents = [] test_rules_used = [] for rule in rules: condition_conjunction = rule["condition_conjunction"] rule_condition = rule["condition"] rule_consequent = rule["consequent"] if rule_consequent in test_attributes: continue if condition_conjunction == "and": if set(rule_condition).issubset(test_attributes): test_rules_used.append(rule) test_consequents.append(rule_consequent) elif condition_conjunction == "or": if not set(rule_condition).isdisjoint(test_attributes): test_rules_used.append(rule) test_consequents.append(rule_consequent) if len(test_consequents) == 0 and random.random() > p_consquenceless: return generate_test(attribute_groups, subject, rules, p_consquenceless) return test_attributes, test_attributes_specific, test_consequents, test_rules_used class LanguagePatternMatchingScenario(Scenario): """ The Massive Multitask Language Understanding benchmark from this paper: https://arxiv.org/pdf/2009.03300.pdf Code is adapted from: https://github.com/hendrycks/test/blob/master/evaluate.py https://github.com/EleutherAI/lm-evaluation-harness/blob/master/lm_eval/tasks/hendrycks_test.py """ name = "mmlu" description = "Massive Multitask Language Understanding" tags = ["reasoning", "language", "pattern_matching"] def __init__(self, subject: str): self.attribute_groups, self.subjects = get_vocab() self.generic_attributes = False self.specific_category = False self.include_intermediates = True self.n_train_samples = 100 self.n_valid_samples = 100 self.n_test_samples = 100 def get_instances(self) -> List[Instance]: # Read all the instances instances = [] for sample_idx in range(self.n_train_samples + self.n_test_samples): # generic_attributes specifies that the top level attribute should always be used # e.g. "cold" instead of "chill" # specific_category specifies that the specific category should always be used # e.g. "dog" instead of "an animal" subject_category = random.choice(list(self.subjects.keys())) subject = random.choice(self.subjects[subject_category]) rules = generate_rules( self.attribute_groups, subject_category, subject, specific_category=self.specific_category ) test_attributes, test_attributes_specific, test_consequents, test_rules_used = generate_test( self.attribute_groups, subject, rules ) question = "Rules:\n" for rule in rules: question += parse_rule(rule) + "\n" test_specifier_base = generate_specifier(subject, upper=True) test_specifier_first = test_specifier_base + " " if subject_category != "person" else "" test_specifier_second = "The " if subject_category != "person" else "" test_specifier_third = "the " if subject_category != "person" else "" print_test_attributes = test_attributes if self.generic_attributes else test_attributes_specific question += "Fact:\n" question += parse_fact(subject, print_test_attributes, specifier=test_specifier_first) + "\n" if self.include_intermediates: question += "Rule(s) used:\n" for rule in test_rules_used: question += parse_rule(rule) + "\n" question += f"The following can be determined about {test_specifier_third}{subject}:\n" correct_answer = parse_fact(subject, test_consequents, specifier=test_specifier_second) if sample_idx < self.n_train_samples: cur_tag = TRAIN_TAG elif sample_idx < self.n_train_samples + self.n_valid_samples: cur_tag = VALID_TAG else: cur_tag = TEST_TAG instance = Instance( input=question, references=[Reference(output=correct_answer, tags=[CORRECT_TAG])], tags=[cur_tag], ) instances.append(instance) return instances
stanford-crfm__helm
60
60-156-32
random
append
[ "append", "clear", "copy", "count", "extend", "index", "insert", "pop", "remove", "reverse", "sort", "__add__", "__annotations__", "__class__", "__class_getitem__", "__contains__", "__delattr__", "__delitem__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__ge__", "__getattribute__", "__getitem__", "__gt__", "__hash__", "__iadd__", "__imul__", "__init__", "__init_subclass__", "__iter__", "__le__", "__len__", "__lt__", "__module__", "__mul__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__reversed__", "__rmul__", "__setattr__", "__setitem__", "__sizeof__", "__slots__", "__str__" ]
import random from copy import copy from typing import List from common.hierarchical_logger import hlog from .scenario import Scenario, Instance, Reference, TRAIN_TAG, VALID_TAG, TEST_TAG, CORRECT_TAG def get_vocab(): subjects = { "person": ["Alice", "Bob", "Carol", "Dan", "Erin", "Frank"], "animal": [ "dog", "cat", "rabbit", "mouse", "tiger", "lion", "bear", "squirrel", "cow", "panda", "hedgehog", "elephant", "giraffe", "hippo", ], "plant": ["poppy", "dandelion", "tree", "rose", "sunflower"], } attributes = [ # 'red', 'blue', 'green', 'young', 'round', 'rough', # 'fuzzy', 'sad', 'tasty', 'soft', 'fine', 'funny', 'rich', # 'new', 'sick', 'poor', 'boring', 'powerful', # 'friendly', 'orange', 'wide', 'lost', 'yellow', # 'white', 'grey', 'black', 'pink', 'brown', 'cheerful', # 'striped', 'wild', 'shiny', # 'fluffy', 'gray', 'curly', 'busy', 'plain', 'flat', 'sleek', # 'scary', 'harmless', 'graceful' # # 'heavy', 'tall', 'short', 'light', 'long', 'fat', 'gentle', 'elegant', 'sparkly', 'great', ] attribute_groups = {attribute: [attribute] for attribute in attributes} attribute_groups.update( { "cold": ["cold", "chill", "cool"], "hot": ["hot", "warm"], "smart": ["smart", "clever", "wise", "intelligent"], "clean": ["clean", "tidy"], "small": ["small", "little", "tiny"], "big": ["big", "enormous", "giant", "huge"], "good": ["good", "kind", "nice"], "beautiful": ["beautiful", "pretty"], "red": ["red", "crimson"], "blue": ["blue", "cobalt"], "green": ["green", "viridian"], "purple": ["purple", "violet"], "boring": ["boring", "dull"], "old": ["old", "ancient", "antique"], "strong": ["strong", "powerful", "muscular"], "weak": ["weak", "frail", "fragile"], "fast": ["fast", "quick"], "slow": ["slow", "sluggish"], "bad": ["bad", "evil", "wicked", "mean"], "happy": ["happy", "elated", "glad"], } ) new_attribute_groups = copy(attribute_groups) for general_attribute, specific_attributes in attribute_groups.items(): for specific_attribute in specific_attributes: if (general_attribute != specific_attribute) and (specific_attribute in attribute_groups): del new_attribute_groups[specific_attribute] attribute_groups = new_attribute_groups return attribute_groups, subjects def generate_specifier(subject, upper=False): base_char = "A" if upper else "a" if subject[0].lower() in ["a", "e", "i", "o", "u"]: return base_char + "n" return base_char # Maps from a rule dictionary to a string def parse_rule(rule): # Rules should have the following format: # { # 'subject': 'someone', # 'condition': ['red', 'kind'], # 'condition_conjunction': 'and', # 'consequent': 'cold' # 'specified': True # } condition = f" {rule['condition_conjunction']} ".join(rule["condition"]) specified = rule["specified"] if specified: specifier = generate_specifier(rule["subject"]) return f"If {specifier} {rule['subject']} is {condition}, then the {rule['subject']} is {rule['consequent']}." return f"If {rule['subject']} is {condition}, then {rule['subject']} is {rule['consequent']}." # Maps from a set of attributes about a subject to a string def parse_fact(subject, attributes, prefix="", specifier=""): if len(attributes) == 0: return "Nothing." return f"{prefix}{specifier}{subject} is {' and '.join(attributes)}." # Generates a set of rules about a subject def generate_rules(attribute_groups, subject_category, subject, max_rules=5, specific_category=False): attributes_shuffled = list(attribute_groups.keys()).copy() random.shuffle(attributes_shuffled) rules = [] hlog("Generating language pattern matching examples") while len(attributes_shuffled) > 2 and len(rules) < max_rules: rule_subject_category = subject if specific_category else random.choice([subject_category, subject]) n_rule_attributes = random.randint(2, 3) rule_attributes, attributes_shuffled = ( attributes_shuffled[:n_rule_attributes], attributes_shuffled[n_rule_attributes:], ) condition = rule_attributes[:-1] condition_conjunction = random.choice(["and", "or"]) consequent = rule_attributes[-1] specied = (subject_category != "person") or (rule_subject_category == "person") rules.append( { "subject": rule_subject_category, "condition": condition, "condition_conjunction": condition_conjunction, "consequent": consequent, "specified": specied, } ) return rules # Generates a test about a subject given a set of rules def generate_test(attribute_groups, subject, rules, p_consquenceless=0.1): # test_attributes = random.sample(attributes, 2) test_attributes = random.sample(list(attribute_groups.keys()), 2) test_attributes_specific = [random.choice(attribute_groups[subcondition]) for subcondition in test_attributes] test_consequents = [] test_rules_used = [] for rule in rules: condition_conjunction = rule["condition_conjunction"] rule_condition = rule["condition"] rule_consequent = rule["consequent"] if rule_consequent in test_attributes: continue if condition_conjunction == "and": if set(rule_condition).issubset(test_attributes): test_rules_used.append(rule) test_consequents.append(rule_consequent) elif condition_conjunction == "or": if not set(rule_condition).isdisjoint(test_attributes): test_rules_used.
(rule) test_consequents.append(rule_consequent) if len(test_consequents) == 0 and random.random() > p_consquenceless: return generate_test(attribute_groups, subject, rules, p_consquenceless) return test_attributes, test_attributes_specific, test_consequents, test_rules_used class LanguagePatternMatchingScenario(Scenario): """ The Massive Multitask Language Understanding benchmark from this paper: https://arxiv.org/pdf/2009.03300.pdf Code is adapted from: https://github.com/hendrycks/test/blob/master/evaluate.py https://github.com/EleutherAI/lm-evaluation-harness/blob/master/lm_eval/tasks/hendrycks_test.py """ name = "mmlu" description = "Massive Multitask Language Understanding" tags = ["reasoning", "language", "pattern_matching"] def __init__(self, subject: str): self.attribute_groups, self.subjects = get_vocab() self.generic_attributes = False self.specific_category = False self.include_intermediates = True self.n_train_samples = 100 self.n_valid_samples = 100 self.n_test_samples = 100 def get_instances(self) -> List[Instance]: # Read all the instances instances = [] for sample_idx in range(self.n_train_samples + self.n_test_samples): # generic_attributes specifies that the top level attribute should always be used # e.g. "cold" instead of "chill" # specific_category specifies that the specific category should always be used # e.g. "dog" instead of "an animal" subject_category = random.choice(list(self.subjects.keys())) subject = random.choice(self.subjects[subject_category]) rules = generate_rules( self.attribute_groups, subject_category, subject, specific_category=self.specific_category ) test_attributes, test_attributes_specific, test_consequents, test_rules_used = generate_test( self.attribute_groups, subject, rules ) question = "Rules:\n" for rule in rules: question += parse_rule(rule) + "\n" test_specifier_base = generate_specifier(subject, upper=True) test_specifier_first = test_specifier_base + " " if subject_category != "person" else "" test_specifier_second = "The " if subject_category != "person" else "" test_specifier_third = "the " if subject_category != "person" else "" print_test_attributes = test_attributes if self.generic_attributes else test_attributes_specific question += "Fact:\n" question += parse_fact(subject, print_test_attributes, specifier=test_specifier_first) + "\n" if self.include_intermediates: question += "Rule(s) used:\n" for rule in test_rules_used: question += parse_rule(rule) + "\n" question += f"The following can be determined about {test_specifier_third}{subject}:\n" correct_answer = parse_fact(subject, test_consequents, specifier=test_specifier_second) if sample_idx < self.n_train_samples: cur_tag = TRAIN_TAG elif sample_idx < self.n_train_samples + self.n_valid_samples: cur_tag = VALID_TAG else: cur_tag = TEST_TAG instance = Instance( input=question, references=[Reference(output=correct_answer, tags=[CORRECT_TAG])], tags=[cur_tag], ) instances.append(instance) return instances
stanford-crfm__helm
60
60-180-13
infile
attribute_groups
[ "attribute_groups", "description", "generic_attributes", "get_instances", "include_intermediates", "n_test_samples", "n_train_samples", "n_valid_samples", "name", "output_path", "render_lines", "specific_category", "subjects", "tags", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init__", "__init_subclass__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__slots__", "__str__" ]
import random from copy import copy from typing import List from common.hierarchical_logger import hlog from .scenario import Scenario, Instance, Reference, TRAIN_TAG, VALID_TAG, TEST_TAG, CORRECT_TAG def get_vocab(): subjects = { "person": ["Alice", "Bob", "Carol", "Dan", "Erin", "Frank"], "animal": [ "dog", "cat", "rabbit", "mouse", "tiger", "lion", "bear", "squirrel", "cow", "panda", "hedgehog", "elephant", "giraffe", "hippo", ], "plant": ["poppy", "dandelion", "tree", "rose", "sunflower"], } attributes = [ # 'red', 'blue', 'green', 'young', 'round', 'rough', # 'fuzzy', 'sad', 'tasty', 'soft', 'fine', 'funny', 'rich', # 'new', 'sick', 'poor', 'boring', 'powerful', # 'friendly', 'orange', 'wide', 'lost', 'yellow', # 'white', 'grey', 'black', 'pink', 'brown', 'cheerful', # 'striped', 'wild', 'shiny', # 'fluffy', 'gray', 'curly', 'busy', 'plain', 'flat', 'sleek', # 'scary', 'harmless', 'graceful' # # 'heavy', 'tall', 'short', 'light', 'long', 'fat', 'gentle', 'elegant', 'sparkly', 'great', ] attribute_groups = {attribute: [attribute] for attribute in attributes} attribute_groups.update( { "cold": ["cold", "chill", "cool"], "hot": ["hot", "warm"], "smart": ["smart", "clever", "wise", "intelligent"], "clean": ["clean", "tidy"], "small": ["small", "little", "tiny"], "big": ["big", "enormous", "giant", "huge"], "good": ["good", "kind", "nice"], "beautiful": ["beautiful", "pretty"], "red": ["red", "crimson"], "blue": ["blue", "cobalt"], "green": ["green", "viridian"], "purple": ["purple", "violet"], "boring": ["boring", "dull"], "old": ["old", "ancient", "antique"], "strong": ["strong", "powerful", "muscular"], "weak": ["weak", "frail", "fragile"], "fast": ["fast", "quick"], "slow": ["slow", "sluggish"], "bad": ["bad", "evil", "wicked", "mean"], "happy": ["happy", "elated", "glad"], } ) new_attribute_groups = copy(attribute_groups) for general_attribute, specific_attributes in attribute_groups.items(): for specific_attribute in specific_attributes: if (general_attribute != specific_attribute) and (specific_attribute in attribute_groups): del new_attribute_groups[specific_attribute] attribute_groups = new_attribute_groups return attribute_groups, subjects def generate_specifier(subject, upper=False): base_char = "A" if upper else "a" if subject[0].lower() in ["a", "e", "i", "o", "u"]: return base_char + "n" return base_char # Maps from a rule dictionary to a string def parse_rule(rule): # Rules should have the following format: # { # 'subject': 'someone', # 'condition': ['red', 'kind'], # 'condition_conjunction': 'and', # 'consequent': 'cold' # 'specified': True # } condition = f" {rule['condition_conjunction']} ".join(rule["condition"]) specified = rule["specified"] if specified: specifier = generate_specifier(rule["subject"]) return f"If {specifier} {rule['subject']} is {condition}, then the {rule['subject']} is {rule['consequent']}." return f"If {rule['subject']} is {condition}, then {rule['subject']} is {rule['consequent']}." # Maps from a set of attributes about a subject to a string def parse_fact(subject, attributes, prefix="", specifier=""): if len(attributes) == 0: return "Nothing." return f"{prefix}{specifier}{subject} is {' and '.join(attributes)}." # Generates a set of rules about a subject def generate_rules(attribute_groups, subject_category, subject, max_rules=5, specific_category=False): attributes_shuffled = list(attribute_groups.keys()).copy() random.shuffle(attributes_shuffled) rules = [] hlog("Generating language pattern matching examples") while len(attributes_shuffled) > 2 and len(rules) < max_rules: rule_subject_category = subject if specific_category else random.choice([subject_category, subject]) n_rule_attributes = random.randint(2, 3) rule_attributes, attributes_shuffled = ( attributes_shuffled[:n_rule_attributes], attributes_shuffled[n_rule_attributes:], ) condition = rule_attributes[:-1] condition_conjunction = random.choice(["and", "or"]) consequent = rule_attributes[-1] specied = (subject_category != "person") or (rule_subject_category == "person") rules.append( { "subject": rule_subject_category, "condition": condition, "condition_conjunction": condition_conjunction, "consequent": consequent, "specified": specied, } ) return rules # Generates a test about a subject given a set of rules def generate_test(attribute_groups, subject, rules, p_consquenceless=0.1): # test_attributes = random.sample(attributes, 2) test_attributes = random.sample(list(attribute_groups.keys()), 2) test_attributes_specific = [random.choice(attribute_groups[subcondition]) for subcondition in test_attributes] test_consequents = [] test_rules_used = [] for rule in rules: condition_conjunction = rule["condition_conjunction"] rule_condition = rule["condition"] rule_consequent = rule["consequent"] if rule_consequent in test_attributes: continue if condition_conjunction == "and": if set(rule_condition).issubset(test_attributes): test_rules_used.append(rule) test_consequents.append(rule_consequent) elif condition_conjunction == "or": if not set(rule_condition).isdisjoint(test_attributes): test_rules_used.append(rule) test_consequents.append(rule_consequent) if len(test_consequents) == 0 and random.random() > p_consquenceless: return generate_test(attribute_groups, subject, rules, p_consquenceless) return test_attributes, test_attributes_specific, test_consequents, test_rules_used class LanguagePatternMatchingScenario(Scenario): """ The Massive Multitask Language Understanding benchmark from this paper: https://arxiv.org/pdf/2009.03300.pdf Code is adapted from: https://github.com/hendrycks/test/blob/master/evaluate.py https://github.com/EleutherAI/lm-evaluation-harness/blob/master/lm_eval/tasks/hendrycks_test.py """ name = "mmlu" description = "Massive Multitask Language Understanding" tags = ["reasoning", "language", "pattern_matching"] def __init__(self, subject: str): self.
, self.subjects = get_vocab() self.generic_attributes = False self.specific_category = False self.include_intermediates = True self.n_train_samples = 100 self.n_valid_samples = 100 self.n_test_samples = 100 def get_instances(self) -> List[Instance]: # Read all the instances instances = [] for sample_idx in range(self.n_train_samples + self.n_test_samples): # generic_attributes specifies that the top level attribute should always be used # e.g. "cold" instead of "chill" # specific_category specifies that the specific category should always be used # e.g. "dog" instead of "an animal" subject_category = random.choice(list(self.subjects.keys())) subject = random.choice(self.subjects[subject_category]) rules = generate_rules( self.attribute_groups, subject_category, subject, specific_category=self.specific_category ) test_attributes, test_attributes_specific, test_consequents, test_rules_used = generate_test( self.attribute_groups, subject, rules ) question = "Rules:\n" for rule in rules: question += parse_rule(rule) + "\n" test_specifier_base = generate_specifier(subject, upper=True) test_specifier_first = test_specifier_base + " " if subject_category != "person" else "" test_specifier_second = "The " if subject_category != "person" else "" test_specifier_third = "the " if subject_category != "person" else "" print_test_attributes = test_attributes if self.generic_attributes else test_attributes_specific question += "Fact:\n" question += parse_fact(subject, print_test_attributes, specifier=test_specifier_first) + "\n" if self.include_intermediates: question += "Rule(s) used:\n" for rule in test_rules_used: question += parse_rule(rule) + "\n" question += f"The following can be determined about {test_specifier_third}{subject}:\n" correct_answer = parse_fact(subject, test_consequents, specifier=test_specifier_second) if sample_idx < self.n_train_samples: cur_tag = TRAIN_TAG elif sample_idx < self.n_train_samples + self.n_valid_samples: cur_tag = VALID_TAG else: cur_tag = TEST_TAG instance = Instance( input=question, references=[Reference(output=correct_answer, tags=[CORRECT_TAG])], tags=[cur_tag], ) instances.append(instance) return instances
stanford-crfm__helm
60
60-180-36
infile
subjects
[ "attribute_groups", "description", "generic_attributes", "get_instances", "include_intermediates", "n_test_samples", "n_train_samples", "n_valid_samples", "name", "output_path", "render_lines", "specific_category", "subjects", "tags", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init__", "__init_subclass__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__slots__", "__str__" ]
import random from copy import copy from typing import List from common.hierarchical_logger import hlog from .scenario import Scenario, Instance, Reference, TRAIN_TAG, VALID_TAG, TEST_TAG, CORRECT_TAG def get_vocab(): subjects = { "person": ["Alice", "Bob", "Carol", "Dan", "Erin", "Frank"], "animal": [ "dog", "cat", "rabbit", "mouse", "tiger", "lion", "bear", "squirrel", "cow", "panda", "hedgehog", "elephant", "giraffe", "hippo", ], "plant": ["poppy", "dandelion", "tree", "rose", "sunflower"], } attributes = [ # 'red', 'blue', 'green', 'young', 'round', 'rough', # 'fuzzy', 'sad', 'tasty', 'soft', 'fine', 'funny', 'rich', # 'new', 'sick', 'poor', 'boring', 'powerful', # 'friendly', 'orange', 'wide', 'lost', 'yellow', # 'white', 'grey', 'black', 'pink', 'brown', 'cheerful', # 'striped', 'wild', 'shiny', # 'fluffy', 'gray', 'curly', 'busy', 'plain', 'flat', 'sleek', # 'scary', 'harmless', 'graceful' # # 'heavy', 'tall', 'short', 'light', 'long', 'fat', 'gentle', 'elegant', 'sparkly', 'great', ] attribute_groups = {attribute: [attribute] for attribute in attributes} attribute_groups.update( { "cold": ["cold", "chill", "cool"], "hot": ["hot", "warm"], "smart": ["smart", "clever", "wise", "intelligent"], "clean": ["clean", "tidy"], "small": ["small", "little", "tiny"], "big": ["big", "enormous", "giant", "huge"], "good": ["good", "kind", "nice"], "beautiful": ["beautiful", "pretty"], "red": ["red", "crimson"], "blue": ["blue", "cobalt"], "green": ["green", "viridian"], "purple": ["purple", "violet"], "boring": ["boring", "dull"], "old": ["old", "ancient", "antique"], "strong": ["strong", "powerful", "muscular"], "weak": ["weak", "frail", "fragile"], "fast": ["fast", "quick"], "slow": ["slow", "sluggish"], "bad": ["bad", "evil", "wicked", "mean"], "happy": ["happy", "elated", "glad"], } ) new_attribute_groups = copy(attribute_groups) for general_attribute, specific_attributes in attribute_groups.items(): for specific_attribute in specific_attributes: if (general_attribute != specific_attribute) and (specific_attribute in attribute_groups): del new_attribute_groups[specific_attribute] attribute_groups = new_attribute_groups return attribute_groups, subjects def generate_specifier(subject, upper=False): base_char = "A" if upper else "a" if subject[0].lower() in ["a", "e", "i", "o", "u"]: return base_char + "n" return base_char # Maps from a rule dictionary to a string def parse_rule(rule): # Rules should have the following format: # { # 'subject': 'someone', # 'condition': ['red', 'kind'], # 'condition_conjunction': 'and', # 'consequent': 'cold' # 'specified': True # } condition = f" {rule['condition_conjunction']} ".join(rule["condition"]) specified = rule["specified"] if specified: specifier = generate_specifier(rule["subject"]) return f"If {specifier} {rule['subject']} is {condition}, then the {rule['subject']} is {rule['consequent']}." return f"If {rule['subject']} is {condition}, then {rule['subject']} is {rule['consequent']}." # Maps from a set of attributes about a subject to a string def parse_fact(subject, attributes, prefix="", specifier=""): if len(attributes) == 0: return "Nothing." return f"{prefix}{specifier}{subject} is {' and '.join(attributes)}." # Generates a set of rules about a subject def generate_rules(attribute_groups, subject_category, subject, max_rules=5, specific_category=False): attributes_shuffled = list(attribute_groups.keys()).copy() random.shuffle(attributes_shuffled) rules = [] hlog("Generating language pattern matching examples") while len(attributes_shuffled) > 2 and len(rules) < max_rules: rule_subject_category = subject if specific_category else random.choice([subject_category, subject]) n_rule_attributes = random.randint(2, 3) rule_attributes, attributes_shuffled = ( attributes_shuffled[:n_rule_attributes], attributes_shuffled[n_rule_attributes:], ) condition = rule_attributes[:-1] condition_conjunction = random.choice(["and", "or"]) consequent = rule_attributes[-1] specied = (subject_category != "person") or (rule_subject_category == "person") rules.append( { "subject": rule_subject_category, "condition": condition, "condition_conjunction": condition_conjunction, "consequent": consequent, "specified": specied, } ) return rules # Generates a test about a subject given a set of rules def generate_test(attribute_groups, subject, rules, p_consquenceless=0.1): # test_attributes = random.sample(attributes, 2) test_attributes = random.sample(list(attribute_groups.keys()), 2) test_attributes_specific = [random.choice(attribute_groups[subcondition]) for subcondition in test_attributes] test_consequents = [] test_rules_used = [] for rule in rules: condition_conjunction = rule["condition_conjunction"] rule_condition = rule["condition"] rule_consequent = rule["consequent"] if rule_consequent in test_attributes: continue if condition_conjunction == "and": if set(rule_condition).issubset(test_attributes): test_rules_used.append(rule) test_consequents.append(rule_consequent) elif condition_conjunction == "or": if not set(rule_condition).isdisjoint(test_attributes): test_rules_used.append(rule) test_consequents.append(rule_consequent) if len(test_consequents) == 0 and random.random() > p_consquenceless: return generate_test(attribute_groups, subject, rules, p_consquenceless) return test_attributes, test_attributes_specific, test_consequents, test_rules_used class LanguagePatternMatchingScenario(Scenario): """ The Massive Multitask Language Understanding benchmark from this paper: https://arxiv.org/pdf/2009.03300.pdf Code is adapted from: https://github.com/hendrycks/test/blob/master/evaluate.py https://github.com/EleutherAI/lm-evaluation-harness/blob/master/lm_eval/tasks/hendrycks_test.py """ name = "mmlu" description = "Massive Multitask Language Understanding" tags = ["reasoning", "language", "pattern_matching"] def __init__(self, subject: str): self.attribute_groups, self.
= get_vocab() self.generic_attributes = False self.specific_category = False self.include_intermediates = True self.n_train_samples = 100 self.n_valid_samples = 100 self.n_test_samples = 100 def get_instances(self) -> List[Instance]: # Read all the instances instances = [] for sample_idx in range(self.n_train_samples + self.n_test_samples): # generic_attributes specifies that the top level attribute should always be used # e.g. "cold" instead of "chill" # specific_category specifies that the specific category should always be used # e.g. "dog" instead of "an animal" subject_category = random.choice(list(self.subjects.keys())) subject = random.choice(self.subjects[subject_category]) rules = generate_rules( self.attribute_groups, subject_category, subject, specific_category=self.specific_category ) test_attributes, test_attributes_specific, test_consequents, test_rules_used = generate_test( self.attribute_groups, subject, rules ) question = "Rules:\n" for rule in rules: question += parse_rule(rule) + "\n" test_specifier_base = generate_specifier(subject, upper=True) test_specifier_first = test_specifier_base + " " if subject_category != "person" else "" test_specifier_second = "The " if subject_category != "person" else "" test_specifier_third = "the " if subject_category != "person" else "" print_test_attributes = test_attributes if self.generic_attributes else test_attributes_specific question += "Fact:\n" question += parse_fact(subject, print_test_attributes, specifier=test_specifier_first) + "\n" if self.include_intermediates: question += "Rule(s) used:\n" for rule in test_rules_used: question += parse_rule(rule) + "\n" question += f"The following can be determined about {test_specifier_third}{subject}:\n" correct_answer = parse_fact(subject, test_consequents, specifier=test_specifier_second) if sample_idx < self.n_train_samples: cur_tag = TRAIN_TAG elif sample_idx < self.n_train_samples + self.n_valid_samples: cur_tag = VALID_TAG else: cur_tag = TEST_TAG instance = Instance( input=question, references=[Reference(output=correct_answer, tags=[CORRECT_TAG])], tags=[cur_tag], ) instances.append(instance) return instances
stanford-crfm__helm
63
63-102-17
infile
_state
[ "active_server_limit", "add_header", "admin_users", "allow_named_servers", "app", "append_query_parameters", "application", "auth_to_user", "authenticate", "authenticate_prometheus", "authenticator", "authorize_redirect", "base_url", "check_etag_header", "check_xsrf_cookie", "clear", "clear_all_cookies", "clear_cookie", "clear_header", "clear_login_cookie", "compute_etag", "concurrent_spawn_limit", "config", "content_security_policy", "cookie_max_age_days", "cookies", "create_signed_value", "create_template_loader", "csp_report_uri", "current_user", "data_received", "db", "decode_argument", "default_url", "delete", "detach", "domain", "eventlog", "expanded_scopes", "extra_error_html", "find_user", "finish", "flush", "get", "get_accessible_services", "get_argument", "get_arguments", "get_auth_http_client", "get_auth_token", "get_body_argument", "get_body_arguments", "get_browser_locale", "get_content_type", "get_cookie", "get_current_user", "get_current_user_cookie", "get_current_user_named_server_limit", "get_current_user_token", "get_login_url", "get_next_url", "get_query_argument", "get_query_arguments", "get_scope_filter", "get_secure_cookie", "get_secure_cookie_key_version", "get_session_cookie", "get_signed_cookie", "get_signed_cookie_key_version", "get_state", "get_status", "get_template", "get_template_namespace", "get_template_path", "get_token", "get_user_locale", "has_scope", "head", "hub", "initialize", "locale", "log", "log_exception", "login_user", "named_server_limit_per_user", "oauth2_request", "oauth_provider", "on_connection_close", "on_finish", "options", "parsed_scopes", "patch", "path_args", "path_kwargs", "post", "prepare", "proxy", "public_url", "put", "redirect", "redirect_to_server", "refresh_auth", "render", "render_embed_css", "render_embed_js", "render_linked_css", "render_linked_js", "render_string", "render_template", "request", "require_setting", "reverse_url", "send_error", "services", "set_cookie", "set_default_headers", "set_etag_header", "set_header", "set_hub_cookie", "set_login_cookie", "set_secure_cookie", "set_service_cookie", "set_session_cookie", "set_signed_cookie", "set_state_cookie", "set_status", "settings", "slow_spawn_timeout", "slow_stop_timeout", "spawn_home_error", "spawn_single_user", "spawner_class", "static_url", "statsd", "stop_single_user", "subdomain_host", "SUPPORTED_METHODS", "template_namespace", "ui", "user_from_username", "user_stopped", "users", "version_hash", "write", "write_error", "xsrf_form_html", "xsrf_token", "_accept_cookie_auth", "_accept_token_auth", "_active_modules", "_auto_finish", "_break_cycles", "_clear_representation_headers", "_convert_header_value", "_current_user", "_decode_xsrf_token", "_execute", "_finished", "_get_argument", "_get_arguments", "_get_raw_xsrf_token", "_handle_request_exception", "_headers", "_headers_written", "_initialize", "_INVALID_HEADER_CHAR_RE", "_jupyterhub_user", "_locale", "_log", "_new_cookie", "_OAUTH_ACCESS_TOKEN_URL", "_OAUTH_AUTHORIZE_URL", "_oauth_request_token_url", "_OAUTH_USERINFO_URL", "_prepared_future", "_raw_xsrf_token", "_reason", "_record_activity", "_refreshed_users", "_remove_control_chars_regex", "_request_summary", "_resolve_roles_and_scopes", "_session_id", "_set_cookie", "_set_user_cookie", "_state", "_status_code", "_stream_request_body", "_template_loader_lock", "_template_loaders", "_token_authenticated", "_transforms", "_ui_method", "_ui_module", "_unimplemented_method", "_user_for_cookie", "_user_from_orm", "_validate_next_url", "_write_buffer", "_xsrf_safe_methods", "_xsrf_token", "_xsrf_token_id", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init__", "__init_subclass__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__slots__", "__str__" ]
""" Base classes for Custom Authenticator to use OAuth with JupyterHub Most of the code c/o Kyle Kelley (@rgbkrk) """ import base64 import json import os import uuid from urllib.parse import quote from urllib.parse import urlparse from urllib.parse import urlunparse from jupyterhub.auth import Authenticator from jupyterhub.handlers import BaseHandler from jupyterhub.handlers import LogoutHandler from jupyterhub.utils import url_path_join from tornado import web from tornado.auth import OAuth2Mixin from tornado.httpclient import AsyncHTTPClient from tornado.httpclient import HTTPClientError from tornado.log import app_log from traitlets import Any from traitlets import Bool from traitlets import default from traitlets import Dict from traitlets import List from traitlets import Unicode def guess_callback_uri(protocol, host, hub_server_url): return '{proto}://{host}{path}'.format( proto=protocol, host=host, path=url_path_join(hub_server_url, 'oauth_callback') ) STATE_COOKIE_NAME = 'oauthenticator-state' def _serialize_state(state): """Serialize OAuth state to a base64 string after passing through JSON""" json_state = json.dumps(state) return base64.urlsafe_b64encode(json_state.encode('utf8')).decode('ascii') def _deserialize_state(b64_state): """Deserialize OAuth state as serialized in _serialize_state""" if isinstance(b64_state, str): b64_state = b64_state.encode('ascii') try: json_state = base64.urlsafe_b64decode(b64_state).decode('utf8') except ValueError: app_log.error("Failed to b64-decode state: %r", b64_state) return {} try: return json.loads(json_state) except ValueError: app_log.error("Failed to json-decode state: %r", json_state) return {} class OAuthLoginHandler(OAuth2Mixin, BaseHandler): """Base class for OAuth login handler Typically subclasses will need """ # these URLs are part of the OAuth2Mixin API # get them from the Authenticator object @property def _OAUTH_AUTHORIZE_URL(self): return self.authenticator.authorize_url @property def _OAUTH_ACCESS_TOKEN_URL(self): return self.authenticator.token_url @property def _OAUTH_USERINFO_URL(self): return self.authenticator.userdata_url def set_state_cookie(self, state): self._set_cookie(STATE_COOKIE_NAME, state, expires_days=1, httponly=True) _state = None def get_state(self): next_url = original_next_url = self.get_argument('next', None) if next_url: # avoid browsers treating \ as / next_url = next_url.replace('\\', quote('\\')) # disallow hostname-having urls, # force absolute path redirect urlinfo = urlparse(next_url) next_url = urlinfo._replace( scheme='', netloc='', path='/' + urlinfo.path.lstrip('/') ).geturl() if next_url != original_next_url: self.log.warning( "Ignoring next_url %r, using %r", original_next_url, next_url ) if self._state is None: self.
= _serialize_state( {'state_id': uuid.uuid4().hex, 'next_url': next_url} ) return self._state def get(self): redirect_uri = self.authenticator.get_callback_url(self) extra_params = self.authenticator.extra_authorize_params.copy() self.log.info('OAuth redirect: %r', redirect_uri) state = self.get_state() self.set_state_cookie(state) extra_params['state'] = state self.authorize_redirect( redirect_uri=redirect_uri, client_id=self.authenticator.client_id, scope=self.authenticator.scope, extra_params=extra_params, response_type='code', ) class OAuthCallbackHandler(BaseHandler): """Basic handler for OAuth callback. Calls authenticator to verify username.""" _state_cookie = None def get_state_cookie(self): """Get OAuth state from cookies To be compared with the value in redirect URL """ if self._state_cookie is None: self._state_cookie = ( self.get_secure_cookie(STATE_COOKIE_NAME) or b'' ).decode('utf8', 'replace') self.clear_cookie(STATE_COOKIE_NAME) return self._state_cookie def get_state_url(self): """Get OAuth state from URL parameters to be compared with the value in cookies """ return self.get_argument("state") def check_state(self): """Verify OAuth state compare value in cookie with redirect url param """ cookie_state = self.get_state_cookie() url_state = self.get_state_url() if not cookie_state: raise web.HTTPError(400, "OAuth state missing from cookies") if not url_state: raise web.HTTPError(400, "OAuth state missing from URL") if cookie_state != url_state: self.log.warning("OAuth state mismatch: %s != %s", cookie_state, url_state) raise web.HTTPError(400, "OAuth state mismatch") def check_error(self): """Check the OAuth code""" error = self.get_argument("error", False) if error: message = self.get_argument("error_description", error) raise web.HTTPError(400, "OAuth error: %s" % message) def check_code(self): """Check the OAuth code""" if not self.get_argument("code", False): raise web.HTTPError(400, "OAuth callback made without a code") def check_arguments(self): """Validate the arguments of the redirect Default: - check for oauth-standard error, error_description arguments - check that there's a code - check that state matches """ self.check_error() self.check_code() self.check_state() def append_query_parameters(self, url, exclude=None): """JupyterHub 1.2 appends query parameters by default in get_next_url This is not appropriate for oauth callback handlers, where params are oauth state, code, etc. Override the method used to append parameters to next_url to not preserve any parameters """ return url def get_next_url(self, user=None): """Get the redirect target from the state field""" state = self.get_state_url() if state: next_url = _deserialize_state(state).get('next_url') if next_url: return next_url # JupyterHub 0.8 adds default .get_next_url for a fallback if hasattr(BaseHandler, 'get_next_url'): return super().get_next_url(user) return url_path_join(self.hub.server.base_url, 'home') async def _login_user_pre_08(self): """login_user simplifies the login+cookie+auth_state process in JupyterHub 0.8 _login_user_07 is for backward-compatibility with JupyterHub 0.7 """ user_info = await self.authenticator.get_authenticated_user(self, None) if user_info is None: return if isinstance(user_info, dict): username = user_info['name'] else: username = user_info user = self.user_from_username(username) self.set_login_cookie(user) return user if not hasattr(BaseHandler, 'login_user'): # JupyterHub 0.7 doesn't have .login_user login_user = _login_user_pre_08 async def get(self): self.check_arguments() user = await self.login_user() if user is None: # todo: custom error page? raise web.HTTPError(403) self.redirect(self.get_next_url(user)) class OAuthLogoutHandler(LogoutHandler): async def handle_logout(self): self.clear_cookie(STATE_COOKIE_NAME) async def render_logout_page(self): if self.authenticator.logout_redirect_url: self.redirect(self.authenticator.logout_redirect_url) return return await super().render_logout_page() class OAuthenticator(Authenticator): """Base class for OAuthenticators Subclasses must override: login_service (string identifying the service provider) authenticate (method takes one arg - the request handler handling the oauth callback) """ login_handler = OAuthLoginHandler callback_handler = OAuthCallbackHandler logout_handler = OAuthLogoutHandler authorize_url = Unicode( config=True, help="""The authenticate url for initiating oauth""" ) @default("authorize_url") def _authorize_url_default(self): return os.environ.get("OAUTH2_AUTHORIZE_URL", "") token_url = Unicode( config=True, help="""The url retrieving an access token at the completion of oauth""", ) @default("token_url") def _token_url_default(self): return os.environ.get("OAUTH2_TOKEN_URL", "") userdata_url = Unicode( config=True, help="""The url for retrieving user data with a completed access token""", ) @default("userdata_url") def _userdata_url_default(self): return os.environ.get("OAUTH2_USERDATA_URL", "") logout_redirect_url = Unicode(config=True, help="""URL for logging out of Auth0""") @default("logout_redirect_url") def _logout_redirect_url_default(self): return os.getenv("OAUTH_LOGOUT_REDIRECT_URL", "") scope = List( Unicode(), config=True, help="""The OAuth scopes to request. See the OAuth documentation of your OAuth provider for options. For GitHub in particular, you can see github_scopes.md in this repo. """, ) extra_authorize_params = Dict( config=True, help="""Extra GET params to send along with the initial OAuth request to the OAuth provider.""", ) login_service = 'override in subclass' oauth_callback_url = Unicode( os.getenv('OAUTH_CALLBACK_URL', ''), config=True, help="""Callback URL to use. Typically `https://{host}/hub/oauth_callback`""", ) client_id_env = '' client_id = Unicode(config=True) def _client_id_default(self): if self.client_id_env: client_id = os.getenv(self.client_id_env, '') if client_id: return client_id return os.getenv('OAUTH_CLIENT_ID', '') client_secret_env = '' client_secret = Unicode(config=True) def _client_secret_default(self): if self.client_secret_env: client_secret = os.getenv(self.client_secret_env, '') if client_secret: return client_secret return os.getenv('OAUTH_CLIENT_SECRET', '') validate_server_cert_env = 'OAUTH_TLS_VERIFY' validate_server_cert = Bool(config=True) def _validate_server_cert_default(self): env_value = os.getenv(self.validate_server_cert_env, '') if env_value == '0': return False else: return True http_client = Any() @default("http_client") def _default_http_client(self): return AsyncHTTPClient() async def fetch(self, req, label="fetching", parse_json=True, **kwargs): """Wrapper for http requests logs error responses, parses successful JSON responses Args: req: tornado HTTPRequest label (str): label describing what is happening, used in log message when the request fails. **kwargs: remaining keyword args passed to underlying `client.fetch(req, **kwargs)` Returns: r: parsed JSON response """ try: resp = await self.http_client.fetch(req, **kwargs) except HTTPClientError as e: if e.response: # Log failed response message for debugging purposes message = e.response.body.decode("utf8", "replace") try: # guess json, reformat for readability json_message = json.loads(message) except ValueError: # not json pass else: # reformat json log message for readability message = json.dumps(json_message, sort_keys=True, indent=1) else: # didn't get a response, e.g. connection error message = str(e) # log url without query params url = urlunparse(urlparse(req.url)._replace(query="")) app_log.error(f"Error {label} {e.code} {req.method} {url}: {message}") raise e else: if parse_json: if resp.body: return json.loads(resp.body.decode('utf8', 'replace')) else: # empty body is None return None else: return resp def login_url(self, base_url): return url_path_join(base_url, 'oauth_login') def logout_url(self, base_url): return url_path_join(base_url, 'logout') def get_callback_url(self, handler=None): """Get my OAuth redirect URL Either from config or guess based on the current request. """ if self.oauth_callback_url: return self.oauth_callback_url elif handler: return guess_callback_uri( handler.request.protocol, handler.request.host, handler.hub.server.base_url, ) else: raise ValueError( "Specify callback oauth_callback_url or give me a handler to guess with" ) def get_handlers(self, app): return [ (r'/oauth_login', self.login_handler), (r'/oauth_callback', self.callback_handler), (r'/logout', self.logout_handler), ] async def authenticate(self, handler, data=None): raise NotImplementedError() _deprecated_oauth_aliases = {} def _deprecated_oauth_trait(self, change): """observer for deprecated traits""" old_attr = change.name new_attr, version = self._deprecated_oauth_aliases.get(old_attr) new_value = getattr(self, new_attr) if new_value != change.new: # only warn if different # protects backward-compatible config from warnings # if they set the same value under both names self.log.warning( "{cls}.{old} is deprecated in {cls} {version}, use {cls}.{new} instead".format( cls=self.__class__.__name__, old=old_attr, new=new_attr, version=version, ) ) setattr(self, new_attr, change.new) def __init__(self, **kwargs): # observe deprecated config names in oauthenticator if self._deprecated_oauth_aliases: self.observe( self._deprecated_oauth_trait, names=list(self._deprecated_oauth_aliases) ) super().__init__(**kwargs)
coffeateam__coffea-casa
63
63-108-28
infile
authenticator
[ "active_server_limit", "add_header", "admin_users", "allow_named_servers", "app", "append_query_parameters", "application", "auth_to_user", "authenticate", "authenticate_prometheus", "authenticator", "authorize_redirect", "base_url", "check_etag_header", "check_xsrf_cookie", "clear", "clear_all_cookies", "clear_cookie", "clear_header", "clear_login_cookie", "compute_etag", "concurrent_spawn_limit", "config", "content_security_policy", "cookie_max_age_days", "cookies", "create_signed_value", "create_template_loader", "csp_report_uri", "current_user", "data_received", "db", "decode_argument", "default_url", "delete", "detach", "domain", "eventlog", "expanded_scopes", "extra_error_html", "find_user", "finish", "flush", "get", "get_accessible_services", "get_argument", "get_arguments", "get_auth_http_client", "get_auth_token", "get_body_argument", "get_body_arguments", "get_browser_locale", "get_content_type", "get_cookie", "get_current_user", "get_current_user_cookie", "get_current_user_named_server_limit", "get_current_user_token", "get_login_url", "get_next_url", "get_query_argument", "get_query_arguments", "get_scope_filter", "get_secure_cookie", "get_secure_cookie_key_version", "get_session_cookie", "get_signed_cookie", "get_signed_cookie_key_version", "get_state", "get_status", "get_template", "get_template_namespace", "get_template_path", "get_token", "get_user_locale", "has_scope", "head", "hub", "initialize", "locale", "log", "log_exception", "login_user", "named_server_limit_per_user", "oauth2_request", "oauth_provider", "on_connection_close", "on_finish", "options", "parsed_scopes", "patch", "path_args", "path_kwargs", "post", "prepare", "proxy", "public_url", "put", "redirect", "redirect_to_server", "refresh_auth", "render", "render_embed_css", "render_embed_js", "render_linked_css", "render_linked_js", "render_string", "render_template", "request", "require_setting", "reverse_url", "send_error", "services", "set_cookie", "set_default_headers", "set_etag_header", "set_header", "set_hub_cookie", "set_login_cookie", "set_secure_cookie", "set_service_cookie", "set_session_cookie", "set_signed_cookie", "set_state_cookie", "set_status", "settings", "slow_spawn_timeout", "slow_stop_timeout", "spawn_home_error", "spawn_single_user", "spawner_class", "static_url", "statsd", "stop_single_user", "subdomain_host", "SUPPORTED_METHODS", "template_namespace", "ui", "user_from_username", "user_stopped", "users", "version_hash", "write", "write_error", "xsrf_form_html", "xsrf_token", "_accept_cookie_auth", "_accept_token_auth", "_active_modules", "_auto_finish", "_break_cycles", "_clear_representation_headers", "_convert_header_value", "_current_user", "_decode_xsrf_token", "_execute", "_finished", "_get_argument", "_get_arguments", "_get_raw_xsrf_token", "_handle_request_exception", "_headers", "_headers_written", "_initialize", "_INVALID_HEADER_CHAR_RE", "_jupyterhub_user", "_locale", "_log", "_new_cookie", "_OAUTH_ACCESS_TOKEN_URL", "_OAUTH_AUTHORIZE_URL", "_oauth_request_token_url", "_OAUTH_USERINFO_URL", "_prepared_future", "_raw_xsrf_token", "_reason", "_record_activity", "_refreshed_users", "_remove_control_chars_regex", "_request_summary", "_resolve_roles_and_scopes", "_session_id", "_set_cookie", "_set_user_cookie", "_state", "_status_code", "_stream_request_body", "_template_loader_lock", "_template_loaders", "_token_authenticated", "_transforms", "_ui_method", "_ui_module", "_unimplemented_method", "_user_for_cookie", "_user_from_orm", "_validate_next_url", "_write_buffer", "_xsrf_safe_methods", "_xsrf_token", "_xsrf_token_id", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init__", "__init_subclass__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__slots__", "__str__" ]
""" Base classes for Custom Authenticator to use OAuth with JupyterHub Most of the code c/o Kyle Kelley (@rgbkrk) """ import base64 import json import os import uuid from urllib.parse import quote from urllib.parse import urlparse from urllib.parse import urlunparse from jupyterhub.auth import Authenticator from jupyterhub.handlers import BaseHandler from jupyterhub.handlers import LogoutHandler from jupyterhub.utils import url_path_join from tornado import web from tornado.auth import OAuth2Mixin from tornado.httpclient import AsyncHTTPClient from tornado.httpclient import HTTPClientError from tornado.log import app_log from traitlets import Any from traitlets import Bool from traitlets import default from traitlets import Dict from traitlets import List from traitlets import Unicode def guess_callback_uri(protocol, host, hub_server_url): return '{proto}://{host}{path}'.format( proto=protocol, host=host, path=url_path_join(hub_server_url, 'oauth_callback') ) STATE_COOKIE_NAME = 'oauthenticator-state' def _serialize_state(state): """Serialize OAuth state to a base64 string after passing through JSON""" json_state = json.dumps(state) return base64.urlsafe_b64encode(json_state.encode('utf8')).decode('ascii') def _deserialize_state(b64_state): """Deserialize OAuth state as serialized in _serialize_state""" if isinstance(b64_state, str): b64_state = b64_state.encode('ascii') try: json_state = base64.urlsafe_b64decode(b64_state).decode('utf8') except ValueError: app_log.error("Failed to b64-decode state: %r", b64_state) return {} try: return json.loads(json_state) except ValueError: app_log.error("Failed to json-decode state: %r", json_state) return {} class OAuthLoginHandler(OAuth2Mixin, BaseHandler): """Base class for OAuth login handler Typically subclasses will need """ # these URLs are part of the OAuth2Mixin API # get them from the Authenticator object @property def _OAUTH_AUTHORIZE_URL(self): return self.authenticator.authorize_url @property def _OAUTH_ACCESS_TOKEN_URL(self): return self.authenticator.token_url @property def _OAUTH_USERINFO_URL(self): return self.authenticator.userdata_url def set_state_cookie(self, state): self._set_cookie(STATE_COOKIE_NAME, state, expires_days=1, httponly=True) _state = None def get_state(self): next_url = original_next_url = self.get_argument('next', None) if next_url: # avoid browsers treating \ as / next_url = next_url.replace('\\', quote('\\')) # disallow hostname-having urls, # force absolute path redirect urlinfo = urlparse(next_url) next_url = urlinfo._replace( scheme='', netloc='', path='/' + urlinfo.path.lstrip('/') ).geturl() if next_url != original_next_url: self.log.warning( "Ignoring next_url %r, using %r", original_next_url, next_url ) if self._state is None: self._state = _serialize_state( {'state_id': uuid.uuid4().hex, 'next_url': next_url} ) return self._state def get(self): redirect_uri = self.
.get_callback_url(self) extra_params = self.authenticator.extra_authorize_params.copy() self.log.info('OAuth redirect: %r', redirect_uri) state = self.get_state() self.set_state_cookie(state) extra_params['state'] = state self.authorize_redirect( redirect_uri=redirect_uri, client_id=self.authenticator.client_id, scope=self.authenticator.scope, extra_params=extra_params, response_type='code', ) class OAuthCallbackHandler(BaseHandler): """Basic handler for OAuth callback. Calls authenticator to verify username.""" _state_cookie = None def get_state_cookie(self): """Get OAuth state from cookies To be compared with the value in redirect URL """ if self._state_cookie is None: self._state_cookie = ( self.get_secure_cookie(STATE_COOKIE_NAME) or b'' ).decode('utf8', 'replace') self.clear_cookie(STATE_COOKIE_NAME) return self._state_cookie def get_state_url(self): """Get OAuth state from URL parameters to be compared with the value in cookies """ return self.get_argument("state") def check_state(self): """Verify OAuth state compare value in cookie with redirect url param """ cookie_state = self.get_state_cookie() url_state = self.get_state_url() if not cookie_state: raise web.HTTPError(400, "OAuth state missing from cookies") if not url_state: raise web.HTTPError(400, "OAuth state missing from URL") if cookie_state != url_state: self.log.warning("OAuth state mismatch: %s != %s", cookie_state, url_state) raise web.HTTPError(400, "OAuth state mismatch") def check_error(self): """Check the OAuth code""" error = self.get_argument("error", False) if error: message = self.get_argument("error_description", error) raise web.HTTPError(400, "OAuth error: %s" % message) def check_code(self): """Check the OAuth code""" if not self.get_argument("code", False): raise web.HTTPError(400, "OAuth callback made without a code") def check_arguments(self): """Validate the arguments of the redirect Default: - check for oauth-standard error, error_description arguments - check that there's a code - check that state matches """ self.check_error() self.check_code() self.check_state() def append_query_parameters(self, url, exclude=None): """JupyterHub 1.2 appends query parameters by default in get_next_url This is not appropriate for oauth callback handlers, where params are oauth state, code, etc. Override the method used to append parameters to next_url to not preserve any parameters """ return url def get_next_url(self, user=None): """Get the redirect target from the state field""" state = self.get_state_url() if state: next_url = _deserialize_state(state).get('next_url') if next_url: return next_url # JupyterHub 0.8 adds default .get_next_url for a fallback if hasattr(BaseHandler, 'get_next_url'): return super().get_next_url(user) return url_path_join(self.hub.server.base_url, 'home') async def _login_user_pre_08(self): """login_user simplifies the login+cookie+auth_state process in JupyterHub 0.8 _login_user_07 is for backward-compatibility with JupyterHub 0.7 """ user_info = await self.authenticator.get_authenticated_user(self, None) if user_info is None: return if isinstance(user_info, dict): username = user_info['name'] else: username = user_info user = self.user_from_username(username) self.set_login_cookie(user) return user if not hasattr(BaseHandler, 'login_user'): # JupyterHub 0.7 doesn't have .login_user login_user = _login_user_pre_08 async def get(self): self.check_arguments() user = await self.login_user() if user is None: # todo: custom error page? raise web.HTTPError(403) self.redirect(self.get_next_url(user)) class OAuthLogoutHandler(LogoutHandler): async def handle_logout(self): self.clear_cookie(STATE_COOKIE_NAME) async def render_logout_page(self): if self.authenticator.logout_redirect_url: self.redirect(self.authenticator.logout_redirect_url) return return await super().render_logout_page() class OAuthenticator(Authenticator): """Base class for OAuthenticators Subclasses must override: login_service (string identifying the service provider) authenticate (method takes one arg - the request handler handling the oauth callback) """ login_handler = OAuthLoginHandler callback_handler = OAuthCallbackHandler logout_handler = OAuthLogoutHandler authorize_url = Unicode( config=True, help="""The authenticate url for initiating oauth""" ) @default("authorize_url") def _authorize_url_default(self): return os.environ.get("OAUTH2_AUTHORIZE_URL", "") token_url = Unicode( config=True, help="""The url retrieving an access token at the completion of oauth""", ) @default("token_url") def _token_url_default(self): return os.environ.get("OAUTH2_TOKEN_URL", "") userdata_url = Unicode( config=True, help="""The url for retrieving user data with a completed access token""", ) @default("userdata_url") def _userdata_url_default(self): return os.environ.get("OAUTH2_USERDATA_URL", "") logout_redirect_url = Unicode(config=True, help="""URL for logging out of Auth0""") @default("logout_redirect_url") def _logout_redirect_url_default(self): return os.getenv("OAUTH_LOGOUT_REDIRECT_URL", "") scope = List( Unicode(), config=True, help="""The OAuth scopes to request. See the OAuth documentation of your OAuth provider for options. For GitHub in particular, you can see github_scopes.md in this repo. """, ) extra_authorize_params = Dict( config=True, help="""Extra GET params to send along with the initial OAuth request to the OAuth provider.""", ) login_service = 'override in subclass' oauth_callback_url = Unicode( os.getenv('OAUTH_CALLBACK_URL', ''), config=True, help="""Callback URL to use. Typically `https://{host}/hub/oauth_callback`""", ) client_id_env = '' client_id = Unicode(config=True) def _client_id_default(self): if self.client_id_env: client_id = os.getenv(self.client_id_env, '') if client_id: return client_id return os.getenv('OAUTH_CLIENT_ID', '') client_secret_env = '' client_secret = Unicode(config=True) def _client_secret_default(self): if self.client_secret_env: client_secret = os.getenv(self.client_secret_env, '') if client_secret: return client_secret return os.getenv('OAUTH_CLIENT_SECRET', '') validate_server_cert_env = 'OAUTH_TLS_VERIFY' validate_server_cert = Bool(config=True) def _validate_server_cert_default(self): env_value = os.getenv(self.validate_server_cert_env, '') if env_value == '0': return False else: return True http_client = Any() @default("http_client") def _default_http_client(self): return AsyncHTTPClient() async def fetch(self, req, label="fetching", parse_json=True, **kwargs): """Wrapper for http requests logs error responses, parses successful JSON responses Args: req: tornado HTTPRequest label (str): label describing what is happening, used in log message when the request fails. **kwargs: remaining keyword args passed to underlying `client.fetch(req, **kwargs)` Returns: r: parsed JSON response """ try: resp = await self.http_client.fetch(req, **kwargs) except HTTPClientError as e: if e.response: # Log failed response message for debugging purposes message = e.response.body.decode("utf8", "replace") try: # guess json, reformat for readability json_message = json.loads(message) except ValueError: # not json pass else: # reformat json log message for readability message = json.dumps(json_message, sort_keys=True, indent=1) else: # didn't get a response, e.g. connection error message = str(e) # log url without query params url = urlunparse(urlparse(req.url)._replace(query="")) app_log.error(f"Error {label} {e.code} {req.method} {url}: {message}") raise e else: if parse_json: if resp.body: return json.loads(resp.body.decode('utf8', 'replace')) else: # empty body is None return None else: return resp def login_url(self, base_url): return url_path_join(base_url, 'oauth_login') def logout_url(self, base_url): return url_path_join(base_url, 'logout') def get_callback_url(self, handler=None): """Get my OAuth redirect URL Either from config or guess based on the current request. """ if self.oauth_callback_url: return self.oauth_callback_url elif handler: return guess_callback_uri( handler.request.protocol, handler.request.host, handler.hub.server.base_url, ) else: raise ValueError( "Specify callback oauth_callback_url or give me a handler to guess with" ) def get_handlers(self, app): return [ (r'/oauth_login', self.login_handler), (r'/oauth_callback', self.callback_handler), (r'/logout', self.logout_handler), ] async def authenticate(self, handler, data=None): raise NotImplementedError() _deprecated_oauth_aliases = {} def _deprecated_oauth_trait(self, change): """observer for deprecated traits""" old_attr = change.name new_attr, version = self._deprecated_oauth_aliases.get(old_attr) new_value = getattr(self, new_attr) if new_value != change.new: # only warn if different # protects backward-compatible config from warnings # if they set the same value under both names self.log.warning( "{cls}.{old} is deprecated in {cls} {version}, use {cls}.{new} instead".format( cls=self.__class__.__name__, old=old_attr, new=new_attr, version=version, ) ) setattr(self, new_attr, change.new) def __init__(self, **kwargs): # observe deprecated config names in oauthenticator if self._deprecated_oauth_aliases: self.observe( self._deprecated_oauth_trait, names=list(self._deprecated_oauth_aliases) ) super().__init__(**kwargs)
coffeateam__coffea-casa
63
63-111-21
infile
get_state
[ "active_server_limit", "add_header", "admin_users", "allow_named_servers", "app", "append_query_parameters", "application", "auth_to_user", "authenticate", "authenticate_prometheus", "authenticator", "authorize_redirect", "base_url", "check_etag_header", "check_xsrf_cookie", "clear", "clear_all_cookies", "clear_cookie", "clear_header", "clear_login_cookie", "compute_etag", "concurrent_spawn_limit", "config", "content_security_policy", "cookie_max_age_days", "cookies", "create_signed_value", "create_template_loader", "csp_report_uri", "current_user", "data_received", "db", "decode_argument", "default_url", "delete", "detach", "domain", "eventlog", "expanded_scopes", "extra_error_html", "find_user", "finish", "flush", "get", "get_accessible_services", "get_argument", "get_arguments", "get_auth_http_client", "get_auth_token", "get_body_argument", "get_body_arguments", "get_browser_locale", "get_content_type", "get_cookie", "get_current_user", "get_current_user_cookie", "get_current_user_named_server_limit", "get_current_user_token", "get_login_url", "get_next_url", "get_query_argument", "get_query_arguments", "get_scope_filter", "get_secure_cookie", "get_secure_cookie_key_version", "get_session_cookie", "get_signed_cookie", "get_signed_cookie_key_version", "get_state", "get_status", "get_template", "get_template_namespace", "get_template_path", "get_token", "get_user_locale", "has_scope", "head", "hub", "initialize", "locale", "log", "log_exception", "login_user", "named_server_limit_per_user", "oauth2_request", "oauth_provider", "on_connection_close", "on_finish", "options", "parsed_scopes", "patch", "path_args", "path_kwargs", "post", "prepare", "proxy", "public_url", "put", "redirect", "redirect_to_server", "refresh_auth", "render", "render_embed_css", "render_embed_js", "render_linked_css", "render_linked_js", "render_string", "render_template", "request", "require_setting", "reverse_url", "send_error", "services", "set_cookie", "set_default_headers", "set_etag_header", "set_header", "set_hub_cookie", "set_login_cookie", "set_secure_cookie", "set_service_cookie", "set_session_cookie", "set_signed_cookie", "set_state_cookie", "set_status", "settings", "slow_spawn_timeout", "slow_stop_timeout", "spawn_home_error", "spawn_single_user", "spawner_class", "static_url", "statsd", "stop_single_user", "subdomain_host", "SUPPORTED_METHODS", "template_namespace", "ui", "user_from_username", "user_stopped", "users", "version_hash", "write", "write_error", "xsrf_form_html", "xsrf_token", "_accept_cookie_auth", "_accept_token_auth", "_active_modules", "_auto_finish", "_break_cycles", "_clear_representation_headers", "_convert_header_value", "_current_user", "_decode_xsrf_token", "_execute", "_finished", "_get_argument", "_get_arguments", "_get_raw_xsrf_token", "_handle_request_exception", "_headers", "_headers_written", "_initialize", "_INVALID_HEADER_CHAR_RE", "_jupyterhub_user", "_locale", "_log", "_new_cookie", "_OAUTH_ACCESS_TOKEN_URL", "_OAUTH_AUTHORIZE_URL", "_oauth_request_token_url", "_OAUTH_USERINFO_URL", "_prepared_future", "_raw_xsrf_token", "_reason", "_record_activity", "_refreshed_users", "_remove_control_chars_regex", "_request_summary", "_resolve_roles_and_scopes", "_session_id", "_set_cookie", "_set_user_cookie", "_state", "_status_code", "_stream_request_body", "_template_loader_lock", "_template_loaders", "_token_authenticated", "_transforms", "_ui_method", "_ui_module", "_unimplemented_method", "_user_for_cookie", "_user_from_orm", "_validate_next_url", "_write_buffer", "_xsrf_safe_methods", "_xsrf_token", "_xsrf_token_id", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init__", "__init_subclass__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__slots__", "__str__" ]
""" Base classes for Custom Authenticator to use OAuth with JupyterHub Most of the code c/o Kyle Kelley (@rgbkrk) """ import base64 import json import os import uuid from urllib.parse import quote from urllib.parse import urlparse from urllib.parse import urlunparse from jupyterhub.auth import Authenticator from jupyterhub.handlers import BaseHandler from jupyterhub.handlers import LogoutHandler from jupyterhub.utils import url_path_join from tornado import web from tornado.auth import OAuth2Mixin from tornado.httpclient import AsyncHTTPClient from tornado.httpclient import HTTPClientError from tornado.log import app_log from traitlets import Any from traitlets import Bool from traitlets import default from traitlets import Dict from traitlets import List from traitlets import Unicode def guess_callback_uri(protocol, host, hub_server_url): return '{proto}://{host}{path}'.format( proto=protocol, host=host, path=url_path_join(hub_server_url, 'oauth_callback') ) STATE_COOKIE_NAME = 'oauthenticator-state' def _serialize_state(state): """Serialize OAuth state to a base64 string after passing through JSON""" json_state = json.dumps(state) return base64.urlsafe_b64encode(json_state.encode('utf8')).decode('ascii') def _deserialize_state(b64_state): """Deserialize OAuth state as serialized in _serialize_state""" if isinstance(b64_state, str): b64_state = b64_state.encode('ascii') try: json_state = base64.urlsafe_b64decode(b64_state).decode('utf8') except ValueError: app_log.error("Failed to b64-decode state: %r", b64_state) return {} try: return json.loads(json_state) except ValueError: app_log.error("Failed to json-decode state: %r", json_state) return {} class OAuthLoginHandler(OAuth2Mixin, BaseHandler): """Base class for OAuth login handler Typically subclasses will need """ # these URLs are part of the OAuth2Mixin API # get them from the Authenticator object @property def _OAUTH_AUTHORIZE_URL(self): return self.authenticator.authorize_url @property def _OAUTH_ACCESS_TOKEN_URL(self): return self.authenticator.token_url @property def _OAUTH_USERINFO_URL(self): return self.authenticator.userdata_url def set_state_cookie(self, state): self._set_cookie(STATE_COOKIE_NAME, state, expires_days=1, httponly=True) _state = None def get_state(self): next_url = original_next_url = self.get_argument('next', None) if next_url: # avoid browsers treating \ as / next_url = next_url.replace('\\', quote('\\')) # disallow hostname-having urls, # force absolute path redirect urlinfo = urlparse(next_url) next_url = urlinfo._replace( scheme='', netloc='', path='/' + urlinfo.path.lstrip('/') ).geturl() if next_url != original_next_url: self.log.warning( "Ignoring next_url %r, using %r", original_next_url, next_url ) if self._state is None: self._state = _serialize_state( {'state_id': uuid.uuid4().hex, 'next_url': next_url} ) return self._state def get(self): redirect_uri = self.authenticator.get_callback_url(self) extra_params = self.authenticator.extra_authorize_params.copy() self.log.info('OAuth redirect: %r', redirect_uri) state = self.
() self.set_state_cookie(state) extra_params['state'] = state self.authorize_redirect( redirect_uri=redirect_uri, client_id=self.authenticator.client_id, scope=self.authenticator.scope, extra_params=extra_params, response_type='code', ) class OAuthCallbackHandler(BaseHandler): """Basic handler for OAuth callback. Calls authenticator to verify username.""" _state_cookie = None def get_state_cookie(self): """Get OAuth state from cookies To be compared with the value in redirect URL """ if self._state_cookie is None: self._state_cookie = ( self.get_secure_cookie(STATE_COOKIE_NAME) or b'' ).decode('utf8', 'replace') self.clear_cookie(STATE_COOKIE_NAME) return self._state_cookie def get_state_url(self): """Get OAuth state from URL parameters to be compared with the value in cookies """ return self.get_argument("state") def check_state(self): """Verify OAuth state compare value in cookie with redirect url param """ cookie_state = self.get_state_cookie() url_state = self.get_state_url() if not cookie_state: raise web.HTTPError(400, "OAuth state missing from cookies") if not url_state: raise web.HTTPError(400, "OAuth state missing from URL") if cookie_state != url_state: self.log.warning("OAuth state mismatch: %s != %s", cookie_state, url_state) raise web.HTTPError(400, "OAuth state mismatch") def check_error(self): """Check the OAuth code""" error = self.get_argument("error", False) if error: message = self.get_argument("error_description", error) raise web.HTTPError(400, "OAuth error: %s" % message) def check_code(self): """Check the OAuth code""" if not self.get_argument("code", False): raise web.HTTPError(400, "OAuth callback made without a code") def check_arguments(self): """Validate the arguments of the redirect Default: - check for oauth-standard error, error_description arguments - check that there's a code - check that state matches """ self.check_error() self.check_code() self.check_state() def append_query_parameters(self, url, exclude=None): """JupyterHub 1.2 appends query parameters by default in get_next_url This is not appropriate for oauth callback handlers, where params are oauth state, code, etc. Override the method used to append parameters to next_url to not preserve any parameters """ return url def get_next_url(self, user=None): """Get the redirect target from the state field""" state = self.get_state_url() if state: next_url = _deserialize_state(state).get('next_url') if next_url: return next_url # JupyterHub 0.8 adds default .get_next_url for a fallback if hasattr(BaseHandler, 'get_next_url'): return super().get_next_url(user) return url_path_join(self.hub.server.base_url, 'home') async def _login_user_pre_08(self): """login_user simplifies the login+cookie+auth_state process in JupyterHub 0.8 _login_user_07 is for backward-compatibility with JupyterHub 0.7 """ user_info = await self.authenticator.get_authenticated_user(self, None) if user_info is None: return if isinstance(user_info, dict): username = user_info['name'] else: username = user_info user = self.user_from_username(username) self.set_login_cookie(user) return user if not hasattr(BaseHandler, 'login_user'): # JupyterHub 0.7 doesn't have .login_user login_user = _login_user_pre_08 async def get(self): self.check_arguments() user = await self.login_user() if user is None: # todo: custom error page? raise web.HTTPError(403) self.redirect(self.get_next_url(user)) class OAuthLogoutHandler(LogoutHandler): async def handle_logout(self): self.clear_cookie(STATE_COOKIE_NAME) async def render_logout_page(self): if self.authenticator.logout_redirect_url: self.redirect(self.authenticator.logout_redirect_url) return return await super().render_logout_page() class OAuthenticator(Authenticator): """Base class for OAuthenticators Subclasses must override: login_service (string identifying the service provider) authenticate (method takes one arg - the request handler handling the oauth callback) """ login_handler = OAuthLoginHandler callback_handler = OAuthCallbackHandler logout_handler = OAuthLogoutHandler authorize_url = Unicode( config=True, help="""The authenticate url for initiating oauth""" ) @default("authorize_url") def _authorize_url_default(self): return os.environ.get("OAUTH2_AUTHORIZE_URL", "") token_url = Unicode( config=True, help="""The url retrieving an access token at the completion of oauth""", ) @default("token_url") def _token_url_default(self): return os.environ.get("OAUTH2_TOKEN_URL", "") userdata_url = Unicode( config=True, help="""The url for retrieving user data with a completed access token""", ) @default("userdata_url") def _userdata_url_default(self): return os.environ.get("OAUTH2_USERDATA_URL", "") logout_redirect_url = Unicode(config=True, help="""URL for logging out of Auth0""") @default("logout_redirect_url") def _logout_redirect_url_default(self): return os.getenv("OAUTH_LOGOUT_REDIRECT_URL", "") scope = List( Unicode(), config=True, help="""The OAuth scopes to request. See the OAuth documentation of your OAuth provider for options. For GitHub in particular, you can see github_scopes.md in this repo. """, ) extra_authorize_params = Dict( config=True, help="""Extra GET params to send along with the initial OAuth request to the OAuth provider.""", ) login_service = 'override in subclass' oauth_callback_url = Unicode( os.getenv('OAUTH_CALLBACK_URL', ''), config=True, help="""Callback URL to use. Typically `https://{host}/hub/oauth_callback`""", ) client_id_env = '' client_id = Unicode(config=True) def _client_id_default(self): if self.client_id_env: client_id = os.getenv(self.client_id_env, '') if client_id: return client_id return os.getenv('OAUTH_CLIENT_ID', '') client_secret_env = '' client_secret = Unicode(config=True) def _client_secret_default(self): if self.client_secret_env: client_secret = os.getenv(self.client_secret_env, '') if client_secret: return client_secret return os.getenv('OAUTH_CLIENT_SECRET', '') validate_server_cert_env = 'OAUTH_TLS_VERIFY' validate_server_cert = Bool(config=True) def _validate_server_cert_default(self): env_value = os.getenv(self.validate_server_cert_env, '') if env_value == '0': return False else: return True http_client = Any() @default("http_client") def _default_http_client(self): return AsyncHTTPClient() async def fetch(self, req, label="fetching", parse_json=True, **kwargs): """Wrapper for http requests logs error responses, parses successful JSON responses Args: req: tornado HTTPRequest label (str): label describing what is happening, used in log message when the request fails. **kwargs: remaining keyword args passed to underlying `client.fetch(req, **kwargs)` Returns: r: parsed JSON response """ try: resp = await self.http_client.fetch(req, **kwargs) except HTTPClientError as e: if e.response: # Log failed response message for debugging purposes message = e.response.body.decode("utf8", "replace") try: # guess json, reformat for readability json_message = json.loads(message) except ValueError: # not json pass else: # reformat json log message for readability message = json.dumps(json_message, sort_keys=True, indent=1) else: # didn't get a response, e.g. connection error message = str(e) # log url without query params url = urlunparse(urlparse(req.url)._replace(query="")) app_log.error(f"Error {label} {e.code} {req.method} {url}: {message}") raise e else: if parse_json: if resp.body: return json.loads(resp.body.decode('utf8', 'replace')) else: # empty body is None return None else: return resp def login_url(self, base_url): return url_path_join(base_url, 'oauth_login') def logout_url(self, base_url): return url_path_join(base_url, 'logout') def get_callback_url(self, handler=None): """Get my OAuth redirect URL Either from config or guess based on the current request. """ if self.oauth_callback_url: return self.oauth_callback_url elif handler: return guess_callback_uri( handler.request.protocol, handler.request.host, handler.hub.server.base_url, ) else: raise ValueError( "Specify callback oauth_callback_url or give me a handler to guess with" ) def get_handlers(self, app): return [ (r'/oauth_login', self.login_handler), (r'/oauth_callback', self.callback_handler), (r'/logout', self.logout_handler), ] async def authenticate(self, handler, data=None): raise NotImplementedError() _deprecated_oauth_aliases = {} def _deprecated_oauth_trait(self, change): """observer for deprecated traits""" old_attr = change.name new_attr, version = self._deprecated_oauth_aliases.get(old_attr) new_value = getattr(self, new_attr) if new_value != change.new: # only warn if different # protects backward-compatible config from warnings # if they set the same value under both names self.log.warning( "{cls}.{old} is deprecated in {cls} {version}, use {cls}.{new} instead".format( cls=self.__class__.__name__, old=old_attr, new=new_attr, version=version, ) ) setattr(self, new_attr, change.new) def __init__(self, **kwargs): # observe deprecated config names in oauthenticator if self._deprecated_oauth_aliases: self.observe( self._deprecated_oauth_trait, names=list(self._deprecated_oauth_aliases) ) super().__init__(**kwargs)
coffeateam__coffea-casa
63
63-112-13
infile
set_state_cookie
[ "active_server_limit", "add_header", "admin_users", "allow_named_servers", "app", "append_query_parameters", "application", "auth_to_user", "authenticate", "authenticate_prometheus", "authenticator", "authorize_redirect", "base_url", "check_etag_header", "check_xsrf_cookie", "clear", "clear_all_cookies", "clear_cookie", "clear_header", "clear_login_cookie", "compute_etag", "concurrent_spawn_limit", "config", "content_security_policy", "cookie_max_age_days", "cookies", "create_signed_value", "create_template_loader", "csp_report_uri", "current_user", "data_received", "db", "decode_argument", "default_url", "delete", "detach", "domain", "eventlog", "expanded_scopes", "extra_error_html", "find_user", "finish", "flush", "get", "get_accessible_services", "get_argument", "get_arguments", "get_auth_http_client", "get_auth_token", "get_body_argument", "get_body_arguments", "get_browser_locale", "get_content_type", "get_cookie", "get_current_user", "get_current_user_cookie", "get_current_user_named_server_limit", "get_current_user_token", "get_login_url", "get_next_url", "get_query_argument", "get_query_arguments", "get_scope_filter", "get_secure_cookie", "get_secure_cookie_key_version", "get_session_cookie", "get_signed_cookie", "get_signed_cookie_key_version", "get_state", "get_status", "get_template", "get_template_namespace", "get_template_path", "get_token", "get_user_locale", "has_scope", "head", "hub", "initialize", "locale", "log", "log_exception", "login_user", "named_server_limit_per_user", "oauth2_request", "oauth_provider", "on_connection_close", "on_finish", "options", "parsed_scopes", "patch", "path_args", "path_kwargs", "post", "prepare", "proxy", "public_url", "put", "redirect", "redirect_to_server", "refresh_auth", "render", "render_embed_css", "render_embed_js", "render_linked_css", "render_linked_js", "render_string", "render_template", "request", "require_setting", "reverse_url", "send_error", "services", "set_cookie", "set_default_headers", "set_etag_header", "set_header", "set_hub_cookie", "set_login_cookie", "set_secure_cookie", "set_service_cookie", "set_session_cookie", "set_signed_cookie", "set_state_cookie", "set_status", "settings", "slow_spawn_timeout", "slow_stop_timeout", "spawn_home_error", "spawn_single_user", "spawner_class", "static_url", "statsd", "stop_single_user", "subdomain_host", "SUPPORTED_METHODS", "template_namespace", "ui", "user_from_username", "user_stopped", "users", "version_hash", "write", "write_error", "xsrf_form_html", "xsrf_token", "_accept_cookie_auth", "_accept_token_auth", "_active_modules", "_auto_finish", "_break_cycles", "_clear_representation_headers", "_convert_header_value", "_current_user", "_decode_xsrf_token", "_execute", "_finished", "_get_argument", "_get_arguments", "_get_raw_xsrf_token", "_handle_request_exception", "_headers", "_headers_written", "_initialize", "_INVALID_HEADER_CHAR_RE", "_jupyterhub_user", "_locale", "_log", "_new_cookie", "_OAUTH_ACCESS_TOKEN_URL", "_OAUTH_AUTHORIZE_URL", "_oauth_request_token_url", "_OAUTH_USERINFO_URL", "_prepared_future", "_raw_xsrf_token", "_reason", "_record_activity", "_refreshed_users", "_remove_control_chars_regex", "_request_summary", "_resolve_roles_and_scopes", "_session_id", "_set_cookie", "_set_user_cookie", "_state", "_status_code", "_stream_request_body", "_template_loader_lock", "_template_loaders", "_token_authenticated", "_transforms", "_ui_method", "_ui_module", "_unimplemented_method", "_user_for_cookie", "_user_from_orm", "_validate_next_url", "_write_buffer", "_xsrf_safe_methods", "_xsrf_token", "_xsrf_token_id", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init__", "__init_subclass__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__slots__", "__str__" ]
""" Base classes for Custom Authenticator to use OAuth with JupyterHub Most of the code c/o Kyle Kelley (@rgbkrk) """ import base64 import json import os import uuid from urllib.parse import quote from urllib.parse import urlparse from urllib.parse import urlunparse from jupyterhub.auth import Authenticator from jupyterhub.handlers import BaseHandler from jupyterhub.handlers import LogoutHandler from jupyterhub.utils import url_path_join from tornado import web from tornado.auth import OAuth2Mixin from tornado.httpclient import AsyncHTTPClient from tornado.httpclient import HTTPClientError from tornado.log import app_log from traitlets import Any from traitlets import Bool from traitlets import default from traitlets import Dict from traitlets import List from traitlets import Unicode def guess_callback_uri(protocol, host, hub_server_url): return '{proto}://{host}{path}'.format( proto=protocol, host=host, path=url_path_join(hub_server_url, 'oauth_callback') ) STATE_COOKIE_NAME = 'oauthenticator-state' def _serialize_state(state): """Serialize OAuth state to a base64 string after passing through JSON""" json_state = json.dumps(state) return base64.urlsafe_b64encode(json_state.encode('utf8')).decode('ascii') def _deserialize_state(b64_state): """Deserialize OAuth state as serialized in _serialize_state""" if isinstance(b64_state, str): b64_state = b64_state.encode('ascii') try: json_state = base64.urlsafe_b64decode(b64_state).decode('utf8') except ValueError: app_log.error("Failed to b64-decode state: %r", b64_state) return {} try: return json.loads(json_state) except ValueError: app_log.error("Failed to json-decode state: %r", json_state) return {} class OAuthLoginHandler(OAuth2Mixin, BaseHandler): """Base class for OAuth login handler Typically subclasses will need """ # these URLs are part of the OAuth2Mixin API # get them from the Authenticator object @property def _OAUTH_AUTHORIZE_URL(self): return self.authenticator.authorize_url @property def _OAUTH_ACCESS_TOKEN_URL(self): return self.authenticator.token_url @property def _OAUTH_USERINFO_URL(self): return self.authenticator.userdata_url def set_state_cookie(self, state): self._set_cookie(STATE_COOKIE_NAME, state, expires_days=1, httponly=True) _state = None def get_state(self): next_url = original_next_url = self.get_argument('next', None) if next_url: # avoid browsers treating \ as / next_url = next_url.replace('\\', quote('\\')) # disallow hostname-having urls, # force absolute path redirect urlinfo = urlparse(next_url) next_url = urlinfo._replace( scheme='', netloc='', path='/' + urlinfo.path.lstrip('/') ).geturl() if next_url != original_next_url: self.log.warning( "Ignoring next_url %r, using %r", original_next_url, next_url ) if self._state is None: self._state = _serialize_state( {'state_id': uuid.uuid4().hex, 'next_url': next_url} ) return self._state def get(self): redirect_uri = self.authenticator.get_callback_url(self) extra_params = self.authenticator.extra_authorize_params.copy() self.log.info('OAuth redirect: %r', redirect_uri) state = self.get_state() self.
(state) extra_params['state'] = state self.authorize_redirect( redirect_uri=redirect_uri, client_id=self.authenticator.client_id, scope=self.authenticator.scope, extra_params=extra_params, response_type='code', ) class OAuthCallbackHandler(BaseHandler): """Basic handler for OAuth callback. Calls authenticator to verify username.""" _state_cookie = None def get_state_cookie(self): """Get OAuth state from cookies To be compared with the value in redirect URL """ if self._state_cookie is None: self._state_cookie = ( self.get_secure_cookie(STATE_COOKIE_NAME) or b'' ).decode('utf8', 'replace') self.clear_cookie(STATE_COOKIE_NAME) return self._state_cookie def get_state_url(self): """Get OAuth state from URL parameters to be compared with the value in cookies """ return self.get_argument("state") def check_state(self): """Verify OAuth state compare value in cookie with redirect url param """ cookie_state = self.get_state_cookie() url_state = self.get_state_url() if not cookie_state: raise web.HTTPError(400, "OAuth state missing from cookies") if not url_state: raise web.HTTPError(400, "OAuth state missing from URL") if cookie_state != url_state: self.log.warning("OAuth state mismatch: %s != %s", cookie_state, url_state) raise web.HTTPError(400, "OAuth state mismatch") def check_error(self): """Check the OAuth code""" error = self.get_argument("error", False) if error: message = self.get_argument("error_description", error) raise web.HTTPError(400, "OAuth error: %s" % message) def check_code(self): """Check the OAuth code""" if not self.get_argument("code", False): raise web.HTTPError(400, "OAuth callback made without a code") def check_arguments(self): """Validate the arguments of the redirect Default: - check for oauth-standard error, error_description arguments - check that there's a code - check that state matches """ self.check_error() self.check_code() self.check_state() def append_query_parameters(self, url, exclude=None): """JupyterHub 1.2 appends query parameters by default in get_next_url This is not appropriate for oauth callback handlers, where params are oauth state, code, etc. Override the method used to append parameters to next_url to not preserve any parameters """ return url def get_next_url(self, user=None): """Get the redirect target from the state field""" state = self.get_state_url() if state: next_url = _deserialize_state(state).get('next_url') if next_url: return next_url # JupyterHub 0.8 adds default .get_next_url for a fallback if hasattr(BaseHandler, 'get_next_url'): return super().get_next_url(user) return url_path_join(self.hub.server.base_url, 'home') async def _login_user_pre_08(self): """login_user simplifies the login+cookie+auth_state process in JupyterHub 0.8 _login_user_07 is for backward-compatibility with JupyterHub 0.7 """ user_info = await self.authenticator.get_authenticated_user(self, None) if user_info is None: return if isinstance(user_info, dict): username = user_info['name'] else: username = user_info user = self.user_from_username(username) self.set_login_cookie(user) return user if not hasattr(BaseHandler, 'login_user'): # JupyterHub 0.7 doesn't have .login_user login_user = _login_user_pre_08 async def get(self): self.check_arguments() user = await self.login_user() if user is None: # todo: custom error page? raise web.HTTPError(403) self.redirect(self.get_next_url(user)) class OAuthLogoutHandler(LogoutHandler): async def handle_logout(self): self.clear_cookie(STATE_COOKIE_NAME) async def render_logout_page(self): if self.authenticator.logout_redirect_url: self.redirect(self.authenticator.logout_redirect_url) return return await super().render_logout_page() class OAuthenticator(Authenticator): """Base class for OAuthenticators Subclasses must override: login_service (string identifying the service provider) authenticate (method takes one arg - the request handler handling the oauth callback) """ login_handler = OAuthLoginHandler callback_handler = OAuthCallbackHandler logout_handler = OAuthLogoutHandler authorize_url = Unicode( config=True, help="""The authenticate url for initiating oauth""" ) @default("authorize_url") def _authorize_url_default(self): return os.environ.get("OAUTH2_AUTHORIZE_URL", "") token_url = Unicode( config=True, help="""The url retrieving an access token at the completion of oauth""", ) @default("token_url") def _token_url_default(self): return os.environ.get("OAUTH2_TOKEN_URL", "") userdata_url = Unicode( config=True, help="""The url for retrieving user data with a completed access token""", ) @default("userdata_url") def _userdata_url_default(self): return os.environ.get("OAUTH2_USERDATA_URL", "") logout_redirect_url = Unicode(config=True, help="""URL for logging out of Auth0""") @default("logout_redirect_url") def _logout_redirect_url_default(self): return os.getenv("OAUTH_LOGOUT_REDIRECT_URL", "") scope = List( Unicode(), config=True, help="""The OAuth scopes to request. See the OAuth documentation of your OAuth provider for options. For GitHub in particular, you can see github_scopes.md in this repo. """, ) extra_authorize_params = Dict( config=True, help="""Extra GET params to send along with the initial OAuth request to the OAuth provider.""", ) login_service = 'override in subclass' oauth_callback_url = Unicode( os.getenv('OAUTH_CALLBACK_URL', ''), config=True, help="""Callback URL to use. Typically `https://{host}/hub/oauth_callback`""", ) client_id_env = '' client_id = Unicode(config=True) def _client_id_default(self): if self.client_id_env: client_id = os.getenv(self.client_id_env, '') if client_id: return client_id return os.getenv('OAUTH_CLIENT_ID', '') client_secret_env = '' client_secret = Unicode(config=True) def _client_secret_default(self): if self.client_secret_env: client_secret = os.getenv(self.client_secret_env, '') if client_secret: return client_secret return os.getenv('OAUTH_CLIENT_SECRET', '') validate_server_cert_env = 'OAUTH_TLS_VERIFY' validate_server_cert = Bool(config=True) def _validate_server_cert_default(self): env_value = os.getenv(self.validate_server_cert_env, '') if env_value == '0': return False else: return True http_client = Any() @default("http_client") def _default_http_client(self): return AsyncHTTPClient() async def fetch(self, req, label="fetching", parse_json=True, **kwargs): """Wrapper for http requests logs error responses, parses successful JSON responses Args: req: tornado HTTPRequest label (str): label describing what is happening, used in log message when the request fails. **kwargs: remaining keyword args passed to underlying `client.fetch(req, **kwargs)` Returns: r: parsed JSON response """ try: resp = await self.http_client.fetch(req, **kwargs) except HTTPClientError as e: if e.response: # Log failed response message for debugging purposes message = e.response.body.decode("utf8", "replace") try: # guess json, reformat for readability json_message = json.loads(message) except ValueError: # not json pass else: # reformat json log message for readability message = json.dumps(json_message, sort_keys=True, indent=1) else: # didn't get a response, e.g. connection error message = str(e) # log url without query params url = urlunparse(urlparse(req.url)._replace(query="")) app_log.error(f"Error {label} {e.code} {req.method} {url}: {message}") raise e else: if parse_json: if resp.body: return json.loads(resp.body.decode('utf8', 'replace')) else: # empty body is None return None else: return resp def login_url(self, base_url): return url_path_join(base_url, 'oauth_login') def logout_url(self, base_url): return url_path_join(base_url, 'logout') def get_callback_url(self, handler=None): """Get my OAuth redirect URL Either from config or guess based on the current request. """ if self.oauth_callback_url: return self.oauth_callback_url elif handler: return guess_callback_uri( handler.request.protocol, handler.request.host, handler.hub.server.base_url, ) else: raise ValueError( "Specify callback oauth_callback_url or give me a handler to guess with" ) def get_handlers(self, app): return [ (r'/oauth_login', self.login_handler), (r'/oauth_callback', self.callback_handler), (r'/logout', self.logout_handler), ] async def authenticate(self, handler, data=None): raise NotImplementedError() _deprecated_oauth_aliases = {} def _deprecated_oauth_trait(self, change): """observer for deprecated traits""" old_attr = change.name new_attr, version = self._deprecated_oauth_aliases.get(old_attr) new_value = getattr(self, new_attr) if new_value != change.new: # only warn if different # protects backward-compatible config from warnings # if they set the same value under both names self.log.warning( "{cls}.{old} is deprecated in {cls} {version}, use {cls}.{new} instead".format( cls=self.__class__.__name__, old=old_attr, new=new_attr, version=version, ) ) setattr(self, new_attr, change.new) def __init__(self, **kwargs): # observe deprecated config names in oauthenticator if self._deprecated_oauth_aliases: self.observe( self._deprecated_oauth_trait, names=list(self._deprecated_oauth_aliases) ) super().__init__(**kwargs)
coffeateam__coffea-casa
63
63-152-28
infile
get_state_cookie
[ "active_server_limit", "add_header", "admin_users", "allow_named_servers", "app", "append_query_parameters", "application", "auth_to_user", "authenticate", "authenticate_prometheus", "authenticator", "base_url", "check_arguments", "check_code", "check_error", "check_etag_header", "check_state", "check_xsrf_cookie", "clear", "clear_all_cookies", "clear_cookie", "clear_header", "clear_login_cookie", "compute_etag", "concurrent_spawn_limit", "config", "content_security_policy", "cookie_max_age_days", "cookies", "create_signed_value", "create_template_loader", "csp_report_uri", "current_user", "data_received", "db", "decode_argument", "default_url", "delete", "detach", "domain", "eventlog", "expanded_scopes", "extra_error_html", "find_user", "finish", "flush", "get", "get_accessible_services", "get_argument", "get_arguments", "get_auth_token", "get_body_argument", "get_body_arguments", "get_browser_locale", "get_content_type", "get_cookie", "get_current_user", "get_current_user_cookie", "get_current_user_named_server_limit", "get_current_user_token", "get_login_url", "get_next_url", "get_query_argument", "get_query_arguments", "get_scope_filter", "get_secure_cookie", "get_secure_cookie_key_version", "get_session_cookie", "get_signed_cookie", "get_signed_cookie_key_version", "get_state_cookie", "get_state_url", "get_status", "get_template", "get_template_namespace", "get_template_path", "get_token", "get_user_locale", "has_scope", "head", "hub", "initialize", "locale", "log", "log_exception", "login_user", "named_server_limit_per_user", "oauth_provider", "on_connection_close", "on_finish", "options", "parsed_scopes", "patch", "path_args", "path_kwargs", "post", "prepare", "proxy", "public_url", "put", "redirect", "redirect_to_server", "refresh_auth", "render", "render_embed_css", "render_embed_js", "render_linked_css", "render_linked_js", "render_string", "render_template", "request", "require_setting", "reverse_url", "send_error", "services", "set_cookie", "set_default_headers", "set_etag_header", "set_header", "set_hub_cookie", "set_login_cookie", "set_secure_cookie", "set_service_cookie", "set_session_cookie", "set_signed_cookie", "set_status", "settings", "slow_spawn_timeout", "slow_stop_timeout", "spawn_home_error", "spawn_single_user", "spawner_class", "static_url", "statsd", "stop_single_user", "subdomain_host", "SUPPORTED_METHODS", "template_namespace", "ui", "user_from_username", "user_stopped", "users", "version_hash", "write", "write_error", "xsrf_form_html", "xsrf_token", "_accept_cookie_auth", "_accept_token_auth", "_active_modules", "_auto_finish", "_break_cycles", "_clear_representation_headers", "_convert_header_value", "_current_user", "_decode_xsrf_token", "_execute", "_finished", "_get_argument", "_get_arguments", "_get_raw_xsrf_token", "_handle_request_exception", "_headers", "_headers_written", "_initialize", "_INVALID_HEADER_CHAR_RE", "_jupyterhub_user", "_locale", "_log", "_login_user_pre_08", "_new_cookie", "_prepared_future", "_raw_xsrf_token", "_reason", "_record_activity", "_refreshed_users", "_remove_control_chars_regex", "_request_summary", "_resolve_roles_and_scopes", "_session_id", "_set_cookie", "_set_user_cookie", "_state_cookie", "_status_code", "_stream_request_body", "_template_loader_lock", "_template_loaders", "_token_authenticated", "_transforms", "_ui_method", "_ui_module", "_unimplemented_method", "_user_for_cookie", "_user_from_orm", "_validate_next_url", "_write_buffer", "_xsrf_safe_methods", "_xsrf_token", "_xsrf_token_id", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init__", "__init_subclass__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__slots__", "__str__" ]
""" Base classes for Custom Authenticator to use OAuth with JupyterHub Most of the code c/o Kyle Kelley (@rgbkrk) """ import base64 import json import os import uuid from urllib.parse import quote from urllib.parse import urlparse from urllib.parse import urlunparse from jupyterhub.auth import Authenticator from jupyterhub.handlers import BaseHandler from jupyterhub.handlers import LogoutHandler from jupyterhub.utils import url_path_join from tornado import web from tornado.auth import OAuth2Mixin from tornado.httpclient import AsyncHTTPClient from tornado.httpclient import HTTPClientError from tornado.log import app_log from traitlets import Any from traitlets import Bool from traitlets import default from traitlets import Dict from traitlets import List from traitlets import Unicode def guess_callback_uri(protocol, host, hub_server_url): return '{proto}://{host}{path}'.format( proto=protocol, host=host, path=url_path_join(hub_server_url, 'oauth_callback') ) STATE_COOKIE_NAME = 'oauthenticator-state' def _serialize_state(state): """Serialize OAuth state to a base64 string after passing through JSON""" json_state = json.dumps(state) return base64.urlsafe_b64encode(json_state.encode('utf8')).decode('ascii') def _deserialize_state(b64_state): """Deserialize OAuth state as serialized in _serialize_state""" if isinstance(b64_state, str): b64_state = b64_state.encode('ascii') try: json_state = base64.urlsafe_b64decode(b64_state).decode('utf8') except ValueError: app_log.error("Failed to b64-decode state: %r", b64_state) return {} try: return json.loads(json_state) except ValueError: app_log.error("Failed to json-decode state: %r", json_state) return {} class OAuthLoginHandler(OAuth2Mixin, BaseHandler): """Base class for OAuth login handler Typically subclasses will need """ # these URLs are part of the OAuth2Mixin API # get them from the Authenticator object @property def _OAUTH_AUTHORIZE_URL(self): return self.authenticator.authorize_url @property def _OAUTH_ACCESS_TOKEN_URL(self): return self.authenticator.token_url @property def _OAUTH_USERINFO_URL(self): return self.authenticator.userdata_url def set_state_cookie(self, state): self._set_cookie(STATE_COOKIE_NAME, state, expires_days=1, httponly=True) _state = None def get_state(self): next_url = original_next_url = self.get_argument('next', None) if next_url: # avoid browsers treating \ as / next_url = next_url.replace('\\', quote('\\')) # disallow hostname-having urls, # force absolute path redirect urlinfo = urlparse(next_url) next_url = urlinfo._replace( scheme='', netloc='', path='/' + urlinfo.path.lstrip('/') ).geturl() if next_url != original_next_url: self.log.warning( "Ignoring next_url %r, using %r", original_next_url, next_url ) if self._state is None: self._state = _serialize_state( {'state_id': uuid.uuid4().hex, 'next_url': next_url} ) return self._state def get(self): redirect_uri = self.authenticator.get_callback_url(self) extra_params = self.authenticator.extra_authorize_params.copy() self.log.info('OAuth redirect: %r', redirect_uri) state = self.get_state() self.set_state_cookie(state) extra_params['state'] = state self.authorize_redirect( redirect_uri=redirect_uri, client_id=self.authenticator.client_id, scope=self.authenticator.scope, extra_params=extra_params, response_type='code', ) class OAuthCallbackHandler(BaseHandler): """Basic handler for OAuth callback. Calls authenticator to verify username.""" _state_cookie = None def get_state_cookie(self): """Get OAuth state from cookies To be compared with the value in redirect URL """ if self._state_cookie is None: self._state_cookie = ( self.get_secure_cookie(STATE_COOKIE_NAME) or b'' ).decode('utf8', 'replace') self.clear_cookie(STATE_COOKIE_NAME) return self._state_cookie def get_state_url(self): """Get OAuth state from URL parameters to be compared with the value in cookies """ return self.get_argument("state") def check_state(self): """Verify OAuth state compare value in cookie with redirect url param """ cookie_state = self.
() url_state = self.get_state_url() if not cookie_state: raise web.HTTPError(400, "OAuth state missing from cookies") if not url_state: raise web.HTTPError(400, "OAuth state missing from URL") if cookie_state != url_state: self.log.warning("OAuth state mismatch: %s != %s", cookie_state, url_state) raise web.HTTPError(400, "OAuth state mismatch") def check_error(self): """Check the OAuth code""" error = self.get_argument("error", False) if error: message = self.get_argument("error_description", error) raise web.HTTPError(400, "OAuth error: %s" % message) def check_code(self): """Check the OAuth code""" if not self.get_argument("code", False): raise web.HTTPError(400, "OAuth callback made without a code") def check_arguments(self): """Validate the arguments of the redirect Default: - check for oauth-standard error, error_description arguments - check that there's a code - check that state matches """ self.check_error() self.check_code() self.check_state() def append_query_parameters(self, url, exclude=None): """JupyterHub 1.2 appends query parameters by default in get_next_url This is not appropriate for oauth callback handlers, where params are oauth state, code, etc. Override the method used to append parameters to next_url to not preserve any parameters """ return url def get_next_url(self, user=None): """Get the redirect target from the state field""" state = self.get_state_url() if state: next_url = _deserialize_state(state).get('next_url') if next_url: return next_url # JupyterHub 0.8 adds default .get_next_url for a fallback if hasattr(BaseHandler, 'get_next_url'): return super().get_next_url(user) return url_path_join(self.hub.server.base_url, 'home') async def _login_user_pre_08(self): """login_user simplifies the login+cookie+auth_state process in JupyterHub 0.8 _login_user_07 is for backward-compatibility with JupyterHub 0.7 """ user_info = await self.authenticator.get_authenticated_user(self, None) if user_info is None: return if isinstance(user_info, dict): username = user_info['name'] else: username = user_info user = self.user_from_username(username) self.set_login_cookie(user) return user if not hasattr(BaseHandler, 'login_user'): # JupyterHub 0.7 doesn't have .login_user login_user = _login_user_pre_08 async def get(self): self.check_arguments() user = await self.login_user() if user is None: # todo: custom error page? raise web.HTTPError(403) self.redirect(self.get_next_url(user)) class OAuthLogoutHandler(LogoutHandler): async def handle_logout(self): self.clear_cookie(STATE_COOKIE_NAME) async def render_logout_page(self): if self.authenticator.logout_redirect_url: self.redirect(self.authenticator.logout_redirect_url) return return await super().render_logout_page() class OAuthenticator(Authenticator): """Base class for OAuthenticators Subclasses must override: login_service (string identifying the service provider) authenticate (method takes one arg - the request handler handling the oauth callback) """ login_handler = OAuthLoginHandler callback_handler = OAuthCallbackHandler logout_handler = OAuthLogoutHandler authorize_url = Unicode( config=True, help="""The authenticate url for initiating oauth""" ) @default("authorize_url") def _authorize_url_default(self): return os.environ.get("OAUTH2_AUTHORIZE_URL", "") token_url = Unicode( config=True, help="""The url retrieving an access token at the completion of oauth""", ) @default("token_url") def _token_url_default(self): return os.environ.get("OAUTH2_TOKEN_URL", "") userdata_url = Unicode( config=True, help="""The url for retrieving user data with a completed access token""", ) @default("userdata_url") def _userdata_url_default(self): return os.environ.get("OAUTH2_USERDATA_URL", "") logout_redirect_url = Unicode(config=True, help="""URL for logging out of Auth0""") @default("logout_redirect_url") def _logout_redirect_url_default(self): return os.getenv("OAUTH_LOGOUT_REDIRECT_URL", "") scope = List( Unicode(), config=True, help="""The OAuth scopes to request. See the OAuth documentation of your OAuth provider for options. For GitHub in particular, you can see github_scopes.md in this repo. """, ) extra_authorize_params = Dict( config=True, help="""Extra GET params to send along with the initial OAuth request to the OAuth provider.""", ) login_service = 'override in subclass' oauth_callback_url = Unicode( os.getenv('OAUTH_CALLBACK_URL', ''), config=True, help="""Callback URL to use. Typically `https://{host}/hub/oauth_callback`""", ) client_id_env = '' client_id = Unicode(config=True) def _client_id_default(self): if self.client_id_env: client_id = os.getenv(self.client_id_env, '') if client_id: return client_id return os.getenv('OAUTH_CLIENT_ID', '') client_secret_env = '' client_secret = Unicode(config=True) def _client_secret_default(self): if self.client_secret_env: client_secret = os.getenv(self.client_secret_env, '') if client_secret: return client_secret return os.getenv('OAUTH_CLIENT_SECRET', '') validate_server_cert_env = 'OAUTH_TLS_VERIFY' validate_server_cert = Bool(config=True) def _validate_server_cert_default(self): env_value = os.getenv(self.validate_server_cert_env, '') if env_value == '0': return False else: return True http_client = Any() @default("http_client") def _default_http_client(self): return AsyncHTTPClient() async def fetch(self, req, label="fetching", parse_json=True, **kwargs): """Wrapper for http requests logs error responses, parses successful JSON responses Args: req: tornado HTTPRequest label (str): label describing what is happening, used in log message when the request fails. **kwargs: remaining keyword args passed to underlying `client.fetch(req, **kwargs)` Returns: r: parsed JSON response """ try: resp = await self.http_client.fetch(req, **kwargs) except HTTPClientError as e: if e.response: # Log failed response message for debugging purposes message = e.response.body.decode("utf8", "replace") try: # guess json, reformat for readability json_message = json.loads(message) except ValueError: # not json pass else: # reformat json log message for readability message = json.dumps(json_message, sort_keys=True, indent=1) else: # didn't get a response, e.g. connection error message = str(e) # log url without query params url = urlunparse(urlparse(req.url)._replace(query="")) app_log.error(f"Error {label} {e.code} {req.method} {url}: {message}") raise e else: if parse_json: if resp.body: return json.loads(resp.body.decode('utf8', 'replace')) else: # empty body is None return None else: return resp def login_url(self, base_url): return url_path_join(base_url, 'oauth_login') def logout_url(self, base_url): return url_path_join(base_url, 'logout') def get_callback_url(self, handler=None): """Get my OAuth redirect URL Either from config or guess based on the current request. """ if self.oauth_callback_url: return self.oauth_callback_url elif handler: return guess_callback_uri( handler.request.protocol, handler.request.host, handler.hub.server.base_url, ) else: raise ValueError( "Specify callback oauth_callback_url or give me a handler to guess with" ) def get_handlers(self, app): return [ (r'/oauth_login', self.login_handler), (r'/oauth_callback', self.callback_handler), (r'/logout', self.logout_handler), ] async def authenticate(self, handler, data=None): raise NotImplementedError() _deprecated_oauth_aliases = {} def _deprecated_oauth_trait(self, change): """observer for deprecated traits""" old_attr = change.name new_attr, version = self._deprecated_oauth_aliases.get(old_attr) new_value = getattr(self, new_attr) if new_value != change.new: # only warn if different # protects backward-compatible config from warnings # if they set the same value under both names self.log.warning( "{cls}.{old} is deprecated in {cls} {version}, use {cls}.{new} instead".format( cls=self.__class__.__name__, old=old_attr, new=new_attr, version=version, ) ) setattr(self, new_attr, change.new) def __init__(self, **kwargs): # observe deprecated config names in oauthenticator if self._deprecated_oauth_aliases: self.observe( self._deprecated_oauth_trait, names=list(self._deprecated_oauth_aliases) ) super().__init__(**kwargs)
coffeateam__coffea-casa
63
63-153-25
infile
get_state_url
[ "active_server_limit", "add_header", "admin_users", "allow_named_servers", "app", "append_query_parameters", "application", "auth_to_user", "authenticate", "authenticate_prometheus", "authenticator", "base_url", "check_arguments", "check_code", "check_error", "check_etag_header", "check_state", "check_xsrf_cookie", "clear", "clear_all_cookies", "clear_cookie", "clear_header", "clear_login_cookie", "compute_etag", "concurrent_spawn_limit", "config", "content_security_policy", "cookie_max_age_days", "cookies", "create_signed_value", "create_template_loader", "csp_report_uri", "current_user", "data_received", "db", "decode_argument", "default_url", "delete", "detach", "domain", "eventlog", "expanded_scopes", "extra_error_html", "find_user", "finish", "flush", "get", "get_accessible_services", "get_argument", "get_arguments", "get_auth_token", "get_body_argument", "get_body_arguments", "get_browser_locale", "get_content_type", "get_cookie", "get_current_user", "get_current_user_cookie", "get_current_user_named_server_limit", "get_current_user_token", "get_login_url", "get_next_url", "get_query_argument", "get_query_arguments", "get_scope_filter", "get_secure_cookie", "get_secure_cookie_key_version", "get_session_cookie", "get_signed_cookie", "get_signed_cookie_key_version", "get_state_cookie", "get_state_url", "get_status", "get_template", "get_template_namespace", "get_template_path", "get_token", "get_user_locale", "has_scope", "head", "hub", "initialize", "locale", "log", "log_exception", "login_user", "named_server_limit_per_user", "oauth_provider", "on_connection_close", "on_finish", "options", "parsed_scopes", "patch", "path_args", "path_kwargs", "post", "prepare", "proxy", "public_url", "put", "redirect", "redirect_to_server", "refresh_auth", "render", "render_embed_css", "render_embed_js", "render_linked_css", "render_linked_js", "render_string", "render_template", "request", "require_setting", "reverse_url", "send_error", "services", "set_cookie", "set_default_headers", "set_etag_header", "set_header", "set_hub_cookie", "set_login_cookie", "set_secure_cookie", "set_service_cookie", "set_session_cookie", "set_signed_cookie", "set_status", "settings", "slow_spawn_timeout", "slow_stop_timeout", "spawn_home_error", "spawn_single_user", "spawner_class", "static_url", "statsd", "stop_single_user", "subdomain_host", "SUPPORTED_METHODS", "template_namespace", "ui", "user_from_username", "user_stopped", "users", "version_hash", "write", "write_error", "xsrf_form_html", "xsrf_token", "_accept_cookie_auth", "_accept_token_auth", "_active_modules", "_auto_finish", "_break_cycles", "_clear_representation_headers", "_convert_header_value", "_current_user", "_decode_xsrf_token", "_execute", "_finished", "_get_argument", "_get_arguments", "_get_raw_xsrf_token", "_handle_request_exception", "_headers", "_headers_written", "_initialize", "_INVALID_HEADER_CHAR_RE", "_jupyterhub_user", "_locale", "_log", "_login_user_pre_08", "_new_cookie", "_prepared_future", "_raw_xsrf_token", "_reason", "_record_activity", "_refreshed_users", "_remove_control_chars_regex", "_request_summary", "_resolve_roles_and_scopes", "_session_id", "_set_cookie", "_set_user_cookie", "_state_cookie", "_status_code", "_stream_request_body", "_template_loader_lock", "_template_loaders", "_token_authenticated", "_transforms", "_ui_method", "_ui_module", "_unimplemented_method", "_user_for_cookie", "_user_from_orm", "_validate_next_url", "_write_buffer", "_xsrf_safe_methods", "_xsrf_token", "_xsrf_token_id", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init__", "__init_subclass__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__slots__", "__str__" ]
""" Base classes for Custom Authenticator to use OAuth with JupyterHub Most of the code c/o Kyle Kelley (@rgbkrk) """ import base64 import json import os import uuid from urllib.parse import quote from urllib.parse import urlparse from urllib.parse import urlunparse from jupyterhub.auth import Authenticator from jupyterhub.handlers import BaseHandler from jupyterhub.handlers import LogoutHandler from jupyterhub.utils import url_path_join from tornado import web from tornado.auth import OAuth2Mixin from tornado.httpclient import AsyncHTTPClient from tornado.httpclient import HTTPClientError from tornado.log import app_log from traitlets import Any from traitlets import Bool from traitlets import default from traitlets import Dict from traitlets import List from traitlets import Unicode def guess_callback_uri(protocol, host, hub_server_url): return '{proto}://{host}{path}'.format( proto=protocol, host=host, path=url_path_join(hub_server_url, 'oauth_callback') ) STATE_COOKIE_NAME = 'oauthenticator-state' def _serialize_state(state): """Serialize OAuth state to a base64 string after passing through JSON""" json_state = json.dumps(state) return base64.urlsafe_b64encode(json_state.encode('utf8')).decode('ascii') def _deserialize_state(b64_state): """Deserialize OAuth state as serialized in _serialize_state""" if isinstance(b64_state, str): b64_state = b64_state.encode('ascii') try: json_state = base64.urlsafe_b64decode(b64_state).decode('utf8') except ValueError: app_log.error("Failed to b64-decode state: %r", b64_state) return {} try: return json.loads(json_state) except ValueError: app_log.error("Failed to json-decode state: %r", json_state) return {} class OAuthLoginHandler(OAuth2Mixin, BaseHandler): """Base class for OAuth login handler Typically subclasses will need """ # these URLs are part of the OAuth2Mixin API # get them from the Authenticator object @property def _OAUTH_AUTHORIZE_URL(self): return self.authenticator.authorize_url @property def _OAUTH_ACCESS_TOKEN_URL(self): return self.authenticator.token_url @property def _OAUTH_USERINFO_URL(self): return self.authenticator.userdata_url def set_state_cookie(self, state): self._set_cookie(STATE_COOKIE_NAME, state, expires_days=1, httponly=True) _state = None def get_state(self): next_url = original_next_url = self.get_argument('next', None) if next_url: # avoid browsers treating \ as / next_url = next_url.replace('\\', quote('\\')) # disallow hostname-having urls, # force absolute path redirect urlinfo = urlparse(next_url) next_url = urlinfo._replace( scheme='', netloc='', path='/' + urlinfo.path.lstrip('/') ).geturl() if next_url != original_next_url: self.log.warning( "Ignoring next_url %r, using %r", original_next_url, next_url ) if self._state is None: self._state = _serialize_state( {'state_id': uuid.uuid4().hex, 'next_url': next_url} ) return self._state def get(self): redirect_uri = self.authenticator.get_callback_url(self) extra_params = self.authenticator.extra_authorize_params.copy() self.log.info('OAuth redirect: %r', redirect_uri) state = self.get_state() self.set_state_cookie(state) extra_params['state'] = state self.authorize_redirect( redirect_uri=redirect_uri, client_id=self.authenticator.client_id, scope=self.authenticator.scope, extra_params=extra_params, response_type='code', ) class OAuthCallbackHandler(BaseHandler): """Basic handler for OAuth callback. Calls authenticator to verify username.""" _state_cookie = None def get_state_cookie(self): """Get OAuth state from cookies To be compared with the value in redirect URL """ if self._state_cookie is None: self._state_cookie = ( self.get_secure_cookie(STATE_COOKIE_NAME) or b'' ).decode('utf8', 'replace') self.clear_cookie(STATE_COOKIE_NAME) return self._state_cookie def get_state_url(self): """Get OAuth state from URL parameters to be compared with the value in cookies """ return self.get_argument("state") def check_state(self): """Verify OAuth state compare value in cookie with redirect url param """ cookie_state = self.get_state_cookie() url_state = self.
() if not cookie_state: raise web.HTTPError(400, "OAuth state missing from cookies") if not url_state: raise web.HTTPError(400, "OAuth state missing from URL") if cookie_state != url_state: self.log.warning("OAuth state mismatch: %s != %s", cookie_state, url_state) raise web.HTTPError(400, "OAuth state mismatch") def check_error(self): """Check the OAuth code""" error = self.get_argument("error", False) if error: message = self.get_argument("error_description", error) raise web.HTTPError(400, "OAuth error: %s" % message) def check_code(self): """Check the OAuth code""" if not self.get_argument("code", False): raise web.HTTPError(400, "OAuth callback made without a code") def check_arguments(self): """Validate the arguments of the redirect Default: - check for oauth-standard error, error_description arguments - check that there's a code - check that state matches """ self.check_error() self.check_code() self.check_state() def append_query_parameters(self, url, exclude=None): """JupyterHub 1.2 appends query parameters by default in get_next_url This is not appropriate for oauth callback handlers, where params are oauth state, code, etc. Override the method used to append parameters to next_url to not preserve any parameters """ return url def get_next_url(self, user=None): """Get the redirect target from the state field""" state = self.get_state_url() if state: next_url = _deserialize_state(state).get('next_url') if next_url: return next_url # JupyterHub 0.8 adds default .get_next_url for a fallback if hasattr(BaseHandler, 'get_next_url'): return super().get_next_url(user) return url_path_join(self.hub.server.base_url, 'home') async def _login_user_pre_08(self): """login_user simplifies the login+cookie+auth_state process in JupyterHub 0.8 _login_user_07 is for backward-compatibility with JupyterHub 0.7 """ user_info = await self.authenticator.get_authenticated_user(self, None) if user_info is None: return if isinstance(user_info, dict): username = user_info['name'] else: username = user_info user = self.user_from_username(username) self.set_login_cookie(user) return user if not hasattr(BaseHandler, 'login_user'): # JupyterHub 0.7 doesn't have .login_user login_user = _login_user_pre_08 async def get(self): self.check_arguments() user = await self.login_user() if user is None: # todo: custom error page? raise web.HTTPError(403) self.redirect(self.get_next_url(user)) class OAuthLogoutHandler(LogoutHandler): async def handle_logout(self): self.clear_cookie(STATE_COOKIE_NAME) async def render_logout_page(self): if self.authenticator.logout_redirect_url: self.redirect(self.authenticator.logout_redirect_url) return return await super().render_logout_page() class OAuthenticator(Authenticator): """Base class for OAuthenticators Subclasses must override: login_service (string identifying the service provider) authenticate (method takes one arg - the request handler handling the oauth callback) """ login_handler = OAuthLoginHandler callback_handler = OAuthCallbackHandler logout_handler = OAuthLogoutHandler authorize_url = Unicode( config=True, help="""The authenticate url for initiating oauth""" ) @default("authorize_url") def _authorize_url_default(self): return os.environ.get("OAUTH2_AUTHORIZE_URL", "") token_url = Unicode( config=True, help="""The url retrieving an access token at the completion of oauth""", ) @default("token_url") def _token_url_default(self): return os.environ.get("OAUTH2_TOKEN_URL", "") userdata_url = Unicode( config=True, help="""The url for retrieving user data with a completed access token""", ) @default("userdata_url") def _userdata_url_default(self): return os.environ.get("OAUTH2_USERDATA_URL", "") logout_redirect_url = Unicode(config=True, help="""URL for logging out of Auth0""") @default("logout_redirect_url") def _logout_redirect_url_default(self): return os.getenv("OAUTH_LOGOUT_REDIRECT_URL", "") scope = List( Unicode(), config=True, help="""The OAuth scopes to request. See the OAuth documentation of your OAuth provider for options. For GitHub in particular, you can see github_scopes.md in this repo. """, ) extra_authorize_params = Dict( config=True, help="""Extra GET params to send along with the initial OAuth request to the OAuth provider.""", ) login_service = 'override in subclass' oauth_callback_url = Unicode( os.getenv('OAUTH_CALLBACK_URL', ''), config=True, help="""Callback URL to use. Typically `https://{host}/hub/oauth_callback`""", ) client_id_env = '' client_id = Unicode(config=True) def _client_id_default(self): if self.client_id_env: client_id = os.getenv(self.client_id_env, '') if client_id: return client_id return os.getenv('OAUTH_CLIENT_ID', '') client_secret_env = '' client_secret = Unicode(config=True) def _client_secret_default(self): if self.client_secret_env: client_secret = os.getenv(self.client_secret_env, '') if client_secret: return client_secret return os.getenv('OAUTH_CLIENT_SECRET', '') validate_server_cert_env = 'OAUTH_TLS_VERIFY' validate_server_cert = Bool(config=True) def _validate_server_cert_default(self): env_value = os.getenv(self.validate_server_cert_env, '') if env_value == '0': return False else: return True http_client = Any() @default("http_client") def _default_http_client(self): return AsyncHTTPClient() async def fetch(self, req, label="fetching", parse_json=True, **kwargs): """Wrapper for http requests logs error responses, parses successful JSON responses Args: req: tornado HTTPRequest label (str): label describing what is happening, used in log message when the request fails. **kwargs: remaining keyword args passed to underlying `client.fetch(req, **kwargs)` Returns: r: parsed JSON response """ try: resp = await self.http_client.fetch(req, **kwargs) except HTTPClientError as e: if e.response: # Log failed response message for debugging purposes message = e.response.body.decode("utf8", "replace") try: # guess json, reformat for readability json_message = json.loads(message) except ValueError: # not json pass else: # reformat json log message for readability message = json.dumps(json_message, sort_keys=True, indent=1) else: # didn't get a response, e.g. connection error message = str(e) # log url without query params url = urlunparse(urlparse(req.url)._replace(query="")) app_log.error(f"Error {label} {e.code} {req.method} {url}: {message}") raise e else: if parse_json: if resp.body: return json.loads(resp.body.decode('utf8', 'replace')) else: # empty body is None return None else: return resp def login_url(self, base_url): return url_path_join(base_url, 'oauth_login') def logout_url(self, base_url): return url_path_join(base_url, 'logout') def get_callback_url(self, handler=None): """Get my OAuth redirect URL Either from config or guess based on the current request. """ if self.oauth_callback_url: return self.oauth_callback_url elif handler: return guess_callback_uri( handler.request.protocol, handler.request.host, handler.hub.server.base_url, ) else: raise ValueError( "Specify callback oauth_callback_url or give me a handler to guess with" ) def get_handlers(self, app): return [ (r'/oauth_login', self.login_handler), (r'/oauth_callback', self.callback_handler), (r'/logout', self.logout_handler), ] async def authenticate(self, handler, data=None): raise NotImplementedError() _deprecated_oauth_aliases = {} def _deprecated_oauth_trait(self, change): """observer for deprecated traits""" old_attr = change.name new_attr, version = self._deprecated_oauth_aliases.get(old_attr) new_value = getattr(self, new_attr) if new_value != change.new: # only warn if different # protects backward-compatible config from warnings # if they set the same value under both names self.log.warning( "{cls}.{old} is deprecated in {cls} {version}, use {cls}.{new} instead".format( cls=self.__class__.__name__, old=old_attr, new=new_attr, version=version, ) ) setattr(self, new_attr, change.new) def __init__(self, **kwargs): # observe deprecated config names in oauthenticator if self._deprecated_oauth_aliases: self.observe( self._deprecated_oauth_trait, names=list(self._deprecated_oauth_aliases) ) super().__init__(**kwargs)
coffeateam__coffea-casa
63
63-183-13
infile
check_error
[ "active_server_limit", "add_header", "admin_users", "allow_named_servers", "app", "append_query_parameters", "application", "auth_to_user", "authenticate", "authenticate_prometheus", "authenticator", "base_url", "check_arguments", "check_code", "check_error", "check_etag_header", "check_state", "check_xsrf_cookie", "clear", "clear_all_cookies", "clear_cookie", "clear_header", "clear_login_cookie", "compute_etag", "concurrent_spawn_limit", "config", "content_security_policy", "cookie_max_age_days", "cookies", "create_signed_value", "create_template_loader", "csp_report_uri", "current_user", "data_received", "db", "decode_argument", "default_url", "delete", "detach", "domain", "eventlog", "expanded_scopes", "extra_error_html", "find_user", "finish", "flush", "get", "get_accessible_services", "get_argument", "get_arguments", "get_auth_token", "get_body_argument", "get_body_arguments", "get_browser_locale", "get_content_type", "get_cookie", "get_current_user", "get_current_user_cookie", "get_current_user_named_server_limit", "get_current_user_token", "get_login_url", "get_next_url", "get_query_argument", "get_query_arguments", "get_scope_filter", "get_secure_cookie", "get_secure_cookie_key_version", "get_session_cookie", "get_signed_cookie", "get_signed_cookie_key_version", "get_state_cookie", "get_state_url", "get_status", "get_template", "get_template_namespace", "get_template_path", "get_token", "get_user_locale", "has_scope", "head", "hub", "initialize", "locale", "log", "log_exception", "login_user", "named_server_limit_per_user", "oauth_provider", "on_connection_close", "on_finish", "options", "parsed_scopes", "patch", "path_args", "path_kwargs", "post", "prepare", "proxy", "public_url", "put", "redirect", "redirect_to_server", "refresh_auth", "render", "render_embed_css", "render_embed_js", "render_linked_css", "render_linked_js", "render_string", "render_template", "request", "require_setting", "reverse_url", "send_error", "services", "set_cookie", "set_default_headers", "set_etag_header", "set_header", "set_hub_cookie", "set_login_cookie", "set_secure_cookie", "set_service_cookie", "set_session_cookie", "set_signed_cookie", "set_status", "settings", "slow_spawn_timeout", "slow_stop_timeout", "spawn_home_error", "spawn_single_user", "spawner_class", "static_url", "statsd", "stop_single_user", "subdomain_host", "SUPPORTED_METHODS", "template_namespace", "ui", "user_from_username", "user_stopped", "users", "version_hash", "write", "write_error", "xsrf_form_html", "xsrf_token", "_accept_cookie_auth", "_accept_token_auth", "_active_modules", "_auto_finish", "_break_cycles", "_clear_representation_headers", "_convert_header_value", "_current_user", "_decode_xsrf_token", "_execute", "_finished", "_get_argument", "_get_arguments", "_get_raw_xsrf_token", "_handle_request_exception", "_headers", "_headers_written", "_initialize", "_INVALID_HEADER_CHAR_RE", "_jupyterhub_user", "_locale", "_log", "_login_user_pre_08", "_new_cookie", "_prepared_future", "_raw_xsrf_token", "_reason", "_record_activity", "_refreshed_users", "_remove_control_chars_regex", "_request_summary", "_resolve_roles_and_scopes", "_session_id", "_set_cookie", "_set_user_cookie", "_state_cookie", "_status_code", "_stream_request_body", "_template_loader_lock", "_template_loaders", "_token_authenticated", "_transforms", "_ui_method", "_ui_module", "_unimplemented_method", "_user_for_cookie", "_user_from_orm", "_validate_next_url", "_write_buffer", "_xsrf_safe_methods", "_xsrf_token", "_xsrf_token_id", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init__", "__init_subclass__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__slots__", "__str__" ]
""" Base classes for Custom Authenticator to use OAuth with JupyterHub Most of the code c/o Kyle Kelley (@rgbkrk) """ import base64 import json import os import uuid from urllib.parse import quote from urllib.parse import urlparse from urllib.parse import urlunparse from jupyterhub.auth import Authenticator from jupyterhub.handlers import BaseHandler from jupyterhub.handlers import LogoutHandler from jupyterhub.utils import url_path_join from tornado import web from tornado.auth import OAuth2Mixin from tornado.httpclient import AsyncHTTPClient from tornado.httpclient import HTTPClientError from tornado.log import app_log from traitlets import Any from traitlets import Bool from traitlets import default from traitlets import Dict from traitlets import List from traitlets import Unicode def guess_callback_uri(protocol, host, hub_server_url): return '{proto}://{host}{path}'.format( proto=protocol, host=host, path=url_path_join(hub_server_url, 'oauth_callback') ) STATE_COOKIE_NAME = 'oauthenticator-state' def _serialize_state(state): """Serialize OAuth state to a base64 string after passing through JSON""" json_state = json.dumps(state) return base64.urlsafe_b64encode(json_state.encode('utf8')).decode('ascii') def _deserialize_state(b64_state): """Deserialize OAuth state as serialized in _serialize_state""" if isinstance(b64_state, str): b64_state = b64_state.encode('ascii') try: json_state = base64.urlsafe_b64decode(b64_state).decode('utf8') except ValueError: app_log.error("Failed to b64-decode state: %r", b64_state) return {} try: return json.loads(json_state) except ValueError: app_log.error("Failed to json-decode state: %r", json_state) return {} class OAuthLoginHandler(OAuth2Mixin, BaseHandler): """Base class for OAuth login handler Typically subclasses will need """ # these URLs are part of the OAuth2Mixin API # get them from the Authenticator object @property def _OAUTH_AUTHORIZE_URL(self): return self.authenticator.authorize_url @property def _OAUTH_ACCESS_TOKEN_URL(self): return self.authenticator.token_url @property def _OAUTH_USERINFO_URL(self): return self.authenticator.userdata_url def set_state_cookie(self, state): self._set_cookie(STATE_COOKIE_NAME, state, expires_days=1, httponly=True) _state = None def get_state(self): next_url = original_next_url = self.get_argument('next', None) if next_url: # avoid browsers treating \ as / next_url = next_url.replace('\\', quote('\\')) # disallow hostname-having urls, # force absolute path redirect urlinfo = urlparse(next_url) next_url = urlinfo._replace( scheme='', netloc='', path='/' + urlinfo.path.lstrip('/') ).geturl() if next_url != original_next_url: self.log.warning( "Ignoring next_url %r, using %r", original_next_url, next_url ) if self._state is None: self._state = _serialize_state( {'state_id': uuid.uuid4().hex, 'next_url': next_url} ) return self._state def get(self): redirect_uri = self.authenticator.get_callback_url(self) extra_params = self.authenticator.extra_authorize_params.copy() self.log.info('OAuth redirect: %r', redirect_uri) state = self.get_state() self.set_state_cookie(state) extra_params['state'] = state self.authorize_redirect( redirect_uri=redirect_uri, client_id=self.authenticator.client_id, scope=self.authenticator.scope, extra_params=extra_params, response_type='code', ) class OAuthCallbackHandler(BaseHandler): """Basic handler for OAuth callback. Calls authenticator to verify username.""" _state_cookie = None def get_state_cookie(self): """Get OAuth state from cookies To be compared with the value in redirect URL """ if self._state_cookie is None: self._state_cookie = ( self.get_secure_cookie(STATE_COOKIE_NAME) or b'' ).decode('utf8', 'replace') self.clear_cookie(STATE_COOKIE_NAME) return self._state_cookie def get_state_url(self): """Get OAuth state from URL parameters to be compared with the value in cookies """ return self.get_argument("state") def check_state(self): """Verify OAuth state compare value in cookie with redirect url param """ cookie_state = self.get_state_cookie() url_state = self.get_state_url() if not cookie_state: raise web.HTTPError(400, "OAuth state missing from cookies") if not url_state: raise web.HTTPError(400, "OAuth state missing from URL") if cookie_state != url_state: self.log.warning("OAuth state mismatch: %s != %s", cookie_state, url_state) raise web.HTTPError(400, "OAuth state mismatch") def check_error(self): """Check the OAuth code""" error = self.get_argument("error", False) if error: message = self.get_argument("error_description", error) raise web.HTTPError(400, "OAuth error: %s" % message) def check_code(self): """Check the OAuth code""" if not self.get_argument("code", False): raise web.HTTPError(400, "OAuth callback made without a code") def check_arguments(self): """Validate the arguments of the redirect Default: - check for oauth-standard error, error_description arguments - check that there's a code - check that state matches """ self.
() self.check_code() self.check_state() def append_query_parameters(self, url, exclude=None): """JupyterHub 1.2 appends query parameters by default in get_next_url This is not appropriate for oauth callback handlers, where params are oauth state, code, etc. Override the method used to append parameters to next_url to not preserve any parameters """ return url def get_next_url(self, user=None): """Get the redirect target from the state field""" state = self.get_state_url() if state: next_url = _deserialize_state(state).get('next_url') if next_url: return next_url # JupyterHub 0.8 adds default .get_next_url for a fallback if hasattr(BaseHandler, 'get_next_url'): return super().get_next_url(user) return url_path_join(self.hub.server.base_url, 'home') async def _login_user_pre_08(self): """login_user simplifies the login+cookie+auth_state process in JupyterHub 0.8 _login_user_07 is for backward-compatibility with JupyterHub 0.7 """ user_info = await self.authenticator.get_authenticated_user(self, None) if user_info is None: return if isinstance(user_info, dict): username = user_info['name'] else: username = user_info user = self.user_from_username(username) self.set_login_cookie(user) return user if not hasattr(BaseHandler, 'login_user'): # JupyterHub 0.7 doesn't have .login_user login_user = _login_user_pre_08 async def get(self): self.check_arguments() user = await self.login_user() if user is None: # todo: custom error page? raise web.HTTPError(403) self.redirect(self.get_next_url(user)) class OAuthLogoutHandler(LogoutHandler): async def handle_logout(self): self.clear_cookie(STATE_COOKIE_NAME) async def render_logout_page(self): if self.authenticator.logout_redirect_url: self.redirect(self.authenticator.logout_redirect_url) return return await super().render_logout_page() class OAuthenticator(Authenticator): """Base class for OAuthenticators Subclasses must override: login_service (string identifying the service provider) authenticate (method takes one arg - the request handler handling the oauth callback) """ login_handler = OAuthLoginHandler callback_handler = OAuthCallbackHandler logout_handler = OAuthLogoutHandler authorize_url = Unicode( config=True, help="""The authenticate url for initiating oauth""" ) @default("authorize_url") def _authorize_url_default(self): return os.environ.get("OAUTH2_AUTHORIZE_URL", "") token_url = Unicode( config=True, help="""The url retrieving an access token at the completion of oauth""", ) @default("token_url") def _token_url_default(self): return os.environ.get("OAUTH2_TOKEN_URL", "") userdata_url = Unicode( config=True, help="""The url for retrieving user data with a completed access token""", ) @default("userdata_url") def _userdata_url_default(self): return os.environ.get("OAUTH2_USERDATA_URL", "") logout_redirect_url = Unicode(config=True, help="""URL for logging out of Auth0""") @default("logout_redirect_url") def _logout_redirect_url_default(self): return os.getenv("OAUTH_LOGOUT_REDIRECT_URL", "") scope = List( Unicode(), config=True, help="""The OAuth scopes to request. See the OAuth documentation of your OAuth provider for options. For GitHub in particular, you can see github_scopes.md in this repo. """, ) extra_authorize_params = Dict( config=True, help="""Extra GET params to send along with the initial OAuth request to the OAuth provider.""", ) login_service = 'override in subclass' oauth_callback_url = Unicode( os.getenv('OAUTH_CALLBACK_URL', ''), config=True, help="""Callback URL to use. Typically `https://{host}/hub/oauth_callback`""", ) client_id_env = '' client_id = Unicode(config=True) def _client_id_default(self): if self.client_id_env: client_id = os.getenv(self.client_id_env, '') if client_id: return client_id return os.getenv('OAUTH_CLIENT_ID', '') client_secret_env = '' client_secret = Unicode(config=True) def _client_secret_default(self): if self.client_secret_env: client_secret = os.getenv(self.client_secret_env, '') if client_secret: return client_secret return os.getenv('OAUTH_CLIENT_SECRET', '') validate_server_cert_env = 'OAUTH_TLS_VERIFY' validate_server_cert = Bool(config=True) def _validate_server_cert_default(self): env_value = os.getenv(self.validate_server_cert_env, '') if env_value == '0': return False else: return True http_client = Any() @default("http_client") def _default_http_client(self): return AsyncHTTPClient() async def fetch(self, req, label="fetching", parse_json=True, **kwargs): """Wrapper for http requests logs error responses, parses successful JSON responses Args: req: tornado HTTPRequest label (str): label describing what is happening, used in log message when the request fails. **kwargs: remaining keyword args passed to underlying `client.fetch(req, **kwargs)` Returns: r: parsed JSON response """ try: resp = await self.http_client.fetch(req, **kwargs) except HTTPClientError as e: if e.response: # Log failed response message for debugging purposes message = e.response.body.decode("utf8", "replace") try: # guess json, reformat for readability json_message = json.loads(message) except ValueError: # not json pass else: # reformat json log message for readability message = json.dumps(json_message, sort_keys=True, indent=1) else: # didn't get a response, e.g. connection error message = str(e) # log url without query params url = urlunparse(urlparse(req.url)._replace(query="")) app_log.error(f"Error {label} {e.code} {req.method} {url}: {message}") raise e else: if parse_json: if resp.body: return json.loads(resp.body.decode('utf8', 'replace')) else: # empty body is None return None else: return resp def login_url(self, base_url): return url_path_join(base_url, 'oauth_login') def logout_url(self, base_url): return url_path_join(base_url, 'logout') def get_callback_url(self, handler=None): """Get my OAuth redirect URL Either from config or guess based on the current request. """ if self.oauth_callback_url: return self.oauth_callback_url elif handler: return guess_callback_uri( handler.request.protocol, handler.request.host, handler.hub.server.base_url, ) else: raise ValueError( "Specify callback oauth_callback_url or give me a handler to guess with" ) def get_handlers(self, app): return [ (r'/oauth_login', self.login_handler), (r'/oauth_callback', self.callback_handler), (r'/logout', self.logout_handler), ] async def authenticate(self, handler, data=None): raise NotImplementedError() _deprecated_oauth_aliases = {} def _deprecated_oauth_trait(self, change): """observer for deprecated traits""" old_attr = change.name new_attr, version = self._deprecated_oauth_aliases.get(old_attr) new_value = getattr(self, new_attr) if new_value != change.new: # only warn if different # protects backward-compatible config from warnings # if they set the same value under both names self.log.warning( "{cls}.{old} is deprecated in {cls} {version}, use {cls}.{new} instead".format( cls=self.__class__.__name__, old=old_attr, new=new_attr, version=version, ) ) setattr(self, new_attr, change.new) def __init__(self, **kwargs): # observe deprecated config names in oauthenticator if self._deprecated_oauth_aliases: self.observe( self._deprecated_oauth_trait, names=list(self._deprecated_oauth_aliases) ) super().__init__(**kwargs)
coffeateam__coffea-casa
63
63-184-13
infile
check_code
[ "active_server_limit", "add_header", "admin_users", "allow_named_servers", "app", "append_query_parameters", "application", "auth_to_user", "authenticate", "authenticate_prometheus", "authenticator", "base_url", "check_arguments", "check_code", "check_error", "check_etag_header", "check_state", "check_xsrf_cookie", "clear", "clear_all_cookies", "clear_cookie", "clear_header", "clear_login_cookie", "compute_etag", "concurrent_spawn_limit", "config", "content_security_policy", "cookie_max_age_days", "cookies", "create_signed_value", "create_template_loader", "csp_report_uri", "current_user", "data_received", "db", "decode_argument", "default_url", "delete", "detach", "domain", "eventlog", "expanded_scopes", "extra_error_html", "find_user", "finish", "flush", "get", "get_accessible_services", "get_argument", "get_arguments", "get_auth_token", "get_body_argument", "get_body_arguments", "get_browser_locale", "get_content_type", "get_cookie", "get_current_user", "get_current_user_cookie", "get_current_user_named_server_limit", "get_current_user_token", "get_login_url", "get_next_url", "get_query_argument", "get_query_arguments", "get_scope_filter", "get_secure_cookie", "get_secure_cookie_key_version", "get_session_cookie", "get_signed_cookie", "get_signed_cookie_key_version", "get_state_cookie", "get_state_url", "get_status", "get_template", "get_template_namespace", "get_template_path", "get_token", "get_user_locale", "has_scope", "head", "hub", "initialize", "locale", "log", "log_exception", "login_user", "named_server_limit_per_user", "oauth_provider", "on_connection_close", "on_finish", "options", "parsed_scopes", "patch", "path_args", "path_kwargs", "post", "prepare", "proxy", "public_url", "put", "redirect", "redirect_to_server", "refresh_auth", "render", "render_embed_css", "render_embed_js", "render_linked_css", "render_linked_js", "render_string", "render_template", "request", "require_setting", "reverse_url", "send_error", "services", "set_cookie", "set_default_headers", "set_etag_header", "set_header", "set_hub_cookie", "set_login_cookie", "set_secure_cookie", "set_service_cookie", "set_session_cookie", "set_signed_cookie", "set_status", "settings", "slow_spawn_timeout", "slow_stop_timeout", "spawn_home_error", "spawn_single_user", "spawner_class", "static_url", "statsd", "stop_single_user", "subdomain_host", "SUPPORTED_METHODS", "template_namespace", "ui", "user_from_username", "user_stopped", "users", "version_hash", "write", "write_error", "xsrf_form_html", "xsrf_token", "_accept_cookie_auth", "_accept_token_auth", "_active_modules", "_auto_finish", "_break_cycles", "_clear_representation_headers", "_convert_header_value", "_current_user", "_decode_xsrf_token", "_execute", "_finished", "_get_argument", "_get_arguments", "_get_raw_xsrf_token", "_handle_request_exception", "_headers", "_headers_written", "_initialize", "_INVALID_HEADER_CHAR_RE", "_jupyterhub_user", "_locale", "_log", "_login_user_pre_08", "_new_cookie", "_prepared_future", "_raw_xsrf_token", "_reason", "_record_activity", "_refreshed_users", "_remove_control_chars_regex", "_request_summary", "_resolve_roles_and_scopes", "_session_id", "_set_cookie", "_set_user_cookie", "_state_cookie", "_status_code", "_stream_request_body", "_template_loader_lock", "_template_loaders", "_token_authenticated", "_transforms", "_ui_method", "_ui_module", "_unimplemented_method", "_user_for_cookie", "_user_from_orm", "_validate_next_url", "_write_buffer", "_xsrf_safe_methods", "_xsrf_token", "_xsrf_token_id", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init__", "__init_subclass__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__slots__", "__str__" ]
""" Base classes for Custom Authenticator to use OAuth with JupyterHub Most of the code c/o Kyle Kelley (@rgbkrk) """ import base64 import json import os import uuid from urllib.parse import quote from urllib.parse import urlparse from urllib.parse import urlunparse from jupyterhub.auth import Authenticator from jupyterhub.handlers import BaseHandler from jupyterhub.handlers import LogoutHandler from jupyterhub.utils import url_path_join from tornado import web from tornado.auth import OAuth2Mixin from tornado.httpclient import AsyncHTTPClient from tornado.httpclient import HTTPClientError from tornado.log import app_log from traitlets import Any from traitlets import Bool from traitlets import default from traitlets import Dict from traitlets import List from traitlets import Unicode def guess_callback_uri(protocol, host, hub_server_url): return '{proto}://{host}{path}'.format( proto=protocol, host=host, path=url_path_join(hub_server_url, 'oauth_callback') ) STATE_COOKIE_NAME = 'oauthenticator-state' def _serialize_state(state): """Serialize OAuth state to a base64 string after passing through JSON""" json_state = json.dumps(state) return base64.urlsafe_b64encode(json_state.encode('utf8')).decode('ascii') def _deserialize_state(b64_state): """Deserialize OAuth state as serialized in _serialize_state""" if isinstance(b64_state, str): b64_state = b64_state.encode('ascii') try: json_state = base64.urlsafe_b64decode(b64_state).decode('utf8') except ValueError: app_log.error("Failed to b64-decode state: %r", b64_state) return {} try: return json.loads(json_state) except ValueError: app_log.error("Failed to json-decode state: %r", json_state) return {} class OAuthLoginHandler(OAuth2Mixin, BaseHandler): """Base class for OAuth login handler Typically subclasses will need """ # these URLs are part of the OAuth2Mixin API # get them from the Authenticator object @property def _OAUTH_AUTHORIZE_URL(self): return self.authenticator.authorize_url @property def _OAUTH_ACCESS_TOKEN_URL(self): return self.authenticator.token_url @property def _OAUTH_USERINFO_URL(self): return self.authenticator.userdata_url def set_state_cookie(self, state): self._set_cookie(STATE_COOKIE_NAME, state, expires_days=1, httponly=True) _state = None def get_state(self): next_url = original_next_url = self.get_argument('next', None) if next_url: # avoid browsers treating \ as / next_url = next_url.replace('\\', quote('\\')) # disallow hostname-having urls, # force absolute path redirect urlinfo = urlparse(next_url) next_url = urlinfo._replace( scheme='', netloc='', path='/' + urlinfo.path.lstrip('/') ).geturl() if next_url != original_next_url: self.log.warning( "Ignoring next_url %r, using %r", original_next_url, next_url ) if self._state is None: self._state = _serialize_state( {'state_id': uuid.uuid4().hex, 'next_url': next_url} ) return self._state def get(self): redirect_uri = self.authenticator.get_callback_url(self) extra_params = self.authenticator.extra_authorize_params.copy() self.log.info('OAuth redirect: %r', redirect_uri) state = self.get_state() self.set_state_cookie(state) extra_params['state'] = state self.authorize_redirect( redirect_uri=redirect_uri, client_id=self.authenticator.client_id, scope=self.authenticator.scope, extra_params=extra_params, response_type='code', ) class OAuthCallbackHandler(BaseHandler): """Basic handler for OAuth callback. Calls authenticator to verify username.""" _state_cookie = None def get_state_cookie(self): """Get OAuth state from cookies To be compared with the value in redirect URL """ if self._state_cookie is None: self._state_cookie = ( self.get_secure_cookie(STATE_COOKIE_NAME) or b'' ).decode('utf8', 'replace') self.clear_cookie(STATE_COOKIE_NAME) return self._state_cookie def get_state_url(self): """Get OAuth state from URL parameters to be compared with the value in cookies """ return self.get_argument("state") def check_state(self): """Verify OAuth state compare value in cookie with redirect url param """ cookie_state = self.get_state_cookie() url_state = self.get_state_url() if not cookie_state: raise web.HTTPError(400, "OAuth state missing from cookies") if not url_state: raise web.HTTPError(400, "OAuth state missing from URL") if cookie_state != url_state: self.log.warning("OAuth state mismatch: %s != %s", cookie_state, url_state) raise web.HTTPError(400, "OAuth state mismatch") def check_error(self): """Check the OAuth code""" error = self.get_argument("error", False) if error: message = self.get_argument("error_description", error) raise web.HTTPError(400, "OAuth error: %s" % message) def check_code(self): """Check the OAuth code""" if not self.get_argument("code", False): raise web.HTTPError(400, "OAuth callback made without a code") def check_arguments(self): """Validate the arguments of the redirect Default: - check for oauth-standard error, error_description arguments - check that there's a code - check that state matches """ self.check_error() self.
() self.check_state() def append_query_parameters(self, url, exclude=None): """JupyterHub 1.2 appends query parameters by default in get_next_url This is not appropriate for oauth callback handlers, where params are oauth state, code, etc. Override the method used to append parameters to next_url to not preserve any parameters """ return url def get_next_url(self, user=None): """Get the redirect target from the state field""" state = self.get_state_url() if state: next_url = _deserialize_state(state).get('next_url') if next_url: return next_url # JupyterHub 0.8 adds default .get_next_url for a fallback if hasattr(BaseHandler, 'get_next_url'): return super().get_next_url(user) return url_path_join(self.hub.server.base_url, 'home') async def _login_user_pre_08(self): """login_user simplifies the login+cookie+auth_state process in JupyterHub 0.8 _login_user_07 is for backward-compatibility with JupyterHub 0.7 """ user_info = await self.authenticator.get_authenticated_user(self, None) if user_info is None: return if isinstance(user_info, dict): username = user_info['name'] else: username = user_info user = self.user_from_username(username) self.set_login_cookie(user) return user if not hasattr(BaseHandler, 'login_user'): # JupyterHub 0.7 doesn't have .login_user login_user = _login_user_pre_08 async def get(self): self.check_arguments() user = await self.login_user() if user is None: # todo: custom error page? raise web.HTTPError(403) self.redirect(self.get_next_url(user)) class OAuthLogoutHandler(LogoutHandler): async def handle_logout(self): self.clear_cookie(STATE_COOKIE_NAME) async def render_logout_page(self): if self.authenticator.logout_redirect_url: self.redirect(self.authenticator.logout_redirect_url) return return await super().render_logout_page() class OAuthenticator(Authenticator): """Base class for OAuthenticators Subclasses must override: login_service (string identifying the service provider) authenticate (method takes one arg - the request handler handling the oauth callback) """ login_handler = OAuthLoginHandler callback_handler = OAuthCallbackHandler logout_handler = OAuthLogoutHandler authorize_url = Unicode( config=True, help="""The authenticate url for initiating oauth""" ) @default("authorize_url") def _authorize_url_default(self): return os.environ.get("OAUTH2_AUTHORIZE_URL", "") token_url = Unicode( config=True, help="""The url retrieving an access token at the completion of oauth""", ) @default("token_url") def _token_url_default(self): return os.environ.get("OAUTH2_TOKEN_URL", "") userdata_url = Unicode( config=True, help="""The url for retrieving user data with a completed access token""", ) @default("userdata_url") def _userdata_url_default(self): return os.environ.get("OAUTH2_USERDATA_URL", "") logout_redirect_url = Unicode(config=True, help="""URL for logging out of Auth0""") @default("logout_redirect_url") def _logout_redirect_url_default(self): return os.getenv("OAUTH_LOGOUT_REDIRECT_URL", "") scope = List( Unicode(), config=True, help="""The OAuth scopes to request. See the OAuth documentation of your OAuth provider for options. For GitHub in particular, you can see github_scopes.md in this repo. """, ) extra_authorize_params = Dict( config=True, help="""Extra GET params to send along with the initial OAuth request to the OAuth provider.""", ) login_service = 'override in subclass' oauth_callback_url = Unicode( os.getenv('OAUTH_CALLBACK_URL', ''), config=True, help="""Callback URL to use. Typically `https://{host}/hub/oauth_callback`""", ) client_id_env = '' client_id = Unicode(config=True) def _client_id_default(self): if self.client_id_env: client_id = os.getenv(self.client_id_env, '') if client_id: return client_id return os.getenv('OAUTH_CLIENT_ID', '') client_secret_env = '' client_secret = Unicode(config=True) def _client_secret_default(self): if self.client_secret_env: client_secret = os.getenv(self.client_secret_env, '') if client_secret: return client_secret return os.getenv('OAUTH_CLIENT_SECRET', '') validate_server_cert_env = 'OAUTH_TLS_VERIFY' validate_server_cert = Bool(config=True) def _validate_server_cert_default(self): env_value = os.getenv(self.validate_server_cert_env, '') if env_value == '0': return False else: return True http_client = Any() @default("http_client") def _default_http_client(self): return AsyncHTTPClient() async def fetch(self, req, label="fetching", parse_json=True, **kwargs): """Wrapper for http requests logs error responses, parses successful JSON responses Args: req: tornado HTTPRequest label (str): label describing what is happening, used in log message when the request fails. **kwargs: remaining keyword args passed to underlying `client.fetch(req, **kwargs)` Returns: r: parsed JSON response """ try: resp = await self.http_client.fetch(req, **kwargs) except HTTPClientError as e: if e.response: # Log failed response message for debugging purposes message = e.response.body.decode("utf8", "replace") try: # guess json, reformat for readability json_message = json.loads(message) except ValueError: # not json pass else: # reformat json log message for readability message = json.dumps(json_message, sort_keys=True, indent=1) else: # didn't get a response, e.g. connection error message = str(e) # log url without query params url = urlunparse(urlparse(req.url)._replace(query="")) app_log.error(f"Error {label} {e.code} {req.method} {url}: {message}") raise e else: if parse_json: if resp.body: return json.loads(resp.body.decode('utf8', 'replace')) else: # empty body is None return None else: return resp def login_url(self, base_url): return url_path_join(base_url, 'oauth_login') def logout_url(self, base_url): return url_path_join(base_url, 'logout') def get_callback_url(self, handler=None): """Get my OAuth redirect URL Either from config or guess based on the current request. """ if self.oauth_callback_url: return self.oauth_callback_url elif handler: return guess_callback_uri( handler.request.protocol, handler.request.host, handler.hub.server.base_url, ) else: raise ValueError( "Specify callback oauth_callback_url or give me a handler to guess with" ) def get_handlers(self, app): return [ (r'/oauth_login', self.login_handler), (r'/oauth_callback', self.callback_handler), (r'/logout', self.logout_handler), ] async def authenticate(self, handler, data=None): raise NotImplementedError() _deprecated_oauth_aliases = {} def _deprecated_oauth_trait(self, change): """observer for deprecated traits""" old_attr = change.name new_attr, version = self._deprecated_oauth_aliases.get(old_attr) new_value = getattr(self, new_attr) if new_value != change.new: # only warn if different # protects backward-compatible config from warnings # if they set the same value under both names self.log.warning( "{cls}.{old} is deprecated in {cls} {version}, use {cls}.{new} instead".format( cls=self.__class__.__name__, old=old_attr, new=new_attr, version=version, ) ) setattr(self, new_attr, change.new) def __init__(self, **kwargs): # observe deprecated config names in oauthenticator if self._deprecated_oauth_aliases: self.observe( self._deprecated_oauth_trait, names=list(self._deprecated_oauth_aliases) ) super().__init__(**kwargs)
coffeateam__coffea-casa
63
63-185-13
infile
check_state
[ "active_server_limit", "add_header", "admin_users", "allow_named_servers", "app", "append_query_parameters", "application", "auth_to_user", "authenticate", "authenticate_prometheus", "authenticator", "base_url", "check_arguments", "check_code", "check_error", "check_etag_header", "check_state", "check_xsrf_cookie", "clear", "clear_all_cookies", "clear_cookie", "clear_header", "clear_login_cookie", "compute_etag", "concurrent_spawn_limit", "config", "content_security_policy", "cookie_max_age_days", "cookies", "create_signed_value", "create_template_loader", "csp_report_uri", "current_user", "data_received", "db", "decode_argument", "default_url", "delete", "detach", "domain", "eventlog", "expanded_scopes", "extra_error_html", "find_user", "finish", "flush", "get", "get_accessible_services", "get_argument", "get_arguments", "get_auth_token", "get_body_argument", "get_body_arguments", "get_browser_locale", "get_content_type", "get_cookie", "get_current_user", "get_current_user_cookie", "get_current_user_named_server_limit", "get_current_user_token", "get_login_url", "get_next_url", "get_query_argument", "get_query_arguments", "get_scope_filter", "get_secure_cookie", "get_secure_cookie_key_version", "get_session_cookie", "get_signed_cookie", "get_signed_cookie_key_version", "get_state_cookie", "get_state_url", "get_status", "get_template", "get_template_namespace", "get_template_path", "get_token", "get_user_locale", "has_scope", "head", "hub", "initialize", "locale", "log", "log_exception", "login_user", "named_server_limit_per_user", "oauth_provider", "on_connection_close", "on_finish", "options", "parsed_scopes", "patch", "path_args", "path_kwargs", "post", "prepare", "proxy", "public_url", "put", "redirect", "redirect_to_server", "refresh_auth", "render", "render_embed_css", "render_embed_js", "render_linked_css", "render_linked_js", "render_string", "render_template", "request", "require_setting", "reverse_url", "send_error", "services", "set_cookie", "set_default_headers", "set_etag_header", "set_header", "set_hub_cookie", "set_login_cookie", "set_secure_cookie", "set_service_cookie", "set_session_cookie", "set_signed_cookie", "set_status", "settings", "slow_spawn_timeout", "slow_stop_timeout", "spawn_home_error", "spawn_single_user", "spawner_class", "static_url", "statsd", "stop_single_user", "subdomain_host", "SUPPORTED_METHODS", "template_namespace", "ui", "user_from_username", "user_stopped", "users", "version_hash", "write", "write_error", "xsrf_form_html", "xsrf_token", "_accept_cookie_auth", "_accept_token_auth", "_active_modules", "_auto_finish", "_break_cycles", "_clear_representation_headers", "_convert_header_value", "_current_user", "_decode_xsrf_token", "_execute", "_finished", "_get_argument", "_get_arguments", "_get_raw_xsrf_token", "_handle_request_exception", "_headers", "_headers_written", "_initialize", "_INVALID_HEADER_CHAR_RE", "_jupyterhub_user", "_locale", "_log", "_login_user_pre_08", "_new_cookie", "_prepared_future", "_raw_xsrf_token", "_reason", "_record_activity", "_refreshed_users", "_remove_control_chars_regex", "_request_summary", "_resolve_roles_and_scopes", "_session_id", "_set_cookie", "_set_user_cookie", "_state_cookie", "_status_code", "_stream_request_body", "_template_loader_lock", "_template_loaders", "_token_authenticated", "_transforms", "_ui_method", "_ui_module", "_unimplemented_method", "_user_for_cookie", "_user_from_orm", "_validate_next_url", "_write_buffer", "_xsrf_safe_methods", "_xsrf_token", "_xsrf_token_id", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init__", "__init_subclass__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__slots__", "__str__" ]
""" Base classes for Custom Authenticator to use OAuth with JupyterHub Most of the code c/o Kyle Kelley (@rgbkrk) """ import base64 import json import os import uuid from urllib.parse import quote from urllib.parse import urlparse from urllib.parse import urlunparse from jupyterhub.auth import Authenticator from jupyterhub.handlers import BaseHandler from jupyterhub.handlers import LogoutHandler from jupyterhub.utils import url_path_join from tornado import web from tornado.auth import OAuth2Mixin from tornado.httpclient import AsyncHTTPClient from tornado.httpclient import HTTPClientError from tornado.log import app_log from traitlets import Any from traitlets import Bool from traitlets import default from traitlets import Dict from traitlets import List from traitlets import Unicode def guess_callback_uri(protocol, host, hub_server_url): return '{proto}://{host}{path}'.format( proto=protocol, host=host, path=url_path_join(hub_server_url, 'oauth_callback') ) STATE_COOKIE_NAME = 'oauthenticator-state' def _serialize_state(state): """Serialize OAuth state to a base64 string after passing through JSON""" json_state = json.dumps(state) return base64.urlsafe_b64encode(json_state.encode('utf8')).decode('ascii') def _deserialize_state(b64_state): """Deserialize OAuth state as serialized in _serialize_state""" if isinstance(b64_state, str): b64_state = b64_state.encode('ascii') try: json_state = base64.urlsafe_b64decode(b64_state).decode('utf8') except ValueError: app_log.error("Failed to b64-decode state: %r", b64_state) return {} try: return json.loads(json_state) except ValueError: app_log.error("Failed to json-decode state: %r", json_state) return {} class OAuthLoginHandler(OAuth2Mixin, BaseHandler): """Base class for OAuth login handler Typically subclasses will need """ # these URLs are part of the OAuth2Mixin API # get them from the Authenticator object @property def _OAUTH_AUTHORIZE_URL(self): return self.authenticator.authorize_url @property def _OAUTH_ACCESS_TOKEN_URL(self): return self.authenticator.token_url @property def _OAUTH_USERINFO_URL(self): return self.authenticator.userdata_url def set_state_cookie(self, state): self._set_cookie(STATE_COOKIE_NAME, state, expires_days=1, httponly=True) _state = None def get_state(self): next_url = original_next_url = self.get_argument('next', None) if next_url: # avoid browsers treating \ as / next_url = next_url.replace('\\', quote('\\')) # disallow hostname-having urls, # force absolute path redirect urlinfo = urlparse(next_url) next_url = urlinfo._replace( scheme='', netloc='', path='/' + urlinfo.path.lstrip('/') ).geturl() if next_url != original_next_url: self.log.warning( "Ignoring next_url %r, using %r", original_next_url, next_url ) if self._state is None: self._state = _serialize_state( {'state_id': uuid.uuid4().hex, 'next_url': next_url} ) return self._state def get(self): redirect_uri = self.authenticator.get_callback_url(self) extra_params = self.authenticator.extra_authorize_params.copy() self.log.info('OAuth redirect: %r', redirect_uri) state = self.get_state() self.set_state_cookie(state) extra_params['state'] = state self.authorize_redirect( redirect_uri=redirect_uri, client_id=self.authenticator.client_id, scope=self.authenticator.scope, extra_params=extra_params, response_type='code', ) class OAuthCallbackHandler(BaseHandler): """Basic handler for OAuth callback. Calls authenticator to verify username.""" _state_cookie = None def get_state_cookie(self): """Get OAuth state from cookies To be compared with the value in redirect URL """ if self._state_cookie is None: self._state_cookie = ( self.get_secure_cookie(STATE_COOKIE_NAME) or b'' ).decode('utf8', 'replace') self.clear_cookie(STATE_COOKIE_NAME) return self._state_cookie def get_state_url(self): """Get OAuth state from URL parameters to be compared with the value in cookies """ return self.get_argument("state") def check_state(self): """Verify OAuth state compare value in cookie with redirect url param """ cookie_state = self.get_state_cookie() url_state = self.get_state_url() if not cookie_state: raise web.HTTPError(400, "OAuth state missing from cookies") if not url_state: raise web.HTTPError(400, "OAuth state missing from URL") if cookie_state != url_state: self.log.warning("OAuth state mismatch: %s != %s", cookie_state, url_state) raise web.HTTPError(400, "OAuth state mismatch") def check_error(self): """Check the OAuth code""" error = self.get_argument("error", False) if error: message = self.get_argument("error_description", error) raise web.HTTPError(400, "OAuth error: %s" % message) def check_code(self): """Check the OAuth code""" if not self.get_argument("code", False): raise web.HTTPError(400, "OAuth callback made without a code") def check_arguments(self): """Validate the arguments of the redirect Default: - check for oauth-standard error, error_description arguments - check that there's a code - check that state matches """ self.check_error() self.check_code() self.
() def append_query_parameters(self, url, exclude=None): """JupyterHub 1.2 appends query parameters by default in get_next_url This is not appropriate for oauth callback handlers, where params are oauth state, code, etc. Override the method used to append parameters to next_url to not preserve any parameters """ return url def get_next_url(self, user=None): """Get the redirect target from the state field""" state = self.get_state_url() if state: next_url = _deserialize_state(state).get('next_url') if next_url: return next_url # JupyterHub 0.8 adds default .get_next_url for a fallback if hasattr(BaseHandler, 'get_next_url'): return super().get_next_url(user) return url_path_join(self.hub.server.base_url, 'home') async def _login_user_pre_08(self): """login_user simplifies the login+cookie+auth_state process in JupyterHub 0.8 _login_user_07 is for backward-compatibility with JupyterHub 0.7 """ user_info = await self.authenticator.get_authenticated_user(self, None) if user_info is None: return if isinstance(user_info, dict): username = user_info['name'] else: username = user_info user = self.user_from_username(username) self.set_login_cookie(user) return user if not hasattr(BaseHandler, 'login_user'): # JupyterHub 0.7 doesn't have .login_user login_user = _login_user_pre_08 async def get(self): self.check_arguments() user = await self.login_user() if user is None: # todo: custom error page? raise web.HTTPError(403) self.redirect(self.get_next_url(user)) class OAuthLogoutHandler(LogoutHandler): async def handle_logout(self): self.clear_cookie(STATE_COOKIE_NAME) async def render_logout_page(self): if self.authenticator.logout_redirect_url: self.redirect(self.authenticator.logout_redirect_url) return return await super().render_logout_page() class OAuthenticator(Authenticator): """Base class for OAuthenticators Subclasses must override: login_service (string identifying the service provider) authenticate (method takes one arg - the request handler handling the oauth callback) """ login_handler = OAuthLoginHandler callback_handler = OAuthCallbackHandler logout_handler = OAuthLogoutHandler authorize_url = Unicode( config=True, help="""The authenticate url for initiating oauth""" ) @default("authorize_url") def _authorize_url_default(self): return os.environ.get("OAUTH2_AUTHORIZE_URL", "") token_url = Unicode( config=True, help="""The url retrieving an access token at the completion of oauth""", ) @default("token_url") def _token_url_default(self): return os.environ.get("OAUTH2_TOKEN_URL", "") userdata_url = Unicode( config=True, help="""The url for retrieving user data with a completed access token""", ) @default("userdata_url") def _userdata_url_default(self): return os.environ.get("OAUTH2_USERDATA_URL", "") logout_redirect_url = Unicode(config=True, help="""URL for logging out of Auth0""") @default("logout_redirect_url") def _logout_redirect_url_default(self): return os.getenv("OAUTH_LOGOUT_REDIRECT_URL", "") scope = List( Unicode(), config=True, help="""The OAuth scopes to request. See the OAuth documentation of your OAuth provider for options. For GitHub in particular, you can see github_scopes.md in this repo. """, ) extra_authorize_params = Dict( config=True, help="""Extra GET params to send along with the initial OAuth request to the OAuth provider.""", ) login_service = 'override in subclass' oauth_callback_url = Unicode( os.getenv('OAUTH_CALLBACK_URL', ''), config=True, help="""Callback URL to use. Typically `https://{host}/hub/oauth_callback`""", ) client_id_env = '' client_id = Unicode(config=True) def _client_id_default(self): if self.client_id_env: client_id = os.getenv(self.client_id_env, '') if client_id: return client_id return os.getenv('OAUTH_CLIENT_ID', '') client_secret_env = '' client_secret = Unicode(config=True) def _client_secret_default(self): if self.client_secret_env: client_secret = os.getenv(self.client_secret_env, '') if client_secret: return client_secret return os.getenv('OAUTH_CLIENT_SECRET', '') validate_server_cert_env = 'OAUTH_TLS_VERIFY' validate_server_cert = Bool(config=True) def _validate_server_cert_default(self): env_value = os.getenv(self.validate_server_cert_env, '') if env_value == '0': return False else: return True http_client = Any() @default("http_client") def _default_http_client(self): return AsyncHTTPClient() async def fetch(self, req, label="fetching", parse_json=True, **kwargs): """Wrapper for http requests logs error responses, parses successful JSON responses Args: req: tornado HTTPRequest label (str): label describing what is happening, used in log message when the request fails. **kwargs: remaining keyword args passed to underlying `client.fetch(req, **kwargs)` Returns: r: parsed JSON response """ try: resp = await self.http_client.fetch(req, **kwargs) except HTTPClientError as e: if e.response: # Log failed response message for debugging purposes message = e.response.body.decode("utf8", "replace") try: # guess json, reformat for readability json_message = json.loads(message) except ValueError: # not json pass else: # reformat json log message for readability message = json.dumps(json_message, sort_keys=True, indent=1) else: # didn't get a response, e.g. connection error message = str(e) # log url without query params url = urlunparse(urlparse(req.url)._replace(query="")) app_log.error(f"Error {label} {e.code} {req.method} {url}: {message}") raise e else: if parse_json: if resp.body: return json.loads(resp.body.decode('utf8', 'replace')) else: # empty body is None return None else: return resp def login_url(self, base_url): return url_path_join(base_url, 'oauth_login') def logout_url(self, base_url): return url_path_join(base_url, 'logout') def get_callback_url(self, handler=None): """Get my OAuth redirect URL Either from config or guess based on the current request. """ if self.oauth_callback_url: return self.oauth_callback_url elif handler: return guess_callback_uri( handler.request.protocol, handler.request.host, handler.hub.server.base_url, ) else: raise ValueError( "Specify callback oauth_callback_url or give me a handler to guess with" ) def get_handlers(self, app): return [ (r'/oauth_login', self.login_handler), (r'/oauth_callback', self.callback_handler), (r'/logout', self.logout_handler), ] async def authenticate(self, handler, data=None): raise NotImplementedError() _deprecated_oauth_aliases = {} def _deprecated_oauth_trait(self, change): """observer for deprecated traits""" old_attr = change.name new_attr, version = self._deprecated_oauth_aliases.get(old_attr) new_value = getattr(self, new_attr) if new_value != change.new: # only warn if different # protects backward-compatible config from warnings # if they set the same value under both names self.log.warning( "{cls}.{old} is deprecated in {cls} {version}, use {cls}.{new} instead".format( cls=self.__class__.__name__, old=old_attr, new=new_attr, version=version, ) ) setattr(self, new_attr, change.new) def __init__(self, **kwargs): # observe deprecated config names in oauthenticator if self._deprecated_oauth_aliases: self.observe( self._deprecated_oauth_trait, names=list(self._deprecated_oauth_aliases) ) super().__init__(**kwargs)
coffeateam__coffea-casa
63
63-198-21
infile
get_state_url
[ "active_server_limit", "add_header", "admin_users", "allow_named_servers", "app", "append_query_parameters", "application", "auth_to_user", "authenticate", "authenticate_prometheus", "authenticator", "base_url", "check_arguments", "check_code", "check_error", "check_etag_header", "check_state", "check_xsrf_cookie", "clear", "clear_all_cookies", "clear_cookie", "clear_header", "clear_login_cookie", "compute_etag", "concurrent_spawn_limit", "config", "content_security_policy", "cookie_max_age_days", "cookies", "create_signed_value", "create_template_loader", "csp_report_uri", "current_user", "data_received", "db", "decode_argument", "default_url", "delete", "detach", "domain", "eventlog", "expanded_scopes", "extra_error_html", "find_user", "finish", "flush", "get", "get_accessible_services", "get_argument", "get_arguments", "get_auth_token", "get_body_argument", "get_body_arguments", "get_browser_locale", "get_content_type", "get_cookie", "get_current_user", "get_current_user_cookie", "get_current_user_named_server_limit", "get_current_user_token", "get_login_url", "get_next_url", "get_query_argument", "get_query_arguments", "get_scope_filter", "get_secure_cookie", "get_secure_cookie_key_version", "get_session_cookie", "get_signed_cookie", "get_signed_cookie_key_version", "get_state_cookie", "get_state_url", "get_status", "get_template", "get_template_namespace", "get_template_path", "get_token", "get_user_locale", "has_scope", "head", "hub", "initialize", "locale", "log", "log_exception", "login_user", "named_server_limit_per_user", "oauth_provider", "on_connection_close", "on_finish", "options", "parsed_scopes", "patch", "path_args", "path_kwargs", "post", "prepare", "proxy", "public_url", "put", "redirect", "redirect_to_server", "refresh_auth", "render", "render_embed_css", "render_embed_js", "render_linked_css", "render_linked_js", "render_string", "render_template", "request", "require_setting", "reverse_url", "send_error", "services", "set_cookie", "set_default_headers", "set_etag_header", "set_header", "set_hub_cookie", "set_login_cookie", "set_secure_cookie", "set_service_cookie", "set_session_cookie", "set_signed_cookie", "set_status", "settings", "slow_spawn_timeout", "slow_stop_timeout", "spawn_home_error", "spawn_single_user", "spawner_class", "static_url", "statsd", "stop_single_user", "subdomain_host", "SUPPORTED_METHODS", "template_namespace", "ui", "user_from_username", "user_stopped", "users", "version_hash", "write", "write_error", "xsrf_form_html", "xsrf_token", "_accept_cookie_auth", "_accept_token_auth", "_active_modules", "_auto_finish", "_break_cycles", "_clear_representation_headers", "_convert_header_value", "_current_user", "_decode_xsrf_token", "_execute", "_finished", "_get_argument", "_get_arguments", "_get_raw_xsrf_token", "_handle_request_exception", "_headers", "_headers_written", "_initialize", "_INVALID_HEADER_CHAR_RE", "_jupyterhub_user", "_locale", "_log", "_login_user_pre_08", "_new_cookie", "_prepared_future", "_raw_xsrf_token", "_reason", "_record_activity", "_refreshed_users", "_remove_control_chars_regex", "_request_summary", "_resolve_roles_and_scopes", "_session_id", "_set_cookie", "_set_user_cookie", "_state_cookie", "_status_code", "_stream_request_body", "_template_loader_lock", "_template_loaders", "_token_authenticated", "_transforms", "_ui_method", "_ui_module", "_unimplemented_method", "_user_for_cookie", "_user_from_orm", "_validate_next_url", "_write_buffer", "_xsrf_safe_methods", "_xsrf_token", "_xsrf_token_id", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init__", "__init_subclass__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__slots__", "__str__" ]
""" Base classes for Custom Authenticator to use OAuth with JupyterHub Most of the code c/o Kyle Kelley (@rgbkrk) """ import base64 import json import os import uuid from urllib.parse import quote from urllib.parse import urlparse from urllib.parse import urlunparse from jupyterhub.auth import Authenticator from jupyterhub.handlers import BaseHandler from jupyterhub.handlers import LogoutHandler from jupyterhub.utils import url_path_join from tornado import web from tornado.auth import OAuth2Mixin from tornado.httpclient import AsyncHTTPClient from tornado.httpclient import HTTPClientError from tornado.log import app_log from traitlets import Any from traitlets import Bool from traitlets import default from traitlets import Dict from traitlets import List from traitlets import Unicode def guess_callback_uri(protocol, host, hub_server_url): return '{proto}://{host}{path}'.format( proto=protocol, host=host, path=url_path_join(hub_server_url, 'oauth_callback') ) STATE_COOKIE_NAME = 'oauthenticator-state' def _serialize_state(state): """Serialize OAuth state to a base64 string after passing through JSON""" json_state = json.dumps(state) return base64.urlsafe_b64encode(json_state.encode('utf8')).decode('ascii') def _deserialize_state(b64_state): """Deserialize OAuth state as serialized in _serialize_state""" if isinstance(b64_state, str): b64_state = b64_state.encode('ascii') try: json_state = base64.urlsafe_b64decode(b64_state).decode('utf8') except ValueError: app_log.error("Failed to b64-decode state: %r", b64_state) return {} try: return json.loads(json_state) except ValueError: app_log.error("Failed to json-decode state: %r", json_state) return {} class OAuthLoginHandler(OAuth2Mixin, BaseHandler): """Base class for OAuth login handler Typically subclasses will need """ # these URLs are part of the OAuth2Mixin API # get them from the Authenticator object @property def _OAUTH_AUTHORIZE_URL(self): return self.authenticator.authorize_url @property def _OAUTH_ACCESS_TOKEN_URL(self): return self.authenticator.token_url @property def _OAUTH_USERINFO_URL(self): return self.authenticator.userdata_url def set_state_cookie(self, state): self._set_cookie(STATE_COOKIE_NAME, state, expires_days=1, httponly=True) _state = None def get_state(self): next_url = original_next_url = self.get_argument('next', None) if next_url: # avoid browsers treating \ as / next_url = next_url.replace('\\', quote('\\')) # disallow hostname-having urls, # force absolute path redirect urlinfo = urlparse(next_url) next_url = urlinfo._replace( scheme='', netloc='', path='/' + urlinfo.path.lstrip('/') ).geturl() if next_url != original_next_url: self.log.warning( "Ignoring next_url %r, using %r", original_next_url, next_url ) if self._state is None: self._state = _serialize_state( {'state_id': uuid.uuid4().hex, 'next_url': next_url} ) return self._state def get(self): redirect_uri = self.authenticator.get_callback_url(self) extra_params = self.authenticator.extra_authorize_params.copy() self.log.info('OAuth redirect: %r', redirect_uri) state = self.get_state() self.set_state_cookie(state) extra_params['state'] = state self.authorize_redirect( redirect_uri=redirect_uri, client_id=self.authenticator.client_id, scope=self.authenticator.scope, extra_params=extra_params, response_type='code', ) class OAuthCallbackHandler(BaseHandler): """Basic handler for OAuth callback. Calls authenticator to verify username.""" _state_cookie = None def get_state_cookie(self): """Get OAuth state from cookies To be compared with the value in redirect URL """ if self._state_cookie is None: self._state_cookie = ( self.get_secure_cookie(STATE_COOKIE_NAME) or b'' ).decode('utf8', 'replace') self.clear_cookie(STATE_COOKIE_NAME) return self._state_cookie def get_state_url(self): """Get OAuth state from URL parameters to be compared with the value in cookies """ return self.get_argument("state") def check_state(self): """Verify OAuth state compare value in cookie with redirect url param """ cookie_state = self.get_state_cookie() url_state = self.get_state_url() if not cookie_state: raise web.HTTPError(400, "OAuth state missing from cookies") if not url_state: raise web.HTTPError(400, "OAuth state missing from URL") if cookie_state != url_state: self.log.warning("OAuth state mismatch: %s != %s", cookie_state, url_state) raise web.HTTPError(400, "OAuth state mismatch") def check_error(self): """Check the OAuth code""" error = self.get_argument("error", False) if error: message = self.get_argument("error_description", error) raise web.HTTPError(400, "OAuth error: %s" % message) def check_code(self): """Check the OAuth code""" if not self.get_argument("code", False): raise web.HTTPError(400, "OAuth callback made without a code") def check_arguments(self): """Validate the arguments of the redirect Default: - check for oauth-standard error, error_description arguments - check that there's a code - check that state matches """ self.check_error() self.check_code() self.check_state() def append_query_parameters(self, url, exclude=None): """JupyterHub 1.2 appends query parameters by default in get_next_url This is not appropriate for oauth callback handlers, where params are oauth state, code, etc. Override the method used to append parameters to next_url to not preserve any parameters """ return url def get_next_url(self, user=None): """Get the redirect target from the state field""" state = self.
() if state: next_url = _deserialize_state(state).get('next_url') if next_url: return next_url # JupyterHub 0.8 adds default .get_next_url for a fallback if hasattr(BaseHandler, 'get_next_url'): return super().get_next_url(user) return url_path_join(self.hub.server.base_url, 'home') async def _login_user_pre_08(self): """login_user simplifies the login+cookie+auth_state process in JupyterHub 0.8 _login_user_07 is for backward-compatibility with JupyterHub 0.7 """ user_info = await self.authenticator.get_authenticated_user(self, None) if user_info is None: return if isinstance(user_info, dict): username = user_info['name'] else: username = user_info user = self.user_from_username(username) self.set_login_cookie(user) return user if not hasattr(BaseHandler, 'login_user'): # JupyterHub 0.7 doesn't have .login_user login_user = _login_user_pre_08 async def get(self): self.check_arguments() user = await self.login_user() if user is None: # todo: custom error page? raise web.HTTPError(403) self.redirect(self.get_next_url(user)) class OAuthLogoutHandler(LogoutHandler): async def handle_logout(self): self.clear_cookie(STATE_COOKIE_NAME) async def render_logout_page(self): if self.authenticator.logout_redirect_url: self.redirect(self.authenticator.logout_redirect_url) return return await super().render_logout_page() class OAuthenticator(Authenticator): """Base class for OAuthenticators Subclasses must override: login_service (string identifying the service provider) authenticate (method takes one arg - the request handler handling the oauth callback) """ login_handler = OAuthLoginHandler callback_handler = OAuthCallbackHandler logout_handler = OAuthLogoutHandler authorize_url = Unicode( config=True, help="""The authenticate url for initiating oauth""" ) @default("authorize_url") def _authorize_url_default(self): return os.environ.get("OAUTH2_AUTHORIZE_URL", "") token_url = Unicode( config=True, help="""The url retrieving an access token at the completion of oauth""", ) @default("token_url") def _token_url_default(self): return os.environ.get("OAUTH2_TOKEN_URL", "") userdata_url = Unicode( config=True, help="""The url for retrieving user data with a completed access token""", ) @default("userdata_url") def _userdata_url_default(self): return os.environ.get("OAUTH2_USERDATA_URL", "") logout_redirect_url = Unicode(config=True, help="""URL for logging out of Auth0""") @default("logout_redirect_url") def _logout_redirect_url_default(self): return os.getenv("OAUTH_LOGOUT_REDIRECT_URL", "") scope = List( Unicode(), config=True, help="""The OAuth scopes to request. See the OAuth documentation of your OAuth provider for options. For GitHub in particular, you can see github_scopes.md in this repo. """, ) extra_authorize_params = Dict( config=True, help="""Extra GET params to send along with the initial OAuth request to the OAuth provider.""", ) login_service = 'override in subclass' oauth_callback_url = Unicode( os.getenv('OAUTH_CALLBACK_URL', ''), config=True, help="""Callback URL to use. Typically `https://{host}/hub/oauth_callback`""", ) client_id_env = '' client_id = Unicode(config=True) def _client_id_default(self): if self.client_id_env: client_id = os.getenv(self.client_id_env, '') if client_id: return client_id return os.getenv('OAUTH_CLIENT_ID', '') client_secret_env = '' client_secret = Unicode(config=True) def _client_secret_default(self): if self.client_secret_env: client_secret = os.getenv(self.client_secret_env, '') if client_secret: return client_secret return os.getenv('OAUTH_CLIENT_SECRET', '') validate_server_cert_env = 'OAUTH_TLS_VERIFY' validate_server_cert = Bool(config=True) def _validate_server_cert_default(self): env_value = os.getenv(self.validate_server_cert_env, '') if env_value == '0': return False else: return True http_client = Any() @default("http_client") def _default_http_client(self): return AsyncHTTPClient() async def fetch(self, req, label="fetching", parse_json=True, **kwargs): """Wrapper for http requests logs error responses, parses successful JSON responses Args: req: tornado HTTPRequest label (str): label describing what is happening, used in log message when the request fails. **kwargs: remaining keyword args passed to underlying `client.fetch(req, **kwargs)` Returns: r: parsed JSON response """ try: resp = await self.http_client.fetch(req, **kwargs) except HTTPClientError as e: if e.response: # Log failed response message for debugging purposes message = e.response.body.decode("utf8", "replace") try: # guess json, reformat for readability json_message = json.loads(message) except ValueError: # not json pass else: # reformat json log message for readability message = json.dumps(json_message, sort_keys=True, indent=1) else: # didn't get a response, e.g. connection error message = str(e) # log url without query params url = urlunparse(urlparse(req.url)._replace(query="")) app_log.error(f"Error {label} {e.code} {req.method} {url}: {message}") raise e else: if parse_json: if resp.body: return json.loads(resp.body.decode('utf8', 'replace')) else: # empty body is None return None else: return resp def login_url(self, base_url): return url_path_join(base_url, 'oauth_login') def logout_url(self, base_url): return url_path_join(base_url, 'logout') def get_callback_url(self, handler=None): """Get my OAuth redirect URL Either from config or guess based on the current request. """ if self.oauth_callback_url: return self.oauth_callback_url elif handler: return guess_callback_uri( handler.request.protocol, handler.request.host, handler.hub.server.base_url, ) else: raise ValueError( "Specify callback oauth_callback_url or give me a handler to guess with" ) def get_handlers(self, app): return [ (r'/oauth_login', self.login_handler), (r'/oauth_callback', self.callback_handler), (r'/logout', self.logout_handler), ] async def authenticate(self, handler, data=None): raise NotImplementedError() _deprecated_oauth_aliases = {} def _deprecated_oauth_trait(self, change): """observer for deprecated traits""" old_attr = change.name new_attr, version = self._deprecated_oauth_aliases.get(old_attr) new_value = getattr(self, new_attr) if new_value != change.new: # only warn if different # protects backward-compatible config from warnings # if they set the same value under both names self.log.warning( "{cls}.{old} is deprecated in {cls} {version}, use {cls}.{new} instead".format( cls=self.__class__.__name__, old=old_attr, new=new_attr, version=version, ) ) setattr(self, new_attr, change.new) def __init__(self, **kwargs): # observe deprecated config names in oauthenticator if self._deprecated_oauth_aliases: self.observe( self._deprecated_oauth_trait, names=list(self._deprecated_oauth_aliases) ) super().__init__(**kwargs)
coffeateam__coffea-casa
63
63-200-49
commited
get
[ "clear", "copy", "fromkeys", "get", "items", "keys", "pop", "popitem", "setdefault", "update", "values", "__annotations__", "__class__", "__class_getitem__", "__contains__", "__delattr__", "__delitem__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__getitem__", "__hash__", "__init__", "__init_subclass__", "__ior__", "__iter__", "__len__", "__module__", "__ne__", "__new__", "__or__", "__reduce__", "__reduce_ex__", "__repr__", "__reversed__", "__setattr__", "__setitem__", "__sizeof__", "__slots__", "__str__" ]
""" Base classes for Custom Authenticator to use OAuth with JupyterHub Most of the code c/o Kyle Kelley (@rgbkrk) """ import base64 import json import os import uuid from urllib.parse import quote from urllib.parse import urlparse from urllib.parse import urlunparse from jupyterhub.auth import Authenticator from jupyterhub.handlers import BaseHandler from jupyterhub.handlers import LogoutHandler from jupyterhub.utils import url_path_join from tornado import web from tornado.auth import OAuth2Mixin from tornado.httpclient import AsyncHTTPClient from tornado.httpclient import HTTPClientError from tornado.log import app_log from traitlets import Any from traitlets import Bool from traitlets import default from traitlets import Dict from traitlets import List from traitlets import Unicode def guess_callback_uri(protocol, host, hub_server_url): return '{proto}://{host}{path}'.format( proto=protocol, host=host, path=url_path_join(hub_server_url, 'oauth_callback') ) STATE_COOKIE_NAME = 'oauthenticator-state' def _serialize_state(state): """Serialize OAuth state to a base64 string after passing through JSON""" json_state = json.dumps(state) return base64.urlsafe_b64encode(json_state.encode('utf8')).decode('ascii') def _deserialize_state(b64_state): """Deserialize OAuth state as serialized in _serialize_state""" if isinstance(b64_state, str): b64_state = b64_state.encode('ascii') try: json_state = base64.urlsafe_b64decode(b64_state).decode('utf8') except ValueError: app_log.error("Failed to b64-decode state: %r", b64_state) return {} try: return json.loads(json_state) except ValueError: app_log.error("Failed to json-decode state: %r", json_state) return {} class OAuthLoginHandler(OAuth2Mixin, BaseHandler): """Base class for OAuth login handler Typically subclasses will need """ # these URLs are part of the OAuth2Mixin API # get them from the Authenticator object @property def _OAUTH_AUTHORIZE_URL(self): return self.authenticator.authorize_url @property def _OAUTH_ACCESS_TOKEN_URL(self): return self.authenticator.token_url @property def _OAUTH_USERINFO_URL(self): return self.authenticator.userdata_url def set_state_cookie(self, state): self._set_cookie(STATE_COOKIE_NAME, state, expires_days=1, httponly=True) _state = None def get_state(self): next_url = original_next_url = self.get_argument('next', None) if next_url: # avoid browsers treating \ as / next_url = next_url.replace('\\', quote('\\')) # disallow hostname-having urls, # force absolute path redirect urlinfo = urlparse(next_url) next_url = urlinfo._replace( scheme='', netloc='', path='/' + urlinfo.path.lstrip('/') ).geturl() if next_url != original_next_url: self.log.warning( "Ignoring next_url %r, using %r", original_next_url, next_url ) if self._state is None: self._state = _serialize_state( {'state_id': uuid.uuid4().hex, 'next_url': next_url} ) return self._state def get(self): redirect_uri = self.authenticator.get_callback_url(self) extra_params = self.authenticator.extra_authorize_params.copy() self.log.info('OAuth redirect: %r', redirect_uri) state = self.get_state() self.set_state_cookie(state) extra_params['state'] = state self.authorize_redirect( redirect_uri=redirect_uri, client_id=self.authenticator.client_id, scope=self.authenticator.scope, extra_params=extra_params, response_type='code', ) class OAuthCallbackHandler(BaseHandler): """Basic handler for OAuth callback. Calls authenticator to verify username.""" _state_cookie = None def get_state_cookie(self): """Get OAuth state from cookies To be compared with the value in redirect URL """ if self._state_cookie is None: self._state_cookie = ( self.get_secure_cookie(STATE_COOKIE_NAME) or b'' ).decode('utf8', 'replace') self.clear_cookie(STATE_COOKIE_NAME) return self._state_cookie def get_state_url(self): """Get OAuth state from URL parameters to be compared with the value in cookies """ return self.get_argument("state") def check_state(self): """Verify OAuth state compare value in cookie with redirect url param """ cookie_state = self.get_state_cookie() url_state = self.get_state_url() if not cookie_state: raise web.HTTPError(400, "OAuth state missing from cookies") if not url_state: raise web.HTTPError(400, "OAuth state missing from URL") if cookie_state != url_state: self.log.warning("OAuth state mismatch: %s != %s", cookie_state, url_state) raise web.HTTPError(400, "OAuth state mismatch") def check_error(self): """Check the OAuth code""" error = self.get_argument("error", False) if error: message = self.get_argument("error_description", error) raise web.HTTPError(400, "OAuth error: %s" % message) def check_code(self): """Check the OAuth code""" if not self.get_argument("code", False): raise web.HTTPError(400, "OAuth callback made without a code") def check_arguments(self): """Validate the arguments of the redirect Default: - check for oauth-standard error, error_description arguments - check that there's a code - check that state matches """ self.check_error() self.check_code() self.check_state() def append_query_parameters(self, url, exclude=None): """JupyterHub 1.2 appends query parameters by default in get_next_url This is not appropriate for oauth callback handlers, where params are oauth state, code, etc. Override the method used to append parameters to next_url to not preserve any parameters """ return url def get_next_url(self, user=None): """Get the redirect target from the state field""" state = self.get_state_url() if state: next_url = _deserialize_state(state).
('next_url') if next_url: return next_url # JupyterHub 0.8 adds default .get_next_url for a fallback if hasattr(BaseHandler, 'get_next_url'): return super().get_next_url(user) return url_path_join(self.hub.server.base_url, 'home') async def _login_user_pre_08(self): """login_user simplifies the login+cookie+auth_state process in JupyterHub 0.8 _login_user_07 is for backward-compatibility with JupyterHub 0.7 """ user_info = await self.authenticator.get_authenticated_user(self, None) if user_info is None: return if isinstance(user_info, dict): username = user_info['name'] else: username = user_info user = self.user_from_username(username) self.set_login_cookie(user) return user if not hasattr(BaseHandler, 'login_user'): # JupyterHub 0.7 doesn't have .login_user login_user = _login_user_pre_08 async def get(self): self.check_arguments() user = await self.login_user() if user is None: # todo: custom error page? raise web.HTTPError(403) self.redirect(self.get_next_url(user)) class OAuthLogoutHandler(LogoutHandler): async def handle_logout(self): self.clear_cookie(STATE_COOKIE_NAME) async def render_logout_page(self): if self.authenticator.logout_redirect_url: self.redirect(self.authenticator.logout_redirect_url) return return await super().render_logout_page() class OAuthenticator(Authenticator): """Base class for OAuthenticators Subclasses must override: login_service (string identifying the service provider) authenticate (method takes one arg - the request handler handling the oauth callback) """ login_handler = OAuthLoginHandler callback_handler = OAuthCallbackHandler logout_handler = OAuthLogoutHandler authorize_url = Unicode( config=True, help="""The authenticate url for initiating oauth""" ) @default("authorize_url") def _authorize_url_default(self): return os.environ.get("OAUTH2_AUTHORIZE_URL", "") token_url = Unicode( config=True, help="""The url retrieving an access token at the completion of oauth""", ) @default("token_url") def _token_url_default(self): return os.environ.get("OAUTH2_TOKEN_URL", "") userdata_url = Unicode( config=True, help="""The url for retrieving user data with a completed access token""", ) @default("userdata_url") def _userdata_url_default(self): return os.environ.get("OAUTH2_USERDATA_URL", "") logout_redirect_url = Unicode(config=True, help="""URL for logging out of Auth0""") @default("logout_redirect_url") def _logout_redirect_url_default(self): return os.getenv("OAUTH_LOGOUT_REDIRECT_URL", "") scope = List( Unicode(), config=True, help="""The OAuth scopes to request. See the OAuth documentation of your OAuth provider for options. For GitHub in particular, you can see github_scopes.md in this repo. """, ) extra_authorize_params = Dict( config=True, help="""Extra GET params to send along with the initial OAuth request to the OAuth provider.""", ) login_service = 'override in subclass' oauth_callback_url = Unicode( os.getenv('OAUTH_CALLBACK_URL', ''), config=True, help="""Callback URL to use. Typically `https://{host}/hub/oauth_callback`""", ) client_id_env = '' client_id = Unicode(config=True) def _client_id_default(self): if self.client_id_env: client_id = os.getenv(self.client_id_env, '') if client_id: return client_id return os.getenv('OAUTH_CLIENT_ID', '') client_secret_env = '' client_secret = Unicode(config=True) def _client_secret_default(self): if self.client_secret_env: client_secret = os.getenv(self.client_secret_env, '') if client_secret: return client_secret return os.getenv('OAUTH_CLIENT_SECRET', '') validate_server_cert_env = 'OAUTH_TLS_VERIFY' validate_server_cert = Bool(config=True) def _validate_server_cert_default(self): env_value = os.getenv(self.validate_server_cert_env, '') if env_value == '0': return False else: return True http_client = Any() @default("http_client") def _default_http_client(self): return AsyncHTTPClient() async def fetch(self, req, label="fetching", parse_json=True, **kwargs): """Wrapper for http requests logs error responses, parses successful JSON responses Args: req: tornado HTTPRequest label (str): label describing what is happening, used in log message when the request fails. **kwargs: remaining keyword args passed to underlying `client.fetch(req, **kwargs)` Returns: r: parsed JSON response """ try: resp = await self.http_client.fetch(req, **kwargs) except HTTPClientError as e: if e.response: # Log failed response message for debugging purposes message = e.response.body.decode("utf8", "replace") try: # guess json, reformat for readability json_message = json.loads(message) except ValueError: # not json pass else: # reformat json log message for readability message = json.dumps(json_message, sort_keys=True, indent=1) else: # didn't get a response, e.g. connection error message = str(e) # log url without query params url = urlunparse(urlparse(req.url)._replace(query="")) app_log.error(f"Error {label} {e.code} {req.method} {url}: {message}") raise e else: if parse_json: if resp.body: return json.loads(resp.body.decode('utf8', 'replace')) else: # empty body is None return None else: return resp def login_url(self, base_url): return url_path_join(base_url, 'oauth_login') def logout_url(self, base_url): return url_path_join(base_url, 'logout') def get_callback_url(self, handler=None): """Get my OAuth redirect URL Either from config or guess based on the current request. """ if self.oauth_callback_url: return self.oauth_callback_url elif handler: return guess_callback_uri( handler.request.protocol, handler.request.host, handler.hub.server.base_url, ) else: raise ValueError( "Specify callback oauth_callback_url or give me a handler to guess with" ) def get_handlers(self, app): return [ (r'/oauth_login', self.login_handler), (r'/oauth_callback', self.callback_handler), (r'/logout', self.logout_handler), ] async def authenticate(self, handler, data=None): raise NotImplementedError() _deprecated_oauth_aliases = {} def _deprecated_oauth_trait(self, change): """observer for deprecated traits""" old_attr = change.name new_attr, version = self._deprecated_oauth_aliases.get(old_attr) new_value = getattr(self, new_attr) if new_value != change.new: # only warn if different # protects backward-compatible config from warnings # if they set the same value under both names self.log.warning( "{cls}.{old} is deprecated in {cls} {version}, use {cls}.{new} instead".format( cls=self.__class__.__name__, old=old_attr, new=new_attr, version=version, ) ) setattr(self, new_attr, change.new) def __init__(self, **kwargs): # observe deprecated config names in oauthenticator if self._deprecated_oauth_aliases: self.observe( self._deprecated_oauth_trait, names=list(self._deprecated_oauth_aliases) ) super().__init__(**kwargs)
coffeateam__coffea-casa
63
63-205-27
infile
get_next_url
[ "active_server_limit", "add_header", "admin_users", "allow_named_servers", "app", "append_query_parameters", "application", "auth_to_user", "authenticate", "authenticate_prometheus", "authenticator", "base_url", "check_etag_header", "check_xsrf_cookie", "clear", "clear_all_cookies", "clear_cookie", "clear_header", "clear_login_cookie", "compute_etag", "concurrent_spawn_limit", "config", "content_security_policy", "cookie_max_age_days", "cookies", "create_signed_value", "create_template_loader", "csp_report_uri", "current_user", "data_received", "db", "decode_argument", "default_url", "delete", "detach", "domain", "eventlog", "expanded_scopes", "extra_error_html", "find_user", "finish", "flush", "get", "get_accessible_services", "get_argument", "get_arguments", "get_auth_token", "get_body_argument", "get_body_arguments", "get_browser_locale", "get_content_type", "get_cookie", "get_current_user", "get_current_user_cookie", "get_current_user_named_server_limit", "get_current_user_token", "get_login_url", "get_next_url", "get_query_argument", "get_query_arguments", "get_scope_filter", "get_secure_cookie", "get_secure_cookie_key_version", "get_session_cookie", "get_signed_cookie", "get_signed_cookie_key_version", "get_status", "get_template", "get_template_namespace", "get_template_path", "get_token", "get_user_locale", "has_scope", "head", "hub", "initialize", "locale", "log", "log_exception", "login_user", "named_server_limit_per_user", "oauth_provider", "on_connection_close", "on_finish", "options", "parsed_scopes", "patch", "path_args", "path_kwargs", "post", "prepare", "proxy", "public_url", "put", "redirect", "redirect_to_server", "refresh_auth", "render", "render_embed_css", "render_embed_js", "render_linked_css", "render_linked_js", "render_string", "render_template", "request", "require_setting", "reverse_url", "send_error", "services", "set_cookie", "set_default_headers", "set_etag_header", "set_header", "set_hub_cookie", "set_login_cookie", "set_secure_cookie", "set_service_cookie", "set_session_cookie", "set_signed_cookie", "set_status", "settings", "slow_spawn_timeout", "slow_stop_timeout", "spawn_home_error", "spawn_single_user", "spawner_class", "static_url", "statsd", "stop_single_user", "subdomain_host", "SUPPORTED_METHODS", "template_namespace", "ui", "user_from_username", "user_stopped", "users", "version_hash", "write", "write_error", "xsrf_form_html", "xsrf_token", "_accept_cookie_auth", "_accept_token_auth", "_active_modules", "_auto_finish", "_break_cycles", "_clear_representation_headers", "_convert_header_value", "_current_user", "_decode_xsrf_token", "_execute", "_finished", "_get_argument", "_get_arguments", "_get_raw_xsrf_token", "_handle_request_exception", "_headers", "_headers_written", "_initialize", "_INVALID_HEADER_CHAR_RE", "_jupyterhub_user", "_locale", "_log", "_new_cookie", "_prepared_future", "_raw_xsrf_token", "_reason", "_record_activity", "_refreshed_users", "_remove_control_chars_regex", "_request_summary", "_resolve_roles_and_scopes", "_session_id", "_set_cookie", "_set_user_cookie", "_status_code", "_stream_request_body", "_template_loader_lock", "_template_loaders", "_token_authenticated", "_transforms", "_ui_method", "_ui_module", "_unimplemented_method", "_user_for_cookie", "_user_from_orm", "_validate_next_url", "_write_buffer", "_xsrf_safe_methods", "_xsrf_token", "_xsrf_token_id", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init__", "__init_subclass__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__slots__", "__str__" ]
""" Base classes for Custom Authenticator to use OAuth with JupyterHub Most of the code c/o Kyle Kelley (@rgbkrk) """ import base64 import json import os import uuid from urllib.parse import quote from urllib.parse import urlparse from urllib.parse import urlunparse from jupyterhub.auth import Authenticator from jupyterhub.handlers import BaseHandler from jupyterhub.handlers import LogoutHandler from jupyterhub.utils import url_path_join from tornado import web from tornado.auth import OAuth2Mixin from tornado.httpclient import AsyncHTTPClient from tornado.httpclient import HTTPClientError from tornado.log import app_log from traitlets import Any from traitlets import Bool from traitlets import default from traitlets import Dict from traitlets import List from traitlets import Unicode def guess_callback_uri(protocol, host, hub_server_url): return '{proto}://{host}{path}'.format( proto=protocol, host=host, path=url_path_join(hub_server_url, 'oauth_callback') ) STATE_COOKIE_NAME = 'oauthenticator-state' def _serialize_state(state): """Serialize OAuth state to a base64 string after passing through JSON""" json_state = json.dumps(state) return base64.urlsafe_b64encode(json_state.encode('utf8')).decode('ascii') def _deserialize_state(b64_state): """Deserialize OAuth state as serialized in _serialize_state""" if isinstance(b64_state, str): b64_state = b64_state.encode('ascii') try: json_state = base64.urlsafe_b64decode(b64_state).decode('utf8') except ValueError: app_log.error("Failed to b64-decode state: %r", b64_state) return {} try: return json.loads(json_state) except ValueError: app_log.error("Failed to json-decode state: %r", json_state) return {} class OAuthLoginHandler(OAuth2Mixin, BaseHandler): """Base class for OAuth login handler Typically subclasses will need """ # these URLs are part of the OAuth2Mixin API # get them from the Authenticator object @property def _OAUTH_AUTHORIZE_URL(self): return self.authenticator.authorize_url @property def _OAUTH_ACCESS_TOKEN_URL(self): return self.authenticator.token_url @property def _OAUTH_USERINFO_URL(self): return self.authenticator.userdata_url def set_state_cookie(self, state): self._set_cookie(STATE_COOKIE_NAME, state, expires_days=1, httponly=True) _state = None def get_state(self): next_url = original_next_url = self.get_argument('next', None) if next_url: # avoid browsers treating \ as / next_url = next_url.replace('\\', quote('\\')) # disallow hostname-having urls, # force absolute path redirect urlinfo = urlparse(next_url) next_url = urlinfo._replace( scheme='', netloc='', path='/' + urlinfo.path.lstrip('/') ).geturl() if next_url != original_next_url: self.log.warning( "Ignoring next_url %r, using %r", original_next_url, next_url ) if self._state is None: self._state = _serialize_state( {'state_id': uuid.uuid4().hex, 'next_url': next_url} ) return self._state def get(self): redirect_uri = self.authenticator.get_callback_url(self) extra_params = self.authenticator.extra_authorize_params.copy() self.log.info('OAuth redirect: %r', redirect_uri) state = self.get_state() self.set_state_cookie(state) extra_params['state'] = state self.authorize_redirect( redirect_uri=redirect_uri, client_id=self.authenticator.client_id, scope=self.authenticator.scope, extra_params=extra_params, response_type='code', ) class OAuthCallbackHandler(BaseHandler): """Basic handler for OAuth callback. Calls authenticator to verify username.""" _state_cookie = None def get_state_cookie(self): """Get OAuth state from cookies To be compared with the value in redirect URL """ if self._state_cookie is None: self._state_cookie = ( self.get_secure_cookie(STATE_COOKIE_NAME) or b'' ).decode('utf8', 'replace') self.clear_cookie(STATE_COOKIE_NAME) return self._state_cookie def get_state_url(self): """Get OAuth state from URL parameters to be compared with the value in cookies """ return self.get_argument("state") def check_state(self): """Verify OAuth state compare value in cookie with redirect url param """ cookie_state = self.get_state_cookie() url_state = self.get_state_url() if not cookie_state: raise web.HTTPError(400, "OAuth state missing from cookies") if not url_state: raise web.HTTPError(400, "OAuth state missing from URL") if cookie_state != url_state: self.log.warning("OAuth state mismatch: %s != %s", cookie_state, url_state) raise web.HTTPError(400, "OAuth state mismatch") def check_error(self): """Check the OAuth code""" error = self.get_argument("error", False) if error: message = self.get_argument("error_description", error) raise web.HTTPError(400, "OAuth error: %s" % message) def check_code(self): """Check the OAuth code""" if not self.get_argument("code", False): raise web.HTTPError(400, "OAuth callback made without a code") def check_arguments(self): """Validate the arguments of the redirect Default: - check for oauth-standard error, error_description arguments - check that there's a code - check that state matches """ self.check_error() self.check_code() self.check_state() def append_query_parameters(self, url, exclude=None): """JupyterHub 1.2 appends query parameters by default in get_next_url This is not appropriate for oauth callback handlers, where params are oauth state, code, etc. Override the method used to append parameters to next_url to not preserve any parameters """ return url def get_next_url(self, user=None): """Get the redirect target from the state field""" state = self.get_state_url() if state: next_url = _deserialize_state(state).get('next_url') if next_url: return next_url # JupyterHub 0.8 adds default .get_next_url for a fallback if hasattr(BaseHandler, 'get_next_url'): return super().
(user) return url_path_join(self.hub.server.base_url, 'home') async def _login_user_pre_08(self): """login_user simplifies the login+cookie+auth_state process in JupyterHub 0.8 _login_user_07 is for backward-compatibility with JupyterHub 0.7 """ user_info = await self.authenticator.get_authenticated_user(self, None) if user_info is None: return if isinstance(user_info, dict): username = user_info['name'] else: username = user_info user = self.user_from_username(username) self.set_login_cookie(user) return user if not hasattr(BaseHandler, 'login_user'): # JupyterHub 0.7 doesn't have .login_user login_user = _login_user_pre_08 async def get(self): self.check_arguments() user = await self.login_user() if user is None: # todo: custom error page? raise web.HTTPError(403) self.redirect(self.get_next_url(user)) class OAuthLogoutHandler(LogoutHandler): async def handle_logout(self): self.clear_cookie(STATE_COOKIE_NAME) async def render_logout_page(self): if self.authenticator.logout_redirect_url: self.redirect(self.authenticator.logout_redirect_url) return return await super().render_logout_page() class OAuthenticator(Authenticator): """Base class for OAuthenticators Subclasses must override: login_service (string identifying the service provider) authenticate (method takes one arg - the request handler handling the oauth callback) """ login_handler = OAuthLoginHandler callback_handler = OAuthCallbackHandler logout_handler = OAuthLogoutHandler authorize_url = Unicode( config=True, help="""The authenticate url for initiating oauth""" ) @default("authorize_url") def _authorize_url_default(self): return os.environ.get("OAUTH2_AUTHORIZE_URL", "") token_url = Unicode( config=True, help="""The url retrieving an access token at the completion of oauth""", ) @default("token_url") def _token_url_default(self): return os.environ.get("OAUTH2_TOKEN_URL", "") userdata_url = Unicode( config=True, help="""The url for retrieving user data with a completed access token""", ) @default("userdata_url") def _userdata_url_default(self): return os.environ.get("OAUTH2_USERDATA_URL", "") logout_redirect_url = Unicode(config=True, help="""URL for logging out of Auth0""") @default("logout_redirect_url") def _logout_redirect_url_default(self): return os.getenv("OAUTH_LOGOUT_REDIRECT_URL", "") scope = List( Unicode(), config=True, help="""The OAuth scopes to request. See the OAuth documentation of your OAuth provider for options. For GitHub in particular, you can see github_scopes.md in this repo. """, ) extra_authorize_params = Dict( config=True, help="""Extra GET params to send along with the initial OAuth request to the OAuth provider.""", ) login_service = 'override in subclass' oauth_callback_url = Unicode( os.getenv('OAUTH_CALLBACK_URL', ''), config=True, help="""Callback URL to use. Typically `https://{host}/hub/oauth_callback`""", ) client_id_env = '' client_id = Unicode(config=True) def _client_id_default(self): if self.client_id_env: client_id = os.getenv(self.client_id_env, '') if client_id: return client_id return os.getenv('OAUTH_CLIENT_ID', '') client_secret_env = '' client_secret = Unicode(config=True) def _client_secret_default(self): if self.client_secret_env: client_secret = os.getenv(self.client_secret_env, '') if client_secret: return client_secret return os.getenv('OAUTH_CLIENT_SECRET', '') validate_server_cert_env = 'OAUTH_TLS_VERIFY' validate_server_cert = Bool(config=True) def _validate_server_cert_default(self): env_value = os.getenv(self.validate_server_cert_env, '') if env_value == '0': return False else: return True http_client = Any() @default("http_client") def _default_http_client(self): return AsyncHTTPClient() async def fetch(self, req, label="fetching", parse_json=True, **kwargs): """Wrapper for http requests logs error responses, parses successful JSON responses Args: req: tornado HTTPRequest label (str): label describing what is happening, used in log message when the request fails. **kwargs: remaining keyword args passed to underlying `client.fetch(req, **kwargs)` Returns: r: parsed JSON response """ try: resp = await self.http_client.fetch(req, **kwargs) except HTTPClientError as e: if e.response: # Log failed response message for debugging purposes message = e.response.body.decode("utf8", "replace") try: # guess json, reformat for readability json_message = json.loads(message) except ValueError: # not json pass else: # reformat json log message for readability message = json.dumps(json_message, sort_keys=True, indent=1) else: # didn't get a response, e.g. connection error message = str(e) # log url without query params url = urlunparse(urlparse(req.url)._replace(query="")) app_log.error(f"Error {label} {e.code} {req.method} {url}: {message}") raise e else: if parse_json: if resp.body: return json.loads(resp.body.decode('utf8', 'replace')) else: # empty body is None return None else: return resp def login_url(self, base_url): return url_path_join(base_url, 'oauth_login') def logout_url(self, base_url): return url_path_join(base_url, 'logout') def get_callback_url(self, handler=None): """Get my OAuth redirect URL Either from config or guess based on the current request. """ if self.oauth_callback_url: return self.oauth_callback_url elif handler: return guess_callback_uri( handler.request.protocol, handler.request.host, handler.hub.server.base_url, ) else: raise ValueError( "Specify callback oauth_callback_url or give me a handler to guess with" ) def get_handlers(self, app): return [ (r'/oauth_login', self.login_handler), (r'/oauth_callback', self.callback_handler), (r'/logout', self.logout_handler), ] async def authenticate(self, handler, data=None): raise NotImplementedError() _deprecated_oauth_aliases = {} def _deprecated_oauth_trait(self, change): """observer for deprecated traits""" old_attr = change.name new_attr, version = self._deprecated_oauth_aliases.get(old_attr) new_value = getattr(self, new_attr) if new_value != change.new: # only warn if different # protects backward-compatible config from warnings # if they set the same value under both names self.log.warning( "{cls}.{old} is deprecated in {cls} {version}, use {cls}.{new} instead".format( cls=self.__class__.__name__, old=old_attr, new=new_attr, version=version, ) ) setattr(self, new_attr, change.new) def __init__(self, **kwargs): # observe deprecated config names in oauthenticator if self._deprecated_oauth_aliases: self.observe( self._deprecated_oauth_trait, names=list(self._deprecated_oauth_aliases) ) super().__init__(**kwargs)
coffeateam__coffea-casa
63
63-229-13
infile
check_arguments
[ "active_server_limit", "add_header", "admin_users", "allow_named_servers", "app", "append_query_parameters", "application", "auth_to_user", "authenticate", "authenticate_prometheus", "authenticator", "base_url", "check_arguments", "check_code", "check_error", "check_etag_header", "check_state", "check_xsrf_cookie", "clear", "clear_all_cookies", "clear_cookie", "clear_header", "clear_login_cookie", "compute_etag", "concurrent_spawn_limit", "config", "content_security_policy", "cookie_max_age_days", "cookies", "create_signed_value", "create_template_loader", "csp_report_uri", "current_user", "data_received", "db", "decode_argument", "default_url", "delete", "detach", "domain", "eventlog", "expanded_scopes", "extra_error_html", "find_user", "finish", "flush", "get", "get_accessible_services", "get_argument", "get_arguments", "get_auth_token", "get_body_argument", "get_body_arguments", "get_browser_locale", "get_content_type", "get_cookie", "get_current_user", "get_current_user_cookie", "get_current_user_named_server_limit", "get_current_user_token", "get_login_url", "get_next_url", "get_query_argument", "get_query_arguments", "get_scope_filter", "get_secure_cookie", "get_secure_cookie_key_version", "get_session_cookie", "get_signed_cookie", "get_signed_cookie_key_version", "get_state_cookie", "get_state_url", "get_status", "get_template", "get_template_namespace", "get_template_path", "get_token", "get_user_locale", "has_scope", "head", "hub", "initialize", "locale", "log", "log_exception", "login_user", "named_server_limit_per_user", "oauth_provider", "on_connection_close", "on_finish", "options", "parsed_scopes", "patch", "path_args", "path_kwargs", "post", "prepare", "proxy", "public_url", "put", "redirect", "redirect_to_server", "refresh_auth", "render", "render_embed_css", "render_embed_js", "render_linked_css", "render_linked_js", "render_string", "render_template", "request", "require_setting", "reverse_url", "send_error", "services", "set_cookie", "set_default_headers", "set_etag_header", "set_header", "set_hub_cookie", "set_login_cookie", "set_secure_cookie", "set_service_cookie", "set_session_cookie", "set_signed_cookie", "set_status", "settings", "slow_spawn_timeout", "slow_stop_timeout", "spawn_home_error", "spawn_single_user", "spawner_class", "static_url", "statsd", "stop_single_user", "subdomain_host", "SUPPORTED_METHODS", "template_namespace", "ui", "user_from_username", "user_stopped", "users", "version_hash", "write", "write_error", "xsrf_form_html", "xsrf_token", "_accept_cookie_auth", "_accept_token_auth", "_active_modules", "_auto_finish", "_break_cycles", "_clear_representation_headers", "_convert_header_value", "_current_user", "_decode_xsrf_token", "_execute", "_finished", "_get_argument", "_get_arguments", "_get_raw_xsrf_token", "_handle_request_exception", "_headers", "_headers_written", "_initialize", "_INVALID_HEADER_CHAR_RE", "_jupyterhub_user", "_locale", "_log", "_login_user_pre_08", "_new_cookie", "_prepared_future", "_raw_xsrf_token", "_reason", "_record_activity", "_refreshed_users", "_remove_control_chars_regex", "_request_summary", "_resolve_roles_and_scopes", "_session_id", "_set_cookie", "_set_user_cookie", "_state_cookie", "_status_code", "_stream_request_body", "_template_loader_lock", "_template_loaders", "_token_authenticated", "_transforms", "_ui_method", "_ui_module", "_unimplemented_method", "_user_for_cookie", "_user_from_orm", "_validate_next_url", "_write_buffer", "_xsrf_safe_methods", "_xsrf_token", "_xsrf_token_id", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init__", "__init_subclass__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__slots__", "__str__" ]
""" Base classes for Custom Authenticator to use OAuth with JupyterHub Most of the code c/o Kyle Kelley (@rgbkrk) """ import base64 import json import os import uuid from urllib.parse import quote from urllib.parse import urlparse from urllib.parse import urlunparse from jupyterhub.auth import Authenticator from jupyterhub.handlers import BaseHandler from jupyterhub.handlers import LogoutHandler from jupyterhub.utils import url_path_join from tornado import web from tornado.auth import OAuth2Mixin from tornado.httpclient import AsyncHTTPClient from tornado.httpclient import HTTPClientError from tornado.log import app_log from traitlets import Any from traitlets import Bool from traitlets import default from traitlets import Dict from traitlets import List from traitlets import Unicode def guess_callback_uri(protocol, host, hub_server_url): return '{proto}://{host}{path}'.format( proto=protocol, host=host, path=url_path_join(hub_server_url, 'oauth_callback') ) STATE_COOKIE_NAME = 'oauthenticator-state' def _serialize_state(state): """Serialize OAuth state to a base64 string after passing through JSON""" json_state = json.dumps(state) return base64.urlsafe_b64encode(json_state.encode('utf8')).decode('ascii') def _deserialize_state(b64_state): """Deserialize OAuth state as serialized in _serialize_state""" if isinstance(b64_state, str): b64_state = b64_state.encode('ascii') try: json_state = base64.urlsafe_b64decode(b64_state).decode('utf8') except ValueError: app_log.error("Failed to b64-decode state: %r", b64_state) return {} try: return json.loads(json_state) except ValueError: app_log.error("Failed to json-decode state: %r", json_state) return {} class OAuthLoginHandler(OAuth2Mixin, BaseHandler): """Base class for OAuth login handler Typically subclasses will need """ # these URLs are part of the OAuth2Mixin API # get them from the Authenticator object @property def _OAUTH_AUTHORIZE_URL(self): return self.authenticator.authorize_url @property def _OAUTH_ACCESS_TOKEN_URL(self): return self.authenticator.token_url @property def _OAUTH_USERINFO_URL(self): return self.authenticator.userdata_url def set_state_cookie(self, state): self._set_cookie(STATE_COOKIE_NAME, state, expires_days=1, httponly=True) _state = None def get_state(self): next_url = original_next_url = self.get_argument('next', None) if next_url: # avoid browsers treating \ as / next_url = next_url.replace('\\', quote('\\')) # disallow hostname-having urls, # force absolute path redirect urlinfo = urlparse(next_url) next_url = urlinfo._replace( scheme='', netloc='', path='/' + urlinfo.path.lstrip('/') ).geturl() if next_url != original_next_url: self.log.warning( "Ignoring next_url %r, using %r", original_next_url, next_url ) if self._state is None: self._state = _serialize_state( {'state_id': uuid.uuid4().hex, 'next_url': next_url} ) return self._state def get(self): redirect_uri = self.authenticator.get_callback_url(self) extra_params = self.authenticator.extra_authorize_params.copy() self.log.info('OAuth redirect: %r', redirect_uri) state = self.get_state() self.set_state_cookie(state) extra_params['state'] = state self.authorize_redirect( redirect_uri=redirect_uri, client_id=self.authenticator.client_id, scope=self.authenticator.scope, extra_params=extra_params, response_type='code', ) class OAuthCallbackHandler(BaseHandler): """Basic handler for OAuth callback. Calls authenticator to verify username.""" _state_cookie = None def get_state_cookie(self): """Get OAuth state from cookies To be compared with the value in redirect URL """ if self._state_cookie is None: self._state_cookie = ( self.get_secure_cookie(STATE_COOKIE_NAME) or b'' ).decode('utf8', 'replace') self.clear_cookie(STATE_COOKIE_NAME) return self._state_cookie def get_state_url(self): """Get OAuth state from URL parameters to be compared with the value in cookies """ return self.get_argument("state") def check_state(self): """Verify OAuth state compare value in cookie with redirect url param """ cookie_state = self.get_state_cookie() url_state = self.get_state_url() if not cookie_state: raise web.HTTPError(400, "OAuth state missing from cookies") if not url_state: raise web.HTTPError(400, "OAuth state missing from URL") if cookie_state != url_state: self.log.warning("OAuth state mismatch: %s != %s", cookie_state, url_state) raise web.HTTPError(400, "OAuth state mismatch") def check_error(self): """Check the OAuth code""" error = self.get_argument("error", False) if error: message = self.get_argument("error_description", error) raise web.HTTPError(400, "OAuth error: %s" % message) def check_code(self): """Check the OAuth code""" if not self.get_argument("code", False): raise web.HTTPError(400, "OAuth callback made without a code") def check_arguments(self): """Validate the arguments of the redirect Default: - check for oauth-standard error, error_description arguments - check that there's a code - check that state matches """ self.check_error() self.check_code() self.check_state() def append_query_parameters(self, url, exclude=None): """JupyterHub 1.2 appends query parameters by default in get_next_url This is not appropriate for oauth callback handlers, where params are oauth state, code, etc. Override the method used to append parameters to next_url to not preserve any parameters """ return url def get_next_url(self, user=None): """Get the redirect target from the state field""" state = self.get_state_url() if state: next_url = _deserialize_state(state).get('next_url') if next_url: return next_url # JupyterHub 0.8 adds default .get_next_url for a fallback if hasattr(BaseHandler, 'get_next_url'): return super().get_next_url(user) return url_path_join(self.hub.server.base_url, 'home') async def _login_user_pre_08(self): """login_user simplifies the login+cookie+auth_state process in JupyterHub 0.8 _login_user_07 is for backward-compatibility with JupyterHub 0.7 """ user_info = await self.authenticator.get_authenticated_user(self, None) if user_info is None: return if isinstance(user_info, dict): username = user_info['name'] else: username = user_info user = self.user_from_username(username) self.set_login_cookie(user) return user if not hasattr(BaseHandler, 'login_user'): # JupyterHub 0.7 doesn't have .login_user login_user = _login_user_pre_08 async def get(self): self.
() user = await self.login_user() if user is None: # todo: custom error page? raise web.HTTPError(403) self.redirect(self.get_next_url(user)) class OAuthLogoutHandler(LogoutHandler): async def handle_logout(self): self.clear_cookie(STATE_COOKIE_NAME) async def render_logout_page(self): if self.authenticator.logout_redirect_url: self.redirect(self.authenticator.logout_redirect_url) return return await super().render_logout_page() class OAuthenticator(Authenticator): """Base class for OAuthenticators Subclasses must override: login_service (string identifying the service provider) authenticate (method takes one arg - the request handler handling the oauth callback) """ login_handler = OAuthLoginHandler callback_handler = OAuthCallbackHandler logout_handler = OAuthLogoutHandler authorize_url = Unicode( config=True, help="""The authenticate url for initiating oauth""" ) @default("authorize_url") def _authorize_url_default(self): return os.environ.get("OAUTH2_AUTHORIZE_URL", "") token_url = Unicode( config=True, help="""The url retrieving an access token at the completion of oauth""", ) @default("token_url") def _token_url_default(self): return os.environ.get("OAUTH2_TOKEN_URL", "") userdata_url = Unicode( config=True, help="""The url for retrieving user data with a completed access token""", ) @default("userdata_url") def _userdata_url_default(self): return os.environ.get("OAUTH2_USERDATA_URL", "") logout_redirect_url = Unicode(config=True, help="""URL for logging out of Auth0""") @default("logout_redirect_url") def _logout_redirect_url_default(self): return os.getenv("OAUTH_LOGOUT_REDIRECT_URL", "") scope = List( Unicode(), config=True, help="""The OAuth scopes to request. See the OAuth documentation of your OAuth provider for options. For GitHub in particular, you can see github_scopes.md in this repo. """, ) extra_authorize_params = Dict( config=True, help="""Extra GET params to send along with the initial OAuth request to the OAuth provider.""", ) login_service = 'override in subclass' oauth_callback_url = Unicode( os.getenv('OAUTH_CALLBACK_URL', ''), config=True, help="""Callback URL to use. Typically `https://{host}/hub/oauth_callback`""", ) client_id_env = '' client_id = Unicode(config=True) def _client_id_default(self): if self.client_id_env: client_id = os.getenv(self.client_id_env, '') if client_id: return client_id return os.getenv('OAUTH_CLIENT_ID', '') client_secret_env = '' client_secret = Unicode(config=True) def _client_secret_default(self): if self.client_secret_env: client_secret = os.getenv(self.client_secret_env, '') if client_secret: return client_secret return os.getenv('OAUTH_CLIENT_SECRET', '') validate_server_cert_env = 'OAUTH_TLS_VERIFY' validate_server_cert = Bool(config=True) def _validate_server_cert_default(self): env_value = os.getenv(self.validate_server_cert_env, '') if env_value == '0': return False else: return True http_client = Any() @default("http_client") def _default_http_client(self): return AsyncHTTPClient() async def fetch(self, req, label="fetching", parse_json=True, **kwargs): """Wrapper for http requests logs error responses, parses successful JSON responses Args: req: tornado HTTPRequest label (str): label describing what is happening, used in log message when the request fails. **kwargs: remaining keyword args passed to underlying `client.fetch(req, **kwargs)` Returns: r: parsed JSON response """ try: resp = await self.http_client.fetch(req, **kwargs) except HTTPClientError as e: if e.response: # Log failed response message for debugging purposes message = e.response.body.decode("utf8", "replace") try: # guess json, reformat for readability json_message = json.loads(message) except ValueError: # not json pass else: # reformat json log message for readability message = json.dumps(json_message, sort_keys=True, indent=1) else: # didn't get a response, e.g. connection error message = str(e) # log url without query params url = urlunparse(urlparse(req.url)._replace(query="")) app_log.error(f"Error {label} {e.code} {req.method} {url}: {message}") raise e else: if parse_json: if resp.body: return json.loads(resp.body.decode('utf8', 'replace')) else: # empty body is None return None else: return resp def login_url(self, base_url): return url_path_join(base_url, 'oauth_login') def logout_url(self, base_url): return url_path_join(base_url, 'logout') def get_callback_url(self, handler=None): """Get my OAuth redirect URL Either from config or guess based on the current request. """ if self.oauth_callback_url: return self.oauth_callback_url elif handler: return guess_callback_uri( handler.request.protocol, handler.request.host, handler.hub.server.base_url, ) else: raise ValueError( "Specify callback oauth_callback_url or give me a handler to guess with" ) def get_handlers(self, app): return [ (r'/oauth_login', self.login_handler), (r'/oauth_callback', self.callback_handler), (r'/logout', self.logout_handler), ] async def authenticate(self, handler, data=None): raise NotImplementedError() _deprecated_oauth_aliases = {} def _deprecated_oauth_trait(self, change): """observer for deprecated traits""" old_attr = change.name new_attr, version = self._deprecated_oauth_aliases.get(old_attr) new_value = getattr(self, new_attr) if new_value != change.new: # only warn if different # protects backward-compatible config from warnings # if they set the same value under both names self.log.warning( "{cls}.{old} is deprecated in {cls} {version}, use {cls}.{new} instead".format( cls=self.__class__.__name__, old=old_attr, new=new_attr, version=version, ) ) setattr(self, new_attr, change.new) def __init__(self, **kwargs): # observe deprecated config names in oauthenticator if self._deprecated_oauth_aliases: self.observe( self._deprecated_oauth_trait, names=list(self._deprecated_oauth_aliases) ) super().__init__(**kwargs)
coffeateam__coffea-casa
63
63-234-13
infile
redirect
[ "active_server_limit", "add_header", "admin_users", "allow_named_servers", "app", "append_query_parameters", "application", "auth_to_user", "authenticate", "authenticate_prometheus", "authenticator", "base_url", "check_arguments", "check_code", "check_error", "check_etag_header", "check_state", "check_xsrf_cookie", "clear", "clear_all_cookies", "clear_cookie", "clear_header", "clear_login_cookie", "compute_etag", "concurrent_spawn_limit", "config", "content_security_policy", "cookie_max_age_days", "cookies", "create_signed_value", "create_template_loader", "csp_report_uri", "current_user", "data_received", "db", "decode_argument", "default_url", "delete", "detach", "domain", "eventlog", "expanded_scopes", "extra_error_html", "find_user", "finish", "flush", "get", "get_accessible_services", "get_argument", "get_arguments", "get_auth_token", "get_body_argument", "get_body_arguments", "get_browser_locale", "get_content_type", "get_cookie", "get_current_user", "get_current_user_cookie", "get_current_user_named_server_limit", "get_current_user_token", "get_login_url", "get_next_url", "get_query_argument", "get_query_arguments", "get_scope_filter", "get_secure_cookie", "get_secure_cookie_key_version", "get_session_cookie", "get_signed_cookie", "get_signed_cookie_key_version", "get_state_cookie", "get_state_url", "get_status", "get_template", "get_template_namespace", "get_template_path", "get_token", "get_user_locale", "has_scope", "head", "hub", "initialize", "locale", "log", "log_exception", "login_user", "named_server_limit_per_user", "oauth_provider", "on_connection_close", "on_finish", "options", "parsed_scopes", "patch", "path_args", "path_kwargs", "post", "prepare", "proxy", "public_url", "put", "redirect", "redirect_to_server", "refresh_auth", "render", "render_embed_css", "render_embed_js", "render_linked_css", "render_linked_js", "render_string", "render_template", "request", "require_setting", "reverse_url", "send_error", "services", "set_cookie", "set_default_headers", "set_etag_header", "set_header", "set_hub_cookie", "set_login_cookie", "set_secure_cookie", "set_service_cookie", "set_session_cookie", "set_signed_cookie", "set_status", "settings", "slow_spawn_timeout", "slow_stop_timeout", "spawn_home_error", "spawn_single_user", "spawner_class", "static_url", "statsd", "stop_single_user", "subdomain_host", "SUPPORTED_METHODS", "template_namespace", "ui", "user_from_username", "user_stopped", "users", "version_hash", "write", "write_error", "xsrf_form_html", "xsrf_token", "_accept_cookie_auth", "_accept_token_auth", "_active_modules", "_auto_finish", "_break_cycles", "_clear_representation_headers", "_convert_header_value", "_current_user", "_decode_xsrf_token", "_execute", "_finished", "_get_argument", "_get_arguments", "_get_raw_xsrf_token", "_handle_request_exception", "_headers", "_headers_written", "_initialize", "_INVALID_HEADER_CHAR_RE", "_jupyterhub_user", "_locale", "_log", "_login_user_pre_08", "_new_cookie", "_prepared_future", "_raw_xsrf_token", "_reason", "_record_activity", "_refreshed_users", "_remove_control_chars_regex", "_request_summary", "_resolve_roles_and_scopes", "_session_id", "_set_cookie", "_set_user_cookie", "_state_cookie", "_status_code", "_stream_request_body", "_template_loader_lock", "_template_loaders", "_token_authenticated", "_transforms", "_ui_method", "_ui_module", "_unimplemented_method", "_user_for_cookie", "_user_from_orm", "_validate_next_url", "_write_buffer", "_xsrf_safe_methods", "_xsrf_token", "_xsrf_token_id", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init__", "__init_subclass__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__slots__", "__str__" ]
""" Base classes for Custom Authenticator to use OAuth with JupyterHub Most of the code c/o Kyle Kelley (@rgbkrk) """ import base64 import json import os import uuid from urllib.parse import quote from urllib.parse import urlparse from urllib.parse import urlunparse from jupyterhub.auth import Authenticator from jupyterhub.handlers import BaseHandler from jupyterhub.handlers import LogoutHandler from jupyterhub.utils import url_path_join from tornado import web from tornado.auth import OAuth2Mixin from tornado.httpclient import AsyncHTTPClient from tornado.httpclient import HTTPClientError from tornado.log import app_log from traitlets import Any from traitlets import Bool from traitlets import default from traitlets import Dict from traitlets import List from traitlets import Unicode def guess_callback_uri(protocol, host, hub_server_url): return '{proto}://{host}{path}'.format( proto=protocol, host=host, path=url_path_join(hub_server_url, 'oauth_callback') ) STATE_COOKIE_NAME = 'oauthenticator-state' def _serialize_state(state): """Serialize OAuth state to a base64 string after passing through JSON""" json_state = json.dumps(state) return base64.urlsafe_b64encode(json_state.encode('utf8')).decode('ascii') def _deserialize_state(b64_state): """Deserialize OAuth state as serialized in _serialize_state""" if isinstance(b64_state, str): b64_state = b64_state.encode('ascii') try: json_state = base64.urlsafe_b64decode(b64_state).decode('utf8') except ValueError: app_log.error("Failed to b64-decode state: %r", b64_state) return {} try: return json.loads(json_state) except ValueError: app_log.error("Failed to json-decode state: %r", json_state) return {} class OAuthLoginHandler(OAuth2Mixin, BaseHandler): """Base class for OAuth login handler Typically subclasses will need """ # these URLs are part of the OAuth2Mixin API # get them from the Authenticator object @property def _OAUTH_AUTHORIZE_URL(self): return self.authenticator.authorize_url @property def _OAUTH_ACCESS_TOKEN_URL(self): return self.authenticator.token_url @property def _OAUTH_USERINFO_URL(self): return self.authenticator.userdata_url def set_state_cookie(self, state): self._set_cookie(STATE_COOKIE_NAME, state, expires_days=1, httponly=True) _state = None def get_state(self): next_url = original_next_url = self.get_argument('next', None) if next_url: # avoid browsers treating \ as / next_url = next_url.replace('\\', quote('\\')) # disallow hostname-having urls, # force absolute path redirect urlinfo = urlparse(next_url) next_url = urlinfo._replace( scheme='', netloc='', path='/' + urlinfo.path.lstrip('/') ).geturl() if next_url != original_next_url: self.log.warning( "Ignoring next_url %r, using %r", original_next_url, next_url ) if self._state is None: self._state = _serialize_state( {'state_id': uuid.uuid4().hex, 'next_url': next_url} ) return self._state def get(self): redirect_uri = self.authenticator.get_callback_url(self) extra_params = self.authenticator.extra_authorize_params.copy() self.log.info('OAuth redirect: %r', redirect_uri) state = self.get_state() self.set_state_cookie(state) extra_params['state'] = state self.authorize_redirect( redirect_uri=redirect_uri, client_id=self.authenticator.client_id, scope=self.authenticator.scope, extra_params=extra_params, response_type='code', ) class OAuthCallbackHandler(BaseHandler): """Basic handler for OAuth callback. Calls authenticator to verify username.""" _state_cookie = None def get_state_cookie(self): """Get OAuth state from cookies To be compared with the value in redirect URL """ if self._state_cookie is None: self._state_cookie = ( self.get_secure_cookie(STATE_COOKIE_NAME) or b'' ).decode('utf8', 'replace') self.clear_cookie(STATE_COOKIE_NAME) return self._state_cookie def get_state_url(self): """Get OAuth state from URL parameters to be compared with the value in cookies """ return self.get_argument("state") def check_state(self): """Verify OAuth state compare value in cookie with redirect url param """ cookie_state = self.get_state_cookie() url_state = self.get_state_url() if not cookie_state: raise web.HTTPError(400, "OAuth state missing from cookies") if not url_state: raise web.HTTPError(400, "OAuth state missing from URL") if cookie_state != url_state: self.log.warning("OAuth state mismatch: %s != %s", cookie_state, url_state) raise web.HTTPError(400, "OAuth state mismatch") def check_error(self): """Check the OAuth code""" error = self.get_argument("error", False) if error: message = self.get_argument("error_description", error) raise web.HTTPError(400, "OAuth error: %s" % message) def check_code(self): """Check the OAuth code""" if not self.get_argument("code", False): raise web.HTTPError(400, "OAuth callback made without a code") def check_arguments(self): """Validate the arguments of the redirect Default: - check for oauth-standard error, error_description arguments - check that there's a code - check that state matches """ self.check_error() self.check_code() self.check_state() def append_query_parameters(self, url, exclude=None): """JupyterHub 1.2 appends query parameters by default in get_next_url This is not appropriate for oauth callback handlers, where params are oauth state, code, etc. Override the method used to append parameters to next_url to not preserve any parameters """ return url def get_next_url(self, user=None): """Get the redirect target from the state field""" state = self.get_state_url() if state: next_url = _deserialize_state(state).get('next_url') if next_url: return next_url # JupyterHub 0.8 adds default .get_next_url for a fallback if hasattr(BaseHandler, 'get_next_url'): return super().get_next_url(user) return url_path_join(self.hub.server.base_url, 'home') async def _login_user_pre_08(self): """login_user simplifies the login+cookie+auth_state process in JupyterHub 0.8 _login_user_07 is for backward-compatibility with JupyterHub 0.7 """ user_info = await self.authenticator.get_authenticated_user(self, None) if user_info is None: return if isinstance(user_info, dict): username = user_info['name'] else: username = user_info user = self.user_from_username(username) self.set_login_cookie(user) return user if not hasattr(BaseHandler, 'login_user'): # JupyterHub 0.7 doesn't have .login_user login_user = _login_user_pre_08 async def get(self): self.check_arguments() user = await self.login_user() if user is None: # todo: custom error page? raise web.HTTPError(403) self.
(self.get_next_url(user)) class OAuthLogoutHandler(LogoutHandler): async def handle_logout(self): self.clear_cookie(STATE_COOKIE_NAME) async def render_logout_page(self): if self.authenticator.logout_redirect_url: self.redirect(self.authenticator.logout_redirect_url) return return await super().render_logout_page() class OAuthenticator(Authenticator): """Base class for OAuthenticators Subclasses must override: login_service (string identifying the service provider) authenticate (method takes one arg - the request handler handling the oauth callback) """ login_handler = OAuthLoginHandler callback_handler = OAuthCallbackHandler logout_handler = OAuthLogoutHandler authorize_url = Unicode( config=True, help="""The authenticate url for initiating oauth""" ) @default("authorize_url") def _authorize_url_default(self): return os.environ.get("OAUTH2_AUTHORIZE_URL", "") token_url = Unicode( config=True, help="""The url retrieving an access token at the completion of oauth""", ) @default("token_url") def _token_url_default(self): return os.environ.get("OAUTH2_TOKEN_URL", "") userdata_url = Unicode( config=True, help="""The url for retrieving user data with a completed access token""", ) @default("userdata_url") def _userdata_url_default(self): return os.environ.get("OAUTH2_USERDATA_URL", "") logout_redirect_url = Unicode(config=True, help="""URL for logging out of Auth0""") @default("logout_redirect_url") def _logout_redirect_url_default(self): return os.getenv("OAUTH_LOGOUT_REDIRECT_URL", "") scope = List( Unicode(), config=True, help="""The OAuth scopes to request. See the OAuth documentation of your OAuth provider for options. For GitHub in particular, you can see github_scopes.md in this repo. """, ) extra_authorize_params = Dict( config=True, help="""Extra GET params to send along with the initial OAuth request to the OAuth provider.""", ) login_service = 'override in subclass' oauth_callback_url = Unicode( os.getenv('OAUTH_CALLBACK_URL', ''), config=True, help="""Callback URL to use. Typically `https://{host}/hub/oauth_callback`""", ) client_id_env = '' client_id = Unicode(config=True) def _client_id_default(self): if self.client_id_env: client_id = os.getenv(self.client_id_env, '') if client_id: return client_id return os.getenv('OAUTH_CLIENT_ID', '') client_secret_env = '' client_secret = Unicode(config=True) def _client_secret_default(self): if self.client_secret_env: client_secret = os.getenv(self.client_secret_env, '') if client_secret: return client_secret return os.getenv('OAUTH_CLIENT_SECRET', '') validate_server_cert_env = 'OAUTH_TLS_VERIFY' validate_server_cert = Bool(config=True) def _validate_server_cert_default(self): env_value = os.getenv(self.validate_server_cert_env, '') if env_value == '0': return False else: return True http_client = Any() @default("http_client") def _default_http_client(self): return AsyncHTTPClient() async def fetch(self, req, label="fetching", parse_json=True, **kwargs): """Wrapper for http requests logs error responses, parses successful JSON responses Args: req: tornado HTTPRequest label (str): label describing what is happening, used in log message when the request fails. **kwargs: remaining keyword args passed to underlying `client.fetch(req, **kwargs)` Returns: r: parsed JSON response """ try: resp = await self.http_client.fetch(req, **kwargs) except HTTPClientError as e: if e.response: # Log failed response message for debugging purposes message = e.response.body.decode("utf8", "replace") try: # guess json, reformat for readability json_message = json.loads(message) except ValueError: # not json pass else: # reformat json log message for readability message = json.dumps(json_message, sort_keys=True, indent=1) else: # didn't get a response, e.g. connection error message = str(e) # log url without query params url = urlunparse(urlparse(req.url)._replace(query="")) app_log.error(f"Error {label} {e.code} {req.method} {url}: {message}") raise e else: if parse_json: if resp.body: return json.loads(resp.body.decode('utf8', 'replace')) else: # empty body is None return None else: return resp def login_url(self, base_url): return url_path_join(base_url, 'oauth_login') def logout_url(self, base_url): return url_path_join(base_url, 'logout') def get_callback_url(self, handler=None): """Get my OAuth redirect URL Either from config or guess based on the current request. """ if self.oauth_callback_url: return self.oauth_callback_url elif handler: return guess_callback_uri( handler.request.protocol, handler.request.host, handler.hub.server.base_url, ) else: raise ValueError( "Specify callback oauth_callback_url or give me a handler to guess with" ) def get_handlers(self, app): return [ (r'/oauth_login', self.login_handler), (r'/oauth_callback', self.callback_handler), (r'/logout', self.logout_handler), ] async def authenticate(self, handler, data=None): raise NotImplementedError() _deprecated_oauth_aliases = {} def _deprecated_oauth_trait(self, change): """observer for deprecated traits""" old_attr = change.name new_attr, version = self._deprecated_oauth_aliases.get(old_attr) new_value = getattr(self, new_attr) if new_value != change.new: # only warn if different # protects backward-compatible config from warnings # if they set the same value under both names self.log.warning( "{cls}.{old} is deprecated in {cls} {version}, use {cls}.{new} instead".format( cls=self.__class__.__name__, old=old_attr, new=new_attr, version=version, ) ) setattr(self, new_attr, change.new) def __init__(self, **kwargs): # observe deprecated config names in oauthenticator if self._deprecated_oauth_aliases: self.observe( self._deprecated_oauth_trait, names=list(self._deprecated_oauth_aliases) ) super().__init__(**kwargs)
coffeateam__coffea-casa
63
63-234-27
infile
get_next_url
[ "active_server_limit", "add_header", "admin_users", "allow_named_servers", "app", "append_query_parameters", "application", "auth_to_user", "authenticate", "authenticate_prometheus", "authenticator", "base_url", "check_arguments", "check_code", "check_error", "check_etag_header", "check_state", "check_xsrf_cookie", "clear", "clear_all_cookies", "clear_cookie", "clear_header", "clear_login_cookie", "compute_etag", "concurrent_spawn_limit", "config", "content_security_policy", "cookie_max_age_days", "cookies", "create_signed_value", "create_template_loader", "csp_report_uri", "current_user", "data_received", "db", "decode_argument", "default_url", "delete", "detach", "domain", "eventlog", "expanded_scopes", "extra_error_html", "find_user", "finish", "flush", "get", "get_accessible_services", "get_argument", "get_arguments", "get_auth_token", "get_body_argument", "get_body_arguments", "get_browser_locale", "get_content_type", "get_cookie", "get_current_user", "get_current_user_cookie", "get_current_user_named_server_limit", "get_current_user_token", "get_login_url", "get_next_url", "get_query_argument", "get_query_arguments", "get_scope_filter", "get_secure_cookie", "get_secure_cookie_key_version", "get_session_cookie", "get_signed_cookie", "get_signed_cookie_key_version", "get_state_cookie", "get_state_url", "get_status", "get_template", "get_template_namespace", "get_template_path", "get_token", "get_user_locale", "has_scope", "head", "hub", "initialize", "locale", "log", "log_exception", "login_user", "named_server_limit_per_user", "oauth_provider", "on_connection_close", "on_finish", "options", "parsed_scopes", "patch", "path_args", "path_kwargs", "post", "prepare", "proxy", "public_url", "put", "redirect", "redirect_to_server", "refresh_auth", "render", "render_embed_css", "render_embed_js", "render_linked_css", "render_linked_js", "render_string", "render_template", "request", "require_setting", "reverse_url", "send_error", "services", "set_cookie", "set_default_headers", "set_etag_header", "set_header", "set_hub_cookie", "set_login_cookie", "set_secure_cookie", "set_service_cookie", "set_session_cookie", "set_signed_cookie", "set_status", "settings", "slow_spawn_timeout", "slow_stop_timeout", "spawn_home_error", "spawn_single_user", "spawner_class", "static_url", "statsd", "stop_single_user", "subdomain_host", "SUPPORTED_METHODS", "template_namespace", "ui", "user_from_username", "user_stopped", "users", "version_hash", "write", "write_error", "xsrf_form_html", "xsrf_token", "_accept_cookie_auth", "_accept_token_auth", "_active_modules", "_auto_finish", "_break_cycles", "_clear_representation_headers", "_convert_header_value", "_current_user", "_decode_xsrf_token", "_execute", "_finished", "_get_argument", "_get_arguments", "_get_raw_xsrf_token", "_handle_request_exception", "_headers", "_headers_written", "_initialize", "_INVALID_HEADER_CHAR_RE", "_jupyterhub_user", "_locale", "_log", "_login_user_pre_08", "_new_cookie", "_prepared_future", "_raw_xsrf_token", "_reason", "_record_activity", "_refreshed_users", "_remove_control_chars_regex", "_request_summary", "_resolve_roles_and_scopes", "_session_id", "_set_cookie", "_set_user_cookie", "_state_cookie", "_status_code", "_stream_request_body", "_template_loader_lock", "_template_loaders", "_token_authenticated", "_transforms", "_ui_method", "_ui_module", "_unimplemented_method", "_user_for_cookie", "_user_from_orm", "_validate_next_url", "_write_buffer", "_xsrf_safe_methods", "_xsrf_token", "_xsrf_token_id", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init__", "__init_subclass__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__slots__", "__str__" ]
""" Base classes for Custom Authenticator to use OAuth with JupyterHub Most of the code c/o Kyle Kelley (@rgbkrk) """ import base64 import json import os import uuid from urllib.parse import quote from urllib.parse import urlparse from urllib.parse import urlunparse from jupyterhub.auth import Authenticator from jupyterhub.handlers import BaseHandler from jupyterhub.handlers import LogoutHandler from jupyterhub.utils import url_path_join from tornado import web from tornado.auth import OAuth2Mixin from tornado.httpclient import AsyncHTTPClient from tornado.httpclient import HTTPClientError from tornado.log import app_log from traitlets import Any from traitlets import Bool from traitlets import default from traitlets import Dict from traitlets import List from traitlets import Unicode def guess_callback_uri(protocol, host, hub_server_url): return '{proto}://{host}{path}'.format( proto=protocol, host=host, path=url_path_join(hub_server_url, 'oauth_callback') ) STATE_COOKIE_NAME = 'oauthenticator-state' def _serialize_state(state): """Serialize OAuth state to a base64 string after passing through JSON""" json_state = json.dumps(state) return base64.urlsafe_b64encode(json_state.encode('utf8')).decode('ascii') def _deserialize_state(b64_state): """Deserialize OAuth state as serialized in _serialize_state""" if isinstance(b64_state, str): b64_state = b64_state.encode('ascii') try: json_state = base64.urlsafe_b64decode(b64_state).decode('utf8') except ValueError: app_log.error("Failed to b64-decode state: %r", b64_state) return {} try: return json.loads(json_state) except ValueError: app_log.error("Failed to json-decode state: %r", json_state) return {} class OAuthLoginHandler(OAuth2Mixin, BaseHandler): """Base class for OAuth login handler Typically subclasses will need """ # these URLs are part of the OAuth2Mixin API # get them from the Authenticator object @property def _OAUTH_AUTHORIZE_URL(self): return self.authenticator.authorize_url @property def _OAUTH_ACCESS_TOKEN_URL(self): return self.authenticator.token_url @property def _OAUTH_USERINFO_URL(self): return self.authenticator.userdata_url def set_state_cookie(self, state): self._set_cookie(STATE_COOKIE_NAME, state, expires_days=1, httponly=True) _state = None def get_state(self): next_url = original_next_url = self.get_argument('next', None) if next_url: # avoid browsers treating \ as / next_url = next_url.replace('\\', quote('\\')) # disallow hostname-having urls, # force absolute path redirect urlinfo = urlparse(next_url) next_url = urlinfo._replace( scheme='', netloc='', path='/' + urlinfo.path.lstrip('/') ).geturl() if next_url != original_next_url: self.log.warning( "Ignoring next_url %r, using %r", original_next_url, next_url ) if self._state is None: self._state = _serialize_state( {'state_id': uuid.uuid4().hex, 'next_url': next_url} ) return self._state def get(self): redirect_uri = self.authenticator.get_callback_url(self) extra_params = self.authenticator.extra_authorize_params.copy() self.log.info('OAuth redirect: %r', redirect_uri) state = self.get_state() self.set_state_cookie(state) extra_params['state'] = state self.authorize_redirect( redirect_uri=redirect_uri, client_id=self.authenticator.client_id, scope=self.authenticator.scope, extra_params=extra_params, response_type='code', ) class OAuthCallbackHandler(BaseHandler): """Basic handler for OAuth callback. Calls authenticator to verify username.""" _state_cookie = None def get_state_cookie(self): """Get OAuth state from cookies To be compared with the value in redirect URL """ if self._state_cookie is None: self._state_cookie = ( self.get_secure_cookie(STATE_COOKIE_NAME) or b'' ).decode('utf8', 'replace') self.clear_cookie(STATE_COOKIE_NAME) return self._state_cookie def get_state_url(self): """Get OAuth state from URL parameters to be compared with the value in cookies """ return self.get_argument("state") def check_state(self): """Verify OAuth state compare value in cookie with redirect url param """ cookie_state = self.get_state_cookie() url_state = self.get_state_url() if not cookie_state: raise web.HTTPError(400, "OAuth state missing from cookies") if not url_state: raise web.HTTPError(400, "OAuth state missing from URL") if cookie_state != url_state: self.log.warning("OAuth state mismatch: %s != %s", cookie_state, url_state) raise web.HTTPError(400, "OAuth state mismatch") def check_error(self): """Check the OAuth code""" error = self.get_argument("error", False) if error: message = self.get_argument("error_description", error) raise web.HTTPError(400, "OAuth error: %s" % message) def check_code(self): """Check the OAuth code""" if not self.get_argument("code", False): raise web.HTTPError(400, "OAuth callback made without a code") def check_arguments(self): """Validate the arguments of the redirect Default: - check for oauth-standard error, error_description arguments - check that there's a code - check that state matches """ self.check_error() self.check_code() self.check_state() def append_query_parameters(self, url, exclude=None): """JupyterHub 1.2 appends query parameters by default in get_next_url This is not appropriate for oauth callback handlers, where params are oauth state, code, etc. Override the method used to append parameters to next_url to not preserve any parameters """ return url def get_next_url(self, user=None): """Get the redirect target from the state field""" state = self.get_state_url() if state: next_url = _deserialize_state(state).get('next_url') if next_url: return next_url # JupyterHub 0.8 adds default .get_next_url for a fallback if hasattr(BaseHandler, 'get_next_url'): return super().get_next_url(user) return url_path_join(self.hub.server.base_url, 'home') async def _login_user_pre_08(self): """login_user simplifies the login+cookie+auth_state process in JupyterHub 0.8 _login_user_07 is for backward-compatibility with JupyterHub 0.7 """ user_info = await self.authenticator.get_authenticated_user(self, None) if user_info is None: return if isinstance(user_info, dict): username = user_info['name'] else: username = user_info user = self.user_from_username(username) self.set_login_cookie(user) return user if not hasattr(BaseHandler, 'login_user'): # JupyterHub 0.7 doesn't have .login_user login_user = _login_user_pre_08 async def get(self): self.check_arguments() user = await self.login_user() if user is None: # todo: custom error page? raise web.HTTPError(403) self.redirect(self.
(user)) class OAuthLogoutHandler(LogoutHandler): async def handle_logout(self): self.clear_cookie(STATE_COOKIE_NAME) async def render_logout_page(self): if self.authenticator.logout_redirect_url: self.redirect(self.authenticator.logout_redirect_url) return return await super().render_logout_page() class OAuthenticator(Authenticator): """Base class for OAuthenticators Subclasses must override: login_service (string identifying the service provider) authenticate (method takes one arg - the request handler handling the oauth callback) """ login_handler = OAuthLoginHandler callback_handler = OAuthCallbackHandler logout_handler = OAuthLogoutHandler authorize_url = Unicode( config=True, help="""The authenticate url for initiating oauth""" ) @default("authorize_url") def _authorize_url_default(self): return os.environ.get("OAUTH2_AUTHORIZE_URL", "") token_url = Unicode( config=True, help="""The url retrieving an access token at the completion of oauth""", ) @default("token_url") def _token_url_default(self): return os.environ.get("OAUTH2_TOKEN_URL", "") userdata_url = Unicode( config=True, help="""The url for retrieving user data with a completed access token""", ) @default("userdata_url") def _userdata_url_default(self): return os.environ.get("OAUTH2_USERDATA_URL", "") logout_redirect_url = Unicode(config=True, help="""URL for logging out of Auth0""") @default("logout_redirect_url") def _logout_redirect_url_default(self): return os.getenv("OAUTH_LOGOUT_REDIRECT_URL", "") scope = List( Unicode(), config=True, help="""The OAuth scopes to request. See the OAuth documentation of your OAuth provider for options. For GitHub in particular, you can see github_scopes.md in this repo. """, ) extra_authorize_params = Dict( config=True, help="""Extra GET params to send along with the initial OAuth request to the OAuth provider.""", ) login_service = 'override in subclass' oauth_callback_url = Unicode( os.getenv('OAUTH_CALLBACK_URL', ''), config=True, help="""Callback URL to use. Typically `https://{host}/hub/oauth_callback`""", ) client_id_env = '' client_id = Unicode(config=True) def _client_id_default(self): if self.client_id_env: client_id = os.getenv(self.client_id_env, '') if client_id: return client_id return os.getenv('OAUTH_CLIENT_ID', '') client_secret_env = '' client_secret = Unicode(config=True) def _client_secret_default(self): if self.client_secret_env: client_secret = os.getenv(self.client_secret_env, '') if client_secret: return client_secret return os.getenv('OAUTH_CLIENT_SECRET', '') validate_server_cert_env = 'OAUTH_TLS_VERIFY' validate_server_cert = Bool(config=True) def _validate_server_cert_default(self): env_value = os.getenv(self.validate_server_cert_env, '') if env_value == '0': return False else: return True http_client = Any() @default("http_client") def _default_http_client(self): return AsyncHTTPClient() async def fetch(self, req, label="fetching", parse_json=True, **kwargs): """Wrapper for http requests logs error responses, parses successful JSON responses Args: req: tornado HTTPRequest label (str): label describing what is happening, used in log message when the request fails. **kwargs: remaining keyword args passed to underlying `client.fetch(req, **kwargs)` Returns: r: parsed JSON response """ try: resp = await self.http_client.fetch(req, **kwargs) except HTTPClientError as e: if e.response: # Log failed response message for debugging purposes message = e.response.body.decode("utf8", "replace") try: # guess json, reformat for readability json_message = json.loads(message) except ValueError: # not json pass else: # reformat json log message for readability message = json.dumps(json_message, sort_keys=True, indent=1) else: # didn't get a response, e.g. connection error message = str(e) # log url without query params url = urlunparse(urlparse(req.url)._replace(query="")) app_log.error(f"Error {label} {e.code} {req.method} {url}: {message}") raise e else: if parse_json: if resp.body: return json.loads(resp.body.decode('utf8', 'replace')) else: # empty body is None return None else: return resp def login_url(self, base_url): return url_path_join(base_url, 'oauth_login') def logout_url(self, base_url): return url_path_join(base_url, 'logout') def get_callback_url(self, handler=None): """Get my OAuth redirect URL Either from config or guess based on the current request. """ if self.oauth_callback_url: return self.oauth_callback_url elif handler: return guess_callback_uri( handler.request.protocol, handler.request.host, handler.hub.server.base_url, ) else: raise ValueError( "Specify callback oauth_callback_url or give me a handler to guess with" ) def get_handlers(self, app): return [ (r'/oauth_login', self.login_handler), (r'/oauth_callback', self.callback_handler), (r'/logout', self.logout_handler), ] async def authenticate(self, handler, data=None): raise NotImplementedError() _deprecated_oauth_aliases = {} def _deprecated_oauth_trait(self, change): """observer for deprecated traits""" old_attr = change.name new_attr, version = self._deprecated_oauth_aliases.get(old_attr) new_value = getattr(self, new_attr) if new_value != change.new: # only warn if different # protects backward-compatible config from warnings # if they set the same value under both names self.log.warning( "{cls}.{old} is deprecated in {cls} {version}, use {cls}.{new} instead".format( cls=self.__class__.__name__, old=old_attr, new=new_attr, version=version, ) ) setattr(self, new_attr, change.new) def __init__(self, **kwargs): # observe deprecated config names in oauthenticator if self._deprecated_oauth_aliases: self.observe( self._deprecated_oauth_trait, names=list(self._deprecated_oauth_aliases) ) super().__init__(**kwargs)
coffeateam__coffea-casa
63
63-243-17
random
redirect
[ "active_server_limit", "add_header", "admin_users", "allow_named_servers", "app", "append_query_parameters", "application", "auth_to_user", "authenticate", "authenticate_prometheus", "authenticator", "base_url", "check_etag_header", "check_xsrf_cookie", "clear", "clear_all_cookies", "clear_cookie", "clear_header", "clear_login_cookie", "compute_etag", "concurrent_spawn_limit", "config", "content_security_policy", "cookie_max_age_days", "cookies", "create_signed_value", "create_template_loader", "csp_report_uri", "current_user", "data_received", "db", "decode_argument", "default_handle_logout", "default_url", "delete", "detach", "domain", "eventlog", "expanded_scopes", "extra_error_html", "find_user", "finish", "flush", "get", "get_accessible_services", "get_argument", "get_arguments", "get_auth_token", "get_body_argument", "get_body_arguments", "get_browser_locale", "get_content_type", "get_cookie", "get_current_user", "get_current_user_cookie", "get_current_user_named_server_limit", "get_current_user_token", "get_login_url", "get_next_url", "get_query_argument", "get_query_arguments", "get_scope_filter", "get_secure_cookie", "get_secure_cookie_key_version", "get_session_cookie", "get_signed_cookie", "get_signed_cookie_key_version", "get_status", "get_template", "get_template_namespace", "get_template_path", "get_token", "get_user_locale", "handle_logout", "has_scope", "head", "hub", "initialize", "locale", "log", "log_exception", "login_user", "named_server_limit_per_user", "oauth_provider", "on_connection_close", "on_finish", "options", "parsed_scopes", "patch", "path_args", "path_kwargs", "post", "prepare", "proxy", "public_url", "put", "redirect", "redirect_to_server", "refresh_auth", "render", "render_embed_css", "render_embed_js", "render_linked_css", "render_linked_js", "render_logout_page", "render_string", "render_template", "request", "require_setting", "reverse_url", "send_error", "services", "set_cookie", "set_default_headers", "set_etag_header", "set_header", "set_hub_cookie", "set_login_cookie", "set_secure_cookie", "set_service_cookie", "set_session_cookie", "set_signed_cookie", "set_status", "settings", "shutdown_on_logout", "slow_spawn_timeout", "slow_stop_timeout", "spawn_home_error", "spawn_single_user", "spawner_class", "static_url", "statsd", "stop_single_user", "subdomain_host", "SUPPORTED_METHODS", "template_namespace", "ui", "user_from_username", "user_stopped", "users", "version_hash", "write", "write_error", "xsrf_form_html", "xsrf_token", "_accept_cookie_auth", "_accept_token_auth", "_active_modules", "_auto_finish", "_backend_logout_cleanup", "_break_cycles", "_clear_representation_headers", "_convert_header_value", "_current_user", "_decode_xsrf_token", "_execute", "_finished", "_get_argument", "_get_arguments", "_get_raw_xsrf_token", "_handle_request_exception", "_headers", "_headers_written", "_initialize", "_INVALID_HEADER_CHAR_RE", "_jupyterhub_user", "_locale", "_log", "_new_cookie", "_prepared_future", "_raw_xsrf_token", "_reason", "_record_activity", "_refreshed_users", "_remove_control_chars_regex", "_request_summary", "_resolve_roles_and_scopes", "_session_id", "_set_cookie", "_set_user_cookie", "_shutdown_servers", "_status_code", "_stream_request_body", "_template_loader_lock", "_template_loaders", "_token_authenticated", "_transforms", "_ui_method", "_ui_module", "_unimplemented_method", "_user_for_cookie", "_user_from_orm", "_validate_next_url", "_write_buffer", "_xsrf_safe_methods", "_xsrf_token", "_xsrf_token_id", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__doc__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init__", "__init_subclass__", "__module__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__slots__", "__str__" ]
""" Base classes for Custom Authenticator to use OAuth with JupyterHub Most of the code c/o Kyle Kelley (@rgbkrk) """ import base64 import json import os import uuid from urllib.parse import quote from urllib.parse import urlparse from urllib.parse import urlunparse from jupyterhub.auth import Authenticator from jupyterhub.handlers import BaseHandler from jupyterhub.handlers import LogoutHandler from jupyterhub.utils import url_path_join from tornado import web from tornado.auth import OAuth2Mixin from tornado.httpclient import AsyncHTTPClient from tornado.httpclient import HTTPClientError from tornado.log import app_log from traitlets import Any from traitlets import Bool from traitlets import default from traitlets import Dict from traitlets import List from traitlets import Unicode def guess_callback_uri(protocol, host, hub_server_url): return '{proto}://{host}{path}'.format( proto=protocol, host=host, path=url_path_join(hub_server_url, 'oauth_callback') ) STATE_COOKIE_NAME = 'oauthenticator-state' def _serialize_state(state): """Serialize OAuth state to a base64 string after passing through JSON""" json_state = json.dumps(state) return base64.urlsafe_b64encode(json_state.encode('utf8')).decode('ascii') def _deserialize_state(b64_state): """Deserialize OAuth state as serialized in _serialize_state""" if isinstance(b64_state, str): b64_state = b64_state.encode('ascii') try: json_state = base64.urlsafe_b64decode(b64_state).decode('utf8') except ValueError: app_log.error("Failed to b64-decode state: %r", b64_state) return {} try: return json.loads(json_state) except ValueError: app_log.error("Failed to json-decode state: %r", json_state) return {} class OAuthLoginHandler(OAuth2Mixin, BaseHandler): """Base class for OAuth login handler Typically subclasses will need """ # these URLs are part of the OAuth2Mixin API # get them from the Authenticator object @property def _OAUTH_AUTHORIZE_URL(self): return self.authenticator.authorize_url @property def _OAUTH_ACCESS_TOKEN_URL(self): return self.authenticator.token_url @property def _OAUTH_USERINFO_URL(self): return self.authenticator.userdata_url def set_state_cookie(self, state): self._set_cookie(STATE_COOKIE_NAME, state, expires_days=1, httponly=True) _state = None def get_state(self): next_url = original_next_url = self.get_argument('next', None) if next_url: # avoid browsers treating \ as / next_url = next_url.replace('\\', quote('\\')) # disallow hostname-having urls, # force absolute path redirect urlinfo = urlparse(next_url) next_url = urlinfo._replace( scheme='', netloc='', path='/' + urlinfo.path.lstrip('/') ).geturl() if next_url != original_next_url: self.log.warning( "Ignoring next_url %r, using %r", original_next_url, next_url ) if self._state is None: self._state = _serialize_state( {'state_id': uuid.uuid4().hex, 'next_url': next_url} ) return self._state def get(self): redirect_uri = self.authenticator.get_callback_url(self) extra_params = self.authenticator.extra_authorize_params.copy() self.log.info('OAuth redirect: %r', redirect_uri) state = self.get_state() self.set_state_cookie(state) extra_params['state'] = state self.authorize_redirect( redirect_uri=redirect_uri, client_id=self.authenticator.client_id, scope=self.authenticator.scope, extra_params=extra_params, response_type='code', ) class OAuthCallbackHandler(BaseHandler): """Basic handler for OAuth callback. Calls authenticator to verify username.""" _state_cookie = None def get_state_cookie(self): """Get OAuth state from cookies To be compared with the value in redirect URL """ if self._state_cookie is None: self._state_cookie = ( self.get_secure_cookie(STATE_COOKIE_NAME) or b'' ).decode('utf8', 'replace') self.clear_cookie(STATE_COOKIE_NAME) return self._state_cookie def get_state_url(self): """Get OAuth state from URL parameters to be compared with the value in cookies """ return self.get_argument("state") def check_state(self): """Verify OAuth state compare value in cookie with redirect url param """ cookie_state = self.get_state_cookie() url_state = self.get_state_url() if not cookie_state: raise web.HTTPError(400, "OAuth state missing from cookies") if not url_state: raise web.HTTPError(400, "OAuth state missing from URL") if cookie_state != url_state: self.log.warning("OAuth state mismatch: %s != %s", cookie_state, url_state) raise web.HTTPError(400, "OAuth state mismatch") def check_error(self): """Check the OAuth code""" error = self.get_argument("error", False) if error: message = self.get_argument("error_description", error) raise web.HTTPError(400, "OAuth error: %s" % message) def check_code(self): """Check the OAuth code""" if not self.get_argument("code", False): raise web.HTTPError(400, "OAuth callback made without a code") def check_arguments(self): """Validate the arguments of the redirect Default: - check for oauth-standard error, error_description arguments - check that there's a code - check that state matches """ self.check_error() self.check_code() self.check_state() def append_query_parameters(self, url, exclude=None): """JupyterHub 1.2 appends query parameters by default in get_next_url This is not appropriate for oauth callback handlers, where params are oauth state, code, etc. Override the method used to append parameters to next_url to not preserve any parameters """ return url def get_next_url(self, user=None): """Get the redirect target from the state field""" state = self.get_state_url() if state: next_url = _deserialize_state(state).get('next_url') if next_url: return next_url # JupyterHub 0.8 adds default .get_next_url for a fallback if hasattr(BaseHandler, 'get_next_url'): return super().get_next_url(user) return url_path_join(self.hub.server.base_url, 'home') async def _login_user_pre_08(self): """login_user simplifies the login+cookie+auth_state process in JupyterHub 0.8 _login_user_07 is for backward-compatibility with JupyterHub 0.7 """ user_info = await self.authenticator.get_authenticated_user(self, None) if user_info is None: return if isinstance(user_info, dict): username = user_info['name'] else: username = user_info user = self.user_from_username(username) self.set_login_cookie(user) return user if not hasattr(BaseHandler, 'login_user'): # JupyterHub 0.7 doesn't have .login_user login_user = _login_user_pre_08 async def get(self): self.check_arguments() user = await self.login_user() if user is None: # todo: custom error page? raise web.HTTPError(403) self.redirect(self.get_next_url(user)) class OAuthLogoutHandler(LogoutHandler): async def handle_logout(self): self.clear_cookie(STATE_COOKIE_NAME) async def render_logout_page(self): if self.authenticator.logout_redirect_url: self.
(self.authenticator.logout_redirect_url) return return await super().render_logout_page() class OAuthenticator(Authenticator): """Base class for OAuthenticators Subclasses must override: login_service (string identifying the service provider) authenticate (method takes one arg - the request handler handling the oauth callback) """ login_handler = OAuthLoginHandler callback_handler = OAuthCallbackHandler logout_handler = OAuthLogoutHandler authorize_url = Unicode( config=True, help="""The authenticate url for initiating oauth""" ) @default("authorize_url") def _authorize_url_default(self): return os.environ.get("OAUTH2_AUTHORIZE_URL", "") token_url = Unicode( config=True, help="""The url retrieving an access token at the completion of oauth""", ) @default("token_url") def _token_url_default(self): return os.environ.get("OAUTH2_TOKEN_URL", "") userdata_url = Unicode( config=True, help="""The url for retrieving user data with a completed access token""", ) @default("userdata_url") def _userdata_url_default(self): return os.environ.get("OAUTH2_USERDATA_URL", "") logout_redirect_url = Unicode(config=True, help="""URL for logging out of Auth0""") @default("logout_redirect_url") def _logout_redirect_url_default(self): return os.getenv("OAUTH_LOGOUT_REDIRECT_URL", "") scope = List( Unicode(), config=True, help="""The OAuth scopes to request. See the OAuth documentation of your OAuth provider for options. For GitHub in particular, you can see github_scopes.md in this repo. """, ) extra_authorize_params = Dict( config=True, help="""Extra GET params to send along with the initial OAuth request to the OAuth provider.""", ) login_service = 'override in subclass' oauth_callback_url = Unicode( os.getenv('OAUTH_CALLBACK_URL', ''), config=True, help="""Callback URL to use. Typically `https://{host}/hub/oauth_callback`""", ) client_id_env = '' client_id = Unicode(config=True) def _client_id_default(self): if self.client_id_env: client_id = os.getenv(self.client_id_env, '') if client_id: return client_id return os.getenv('OAUTH_CLIENT_ID', '') client_secret_env = '' client_secret = Unicode(config=True) def _client_secret_default(self): if self.client_secret_env: client_secret = os.getenv(self.client_secret_env, '') if client_secret: return client_secret return os.getenv('OAUTH_CLIENT_SECRET', '') validate_server_cert_env = 'OAUTH_TLS_VERIFY' validate_server_cert = Bool(config=True) def _validate_server_cert_default(self): env_value = os.getenv(self.validate_server_cert_env, '') if env_value == '0': return False else: return True http_client = Any() @default("http_client") def _default_http_client(self): return AsyncHTTPClient() async def fetch(self, req, label="fetching", parse_json=True, **kwargs): """Wrapper for http requests logs error responses, parses successful JSON responses Args: req: tornado HTTPRequest label (str): label describing what is happening, used in log message when the request fails. **kwargs: remaining keyword args passed to underlying `client.fetch(req, **kwargs)` Returns: r: parsed JSON response """ try: resp = await self.http_client.fetch(req, **kwargs) except HTTPClientError as e: if e.response: # Log failed response message for debugging purposes message = e.response.body.decode("utf8", "replace") try: # guess json, reformat for readability json_message = json.loads(message) except ValueError: # not json pass else: # reformat json log message for readability message = json.dumps(json_message, sort_keys=True, indent=1) else: # didn't get a response, e.g. connection error message = str(e) # log url without query params url = urlunparse(urlparse(req.url)._replace(query="")) app_log.error(f"Error {label} {e.code} {req.method} {url}: {message}") raise e else: if parse_json: if resp.body: return json.loads(resp.body.decode('utf8', 'replace')) else: # empty body is None return None else: return resp def login_url(self, base_url): return url_path_join(base_url, 'oauth_login') def logout_url(self, base_url): return url_path_join(base_url, 'logout') def get_callback_url(self, handler=None): """Get my OAuth redirect URL Either from config or guess based on the current request. """ if self.oauth_callback_url: return self.oauth_callback_url elif handler: return guess_callback_uri( handler.request.protocol, handler.request.host, handler.hub.server.base_url, ) else: raise ValueError( "Specify callback oauth_callback_url or give me a handler to guess with" ) def get_handlers(self, app): return [ (r'/oauth_login', self.login_handler), (r'/oauth_callback', self.callback_handler), (r'/logout', self.logout_handler), ] async def authenticate(self, handler, data=None): raise NotImplementedError() _deprecated_oauth_aliases = {} def _deprecated_oauth_trait(self, change): """observer for deprecated traits""" old_attr = change.name new_attr, version = self._deprecated_oauth_aliases.get(old_attr) new_value = getattr(self, new_attr) if new_value != change.new: # only warn if different # protects backward-compatible config from warnings # if they set the same value under both names self.log.warning( "{cls}.{old} is deprecated in {cls} {version}, use {cls}.{new} instead".format( cls=self.__class__.__name__, old=old_attr, new=new_attr, version=version, ) ) setattr(self, new_attr, change.new) def __init__(self, **kwargs): # observe deprecated config names in oauthenticator if self._deprecated_oauth_aliases: self.observe( self._deprecated_oauth_trait, names=list(self._deprecated_oauth_aliases) ) super().__init__(**kwargs)
coffeateam__coffea-casa