{"repo": "AnonymouX47/term-image", "n_pairs": 138, "version": "v2_function_scoped", "contexts": {"tests/widget/urwid/test_main.py::320": {"resolved_imports": ["src/term_image/__init__.py", "src/term_image/_ctlseqs.py", "src/term_image/exceptions.py", "src/term_image/image/block.py", "src/term_image/image/common.py", "src/term_image/image/iterm2.py", "src/term_image/image/kitty.py", "src/term_image/widget/_urwid.py"], "used_names": ["UrwidImage", "gc"], "enclosing_function": "test_alloc", "extracted_code": "# Source: src/term_image/widget/_urwid.py\nclass UrwidImage(urwid.Widget):\n \"\"\"Image widget (box/flow) for the urwid TUI framework.\n\n Args:\n image: The image to be rendered by the widget.\n format_spec: :ref:`Render format specifier `. Padding width and\n height are ignored.\n upscale: If ``True``, the image will be upscaled to fit maximally within the\n available size, if necessary, while still preserving the aspect ratio.\n Otherwise, the image is never upscaled.\n\n Raises:\n TypeError: An argument is of an inappropriate type.\n ValueError: An argument is of an appropriate type but has an\n unexpected/invalid value.\n term_image.exceptions.StyleError: Invalid style-specific format specifier.\n term_image.exceptions.UrwidImageError: Too many image widgets rendering images\n with the *kitty* render style.\n\n | Any ample space in the widget's render size is filled with spaces.\n | For animated images, the current frame (at render-time) is rendered.\n\n TIP:\n If *image* is of a :ref:`graphics-based ` render style and the\n widget is being used as or within a **flow** widget, with overlays or in any\n other case where the canvas will require vertical trimming, make sure to use a\n render method that splits images across lines such as the **LINES** render\n method for *kitty* and *iterm2* render styles.\n\n NOTE:\n * The `z-index` style-specific format spec field for\n :py:class:`~term_image.image.KittyImage` is ignored as this is used\n internally.\n * A **maximum** of ``2**32 - 2`` instances initialized with\n :py:class:`~term_image.image.KittyImage` instances may exist at the same time.\n\n IMPORTANT:\n This is defined if and only if the ``urwid`` package is available.\n \"\"\"\n\n _sizing = frozenset((urwid.BOX, urwid.FLOW))\n ignore_focus = True\n\n _ti_error_placeholder = None\n\n # For kitty images\n _ti_disguise_state = 0\n _ti_free_z_indexes = set()\n\n # Progresses thus: 1, -1, 2, -2, 3, ..., 2**31 - 1, -(2**31 - 1)\n # This sequence results in shorter image escape sequences compared to starting\n # from -(2**31)\n _ti_next_z_index = 1\n\n def __init__(\n self, image: BaseImage, format_spec: str = \"\", *, upscale: bool = False\n ) -> None:\n if not isinstance(image, BaseImage):\n raise arg_type_error(\"image\", image)\n\n if not isinstance(format_spec, str):\n raise arg_type_error(\"format_spec\", format_spec)\n *fmt, alpha, style_args = image._check_format_spec(format_spec)\n\n if not isinstance(upscale, bool):\n raise arg_type_error(\"upscale\", upscale)\n\n super().__init__()\n self._ti_image = image\n self._ti_h_align, _, self._ti_v_align, _ = fmt\n self._ti_alpha = alpha\n self._ti_style_args = style_args\n self._ti_sizing = Size.FIT if upscale else Size.AUTO\n\n if isinstance(image, TextImage):\n style_args[\"split_cells\"] = True\n elif isinstance(image, KittyImage):\n style_args[\"z_index\"] = self._ti_z_index = self._ti_get_z_index()\n\n # Since Konsole doesn't blend images placed at the same location and\n # z-index, unlike Kitty (and potentially others), `blend=True` is\n # better on Konsole as it reduces/eliminates flicker.\n if get_terminal_name_version()[0] != \"konsole\":\n # To clear directly overlapped images when urwid redraws a line without\n # a change in image position\n style_args[\"blend\"] = False\n\n def __del__(self) -> None:\n if hasattr(self, \"_ti_z_index\"):\n __class__._ti_free_z_indexes.add(self._ti_z_index)\n\n image = property(\n lambda self: self._ti_image,\n doc=\"\"\"\n The image rendered by the widget\n\n :type: BaseImage\n\n GET:\n Returns the image instance rendered by the widget.\n \"\"\",\n )\n\n def render(self, size: Tuple[int, int], focus: bool = False) -> urwid.Canvas:\n image = self._ti_image\n\n if len(size) == 2: # box\n image.set_size(self._ti_sizing, frame_size=size)\n elif len(size) == 1: # flow\n if self._ti_sizing is Size.FIT:\n image.set_size(size[0])\n else:\n fit_size = self._ti_image._valid_size(size[0])\n ori_size = self._ti_image._valid_size(Size.ORIGINAL)\n image._size = (\n ori_size\n if ori_size[0] <= fit_size[0] and ori_size[1] <= fit_size[1]\n else fit_size\n )\n size = (size[0], image._size[1])\n else: # fixed\n raise UrwidImageError(\"Not a fixed widget\")\n\n try:\n render = image._format_render(\n image._renderer(\n image._render_image, self._ti_alpha, **self._ti_style_args\n ),\n self._ti_h_align,\n size[0],\n self._ti_v_align,\n size[1],\n )\n except Exception:\n if type(self)._ti_error_placeholder is None:\n raise\n canv = type(self)._ti_error_placeholder.render(size, focus)\n else:\n canv = UrwidImageCanvas(render, size, image._size)\n\n return canv\n\n def rows(self, size: Tuple[int], focus: bool = False) -> int:\n fit_size = self._ti_image._valid_size(size[0])\n if self._ti_sizing is Size.FIT:\n n_rows = fit_size[1]\n else:\n ori_size = self._ti_image._valid_size(Size.ORIGINAL)\n n_rows = (\n ori_size[1]\n if ori_size[0] <= fit_size[0] and ori_size[1] <= fit_size[1]\n else fit_size[1]\n )\n\n return n_rows\n\n @classmethod\n def set_error_placeholder(cls, widget: Optional[urwid.Widget]) -> None:\n \"\"\"Sets the widget to be rendered in place of an image when rendering fails.\n\n Args:\n widget: The placeholder widget or ``None`` to remove the placeholder.\n\n Raises:\n TypeError: *widget* is not an urwid widget.\n\n If set, any exception raised during rendering is **suppressed** and the\n placeholder is rendered in place of the image.\n \"\"\"\n if not isinstance(widget, urwid.Widget):\n raise arg_type_error(\"widget\", widget)\n\n cls._ti_error_placeholder = widget\n\n @staticmethod\n def _ti_get_z_index() -> int:\n if __class__._ti_free_z_indexes:\n return __class__._ti_free_z_indexes.pop()\n\n z_index = __class__._ti_next_z_index\n if z_index == 2**31:\n raise UrwidImageError(\"Too many image widgets with the kitty render style\")\n __class__._ti_next_z_index = -z_index if z_index > 0 else -z_index + 1\n\n return z_index\n\n def _ti_change_disguise(self) -> None:\n \"\"\"See :py:meth`UrwidImageCanvas._ti_change_disguise`.\"\"\"\n self._ti_disguise_state = (self._ti_disguise_state + 1) % 3", "n_imports_parsed": 10, "n_files_resolved": 8, "n_chars_extracted": 7167}, "tests/renderable/test_renderable.py::499": {"resolved_imports": ["src/term_image/_ctlseqs.py", "src/term_image/geometry.py", "src/term_image/padding.py", "src/term_image/renderable/_enum.py", "src/term_image/renderable/_exceptions.py", "src/term_image/renderable/_renderable.py", "src/term_image/renderable/_types.py"], "used_names": ["Renderable"], "enclosing_function": "test_base", "extracted_code": "# Source: src/term_image/renderable/_renderable.py\nclass Renderable(metaclass=RenderableMeta, _base=True):\n \"\"\"A renderable.\n\n Args:\n frame_count: Number of frames. If it's a\n\n * positive integer, the number of frames is as given.\n * :py:class:`~term_image.renderable.FrameCount` enum member, see the\n member's description.\n\n If equal to 1 (one), the renderable is non-animated.\n Otherwise, it is animated.\n\n frame_duration: The duration of a frame. If it's a\n\n * positive integer, it implies a static duration (in **milliseconds**)\n i.e the same duration applies to every frame.\n * :py:class:`~term_image.renderable.FrameDuration` enum member, see the\n member's description.\n\n This argument is ignored if *frame_count* equals 1 (one)\n i.e the renderable is non-animated.\n\n Raises:\n ValueError: An argument has an invalid value.\n\n ATTENTION:\n This is an abstract base class. Hence, only **concrete** subclasses can be\n instantiated.\n\n .. seealso::\n\n :ref:`renderable-ext-api`\n :py:class:`Renderable`\\\\ 's Extension API\n \"\"\"\n\n # Class Attributes =========================================================\n\n # Initialized by `RenderableMeta` and may be updated by `ArgsNamespaceMeta`\n Args: ClassVar[type[ArgsNamespace] | None]\n \"\"\":term:`Render class`\\\\ -specific render arguments.\n\n This is either:\n\n - a render argument namespace class (subclass of :py:class:`ArgsNamespace`)\n associated [#an-ass]_ with the render class, or\n - :py:data:`None`, if the render class has no render arguments.\n\n If this is a class, an instance of it (or a subclass thereof) is contained within\n any :py:class:`RenderArgs` instance associated [#ra-ass]_ with the render class or\n any of its subclasses. Also, an instance of this class (or a subclass of it) is\n returned by :py:meth:`render_args[render_cls]\n `; where *render_args* is\n an instance of :py:class:`~term_image.renderable.RenderArgs` as previously\n described and *render_cls* is the render class with which this namespace class\n is associated [#an-ass]_.\n\n .. collapse:: Example\n\n >>> class Foo(Renderable):\n ... pass\n ...\n ... class FooArgs(ArgsNamespace, render_cls=Foo):\n ... foo: str | None = None\n ...\n >>> Foo.Args is FooArgs\n True\n >>>\n >>> # default\n >>> foo_args = Foo.Args()\n >>> foo_args\n FooArgs(foo=None)\n >>> foo_args.foo is None\n True\n >>>\n >>> render_args = RenderArgs(Foo)\n >>> render_args[Foo]\n FooArgs(foo=None)\n >>>\n >>> # non-default\n >>> foo_args = Foo.Args(\"FOO\")\n >>> foo_args\n FooArgs(foo='FOO')\n >>> foo_args.foo\n 'FOO'\n >>>\n >>> render_args = RenderArgs(Foo, foo_args.update(foo=\"bar\"))\n >>> render_args[Foo]\n FooArgs(foo='bar')\n\n On the other hand, if this is :py:data:`None`, it implies the render class has no\n render arguments.\n\n .. collapse:: Example\n\n >>> class Bar(Renderable):\n ... pass\n ...\n >>> Bar.Args is None\n True\n >>> render_args = RenderArgs(Bar)\n >>> render_args[Bar]\n Traceback (most recent call last):\n ...\n NoArgsNamespaceError: 'Bar' has no render arguments\n \"\"\"\n\n # Initialized by `RenderableMeta` and may be updated by `DataNamespaceMeta`\n _Data_: ClassVar[type[DataNamespace] | None]\n \"\"\":term:`Render class`\\\\ -specific render data.\n\n This is either:\n\n - a render data namespace class (subclass of :py:class:`DataNamespace`)\n associated [#dn-ass]_ with the render class, or\n - :py:data:`None`, if the render class has no render data.\n\n If this is a class, an instance of it (or a subclass thereof) is contained within\n any :py:class:`RenderData` instance associated [#rd-ass]_ with the render class or\n any of its subclasses. Also, an instance of this class (or a subclass of it) is\n returned by :py:meth:`render_data[render_cls]\n `; where *render_data* is\n an instance of :py:class:`~term_image.renderable.RenderData` as previously\n described and *render_cls* is the render class with which this namespace class\n is associated [#dn-ass]_.\n\n .. collapse:: Example\n\n >>> class Foo(Renderable):\n ... pass\n ...\n ... class _Data_(DataNamespace, render_cls=Foo):\n ... foo: str | None\n ...\n >>> Foo._Data_ is FooData\n True\n >>>\n >>> foo_data = Foo._Data_()\n >>> foo_data\n >\n >>> foo_data.foo\n Traceback (most recent call last):\n ...\n UninitializedDataFieldError: The render data field 'foo' of 'Foo' has not \\\nbeen initialized\n >>>\n >>> foo_data.foo = \"FOO\"\n >>> foo_data\n \n >>> foo_data.foo\n 'FOO'\n >>>\n >>> render_data = RenderData(Foo)\n >>> render_data[Foo]\n >\n >>>\n >>> render_data[Foo].foo = \"bar\"\n >>> render_data[Foo]\n \n\n On the other hand, if this is :py:data:`None`, it implies the render class has no\n render data.\n\n .. collapse:: Example\n\n >>> class Bar(Renderable):\n ... pass\n ...\n >>> Bar._Data_ is None\n True\n >>>\n >>> render_data = RenderData(Bar)\n >>> render_data[Bar]\n Traceback (most recent call last):\n ...\n NoDataNamespaceError: 'Bar' has no render data\n\n .. seealso::\n\n :py:class:`~term_image.renderable.RenderableData`\n Render data for :py:class:`~term_image.renderable.Renderable`.\n \"\"\"\n\n _EXPORTED_ATTRS_: ClassVar[tuple[str, ...]]\n \"\"\"Exported attributes.\n\n This specifies class attributes defined by the class (not a parent) on itself\n **but not** its subclasses which should be exported to definitions of the class\n in subprocesses.\n\n These attributes are typically assigned using ``__class__.*`` within methods.\n\n NOTE:\n * Defining this is optional.\n * The attributes are exported for a class if and only if they are defined\n on that class when starting a subprocess.\n * The attributes are exported only for subprocesses started via\n :py:class:`multiprocessing.Process`.\n\n TIP:\n This can be used to export \"private\" attributes of the class across\n subprocesses.\n \"\"\"\n\n _EXPORTED_DESCENDANT_ATTRS_: ClassVar[tuple[str, ...]]\n \"\"\"Exported :term:`descendant` attributes.\n\n This specifies class attributes defined by the class (not a parent) on itself\n **and** its subclasses (i.e :term:`descendant` attributes) which should be exported\n to definitions of the class and its subclasses in subprocesses.\n\n These attributes are typically assigned using ``cls.*`` within class methods.\n\n This extends the exported descendant attributes of parent classes i.e all\n exported descendant attributes of a class are also exported for its subclasses.\n\n NOTE:\n * Defining this is optional.\n * The attributes are exported for a class if and only if they are defined\n on that class when starting a subprocess.\n * The attributes are exported only for subprocesses started via\n :py:class:`multiprocessing.Process`.\n\n TIP:\n This can be used to export \"private\" :term:`descendant` attributes of the\n class across subprocesses.\n \"\"\"\n\n _ALL_DEFAULT_ARGS: ClassVar[MappingProxyType[type[Renderable], ArgsNamespace]]\n _RENDER_DATA_MRO: ClassVar[MappingProxyType[type[Renderable], type[DataNamespace]]]\n _ALL_EXPORTED_ATTRS: ClassVar[tuple[str, ...]]\n\n # Instance Attributes ======================================================\n\n animated: bool\n \"\"\"``True`` if the renderable is :term:`animated`. Otherwise, ``False``.\"\"\"\n\n _frame: int\n _frame_count: int | FrameCount\n _frame_duration: int | FrameDuration\n\n # Special Methods ==========================================================\n\n def __init__(\n self,\n frame_count: int | FrameCount,\n frame_duration: int | FrameDuration,\n ) -> None:\n if isinstance(frame_count, int) and frame_count < 1:\n raise arg_value_error_range(\"frame_count\", frame_count)\n\n if frame_count != 1:\n if isinstance(frame_duration, int) and frame_duration <= 0:\n raise arg_value_error_range(\"frame_duration\", frame_duration)\n self._frame_duration = frame_duration\n\n self.animated = frame_count != 1\n self._frame_count = frame_count\n self._frame = 0\n\n def __iter__(self) -> term_image.render.RenderIterator:\n \"\"\"Returns a render iterator.\n\n Returns:\n A render iterator (with frame caching disabled and all other optional\n arguments to :py:class:`~term_image.render.RenderIterator` being the\n default values).\n\n Raises:\n NonAnimatedRenderableError: The renderable is non-animated.\n\n :term:`Animated` renderables are iterable i.e they can be used with various\n means of iteration such as the ``for`` statement and iterable unpacking.\n \"\"\"\n from term_image.render import RenderIterator\n\n try:\n return RenderIterator(self, cache=False)\n except ValueError:\n raise NonAnimatedRenderableError(\n \"Non-animated renderables are not iterable\"\n ) from None\n\n def __repr__(self) -> str:\n return f\"<{type(self).__name__}: frame_count={self._frame_count}>\"\n\n def __str__(self) -> str:\n \"\"\":term:`Renders` the current frame with default arguments and no padding.\n\n Returns:\n The frame :term:`render output`.\n\n Raises:\n RenderError: An error occurred during :term:`rendering`.\n \"\"\"\n return self._init_render_(self._render_)[0].render_output\n\n # Properties ===============================================================\n\n @property\n def frame_count(self) -> int | Literal[FrameCount.INDEFINITE]:\n \"\"\"Frame count\n\n GET:\n Returns either\n\n * the number of frames the renderable has, or\n * :py:attr:`~term_image.renderable.FrameCount.INDEFINITE`.\n \"\"\"\n if self._frame_count is FrameCount.POSTPONED:\n self._frame_count = self._get_frame_count_()\n\n return self._frame_count\n\n @property\n def frame_duration(self) -> int | FrameDuration:\n \"\"\"Frame duration\n\n GET:\n Returns\n\n * a positive integer, a static duration (in **milliseconds**) i.e the\n same duration applies to every frame; or\n * :py:attr:`~term_image.renderable.FrameDuration.DYNAMIC`.\n\n SET:\n If the value is\n\n * a positive integer, it implies a static duration (in **milliseconds**)\n i.e the same duration applies to every frame.\n * :py:attr:`~term_image.renderable.FrameDuration.DYNAMIC`, see the\n enum member's description.\n\n Raises:\n NonAnimatedRenderableError: The renderable is non-animated.\n \"\"\"\n try:\n return self._frame_duration\n except AttributeError:\n if not self.animated:\n raise NonAnimatedRenderableError(\n \"Non-animated renderables have no frame duration\"\n ) from None\n raise\n\n @frame_duration.setter\n def frame_duration(self, duration: int | FrameDuration) -> None:\n if not self.animated:\n raise NonAnimatedRenderableError(\n \"Cannot set frame duration for a non-animated renderable\"\n )\n\n if isinstance(duration, int) and duration <= 0:\n raise arg_value_error_range(\"frame_duration\", duration)\n\n self._frame_duration = duration\n\n @property\n def render_size(self) -> geometry.Size:\n \"\"\":term:`Render size`\n\n GET:\n Returns the size of the renderable's :term:`render output`.\n \"\"\"\n return self._get_render_size_()\n\n # Public Methods ===========================================================\n\n def draw(\n self,\n render_args: RenderArgs | None = None,\n padding: Padding = AlignedPadding(0, -2),\n *,\n animate: bool = True,\n loops: int = -1,\n cache: bool | int = 100,\n check_size: bool = True,\n allow_scroll: bool = False,\n hide_cursor: bool = True,\n echo_input: bool = False,\n ) -> None:\n \"\"\"Draws the current frame or an animation to standard output.\n\n Args:\n render_args: Render arguments.\n padding: :term:`Render output` padding.\n animate: Whether to enable animation for :term:`animated` renderables.\n If disabled, only the current frame is drawn.\n loops: See :py:class:`~term_image.render.RenderIterator`\n (applies to **animations only**).\n cache: See :py:class:`~term_image.render.RenderIterator`.\n (applies to **animations only**).\n check_size: Whether to validate the padded :term:`render size` of\n **non-animations**.\n allow_scroll: Whether to validate the padded :term:`render height` of\n **non-animations**. Ignored if *check_size* is ``False``.\n hide_cursor: Whether to hide the cursor **while drawing**.\n echo_input: Whether to display input **while drawing** (applies on **Unix\n only**).\n\n .. note::\n * If disabled (default), input is not read/consumed, it's just not\n displayed.\n * If enabled, echoed input may affect cursor positioning and\n therefore, the output (especially for animations).\n\n Raises:\n RenderSizeOutofRangeError: The padded :term:`render size` can not fit into\n the :term:`terminal size`.\n IncompatibleRenderArgsError: Incompatible render arguments.\n RenderError: An error occurred during :term:`rendering`.\n\n If *check_size* is ``True`` (or it's an animation),\n\n * the padded :term:`render width` must not be greater than the\n :term:`terminal width`.\n * and *allow_scroll* is ``False`` (or it's an animation), the padded\n :term:`render height` must not be greater than the :term:`terminal height`.\n\n NOTE:\n * *hide_cursor* and *echo_input* apply if and only if the output stream\n is connected to a terminal.\n * For animations (i.e animated renderables with *animate* = ``True``),\n the padded :term:`render size` is always validated.\n * Animations with **definite** frame count, **by default**, are infinitely\n looped but can be terminated with :py:data:`~signal.SIGINT`\n (``CTRL + C``), **without** raising :py:class:`KeyboardInterrupt`.\n \"\"\"\n animation = self.animated and animate\n output = sys.stdout\n not_echo_input = OS_IS_UNIX and not echo_input and output.isatty()\n hide_cursor = hide_cursor and output.isatty()\n\n # Validate size and get render data and args\n render_data: RenderData\n real_render_args: RenderArgs\n (render_data, real_render_args), padding = self._init_render_(\n lambda *args: args,\n render_args,\n padding,\n iteration=animation,\n finalize=False,\n check_size=animation or check_size,\n allow_scroll=not animation and allow_scroll,\n )\n\n if not_echo_input:\n output_fd = output.fileno()\n old_attr = termios.tcgetattr(output_fd)\n new_attr = termios.tcgetattr(output_fd)\n new_attr[3] &= ~termios.ECHO\n try:\n if hide_cursor:\n output.write(HIDE_CURSOR)\n if not_echo_input:\n termios.tcsetattr(output_fd, termios.TCSAFLUSH, new_attr)\n\n if animation:\n self._animate_(\n render_data, real_render_args, padding, loops, cache, output\n )\n else:\n frame = self._render_(render_data, real_render_args)\n padded_size = padding.get_padded_size(frame.render_size)\n render = (\n frame.render_output\n if frame.render_size == padded_size\n else padding.pad(frame.render_output, frame.render_size)\n )\n try:\n output.write(render)\n output.flush()\n except KeyboardInterrupt:\n self._handle_interrupted_draw_(\n render_data, real_render_args, output\n )\n raise\n finally:\n output.write(\"\\n\")\n if hide_cursor:\n output.write(SHOW_CURSOR)\n output.flush()\n if not_echo_input:\n termios.tcsetattr(output_fd, termios.TCSANOW, old_attr)\n render_data.finalize()\n\n def render(\n self,\n render_args: RenderArgs | None = None,\n padding: Padding = NO_PADDING,\n ) -> Frame:\n \"\"\":term:`Renders` the current frame.\n\n Args:\n render_args: Render arguments.\n padding: :term:`Render output` padding.\n\n Returns:\n The rendered frame.\n\n Raises:\n IncompatibleRenderArgsError: Incompatible render arguments.\n RenderError: An error occurred during :term:`rendering`.\n \"\"\"\n frame, padding = self._init_render_(self._render_, render_args, padding)\n padded_size = padding.get_padded_size(frame.render_size)\n\n return (\n frame\n if frame.render_size == padded_size\n else Frame(\n frame.number,\n frame.duration,\n padded_size,\n padding.pad(frame.render_output, frame.render_size),\n )\n )\n\n def seek(self, offset: int, whence: Seek = Seek.START) -> int:\n \"\"\"Sets the current frame number.\n\n Args:\n offset: Frame offset (relative to *whence*).\n whence: Reference position for *offset*.\n\n Returns:\n The new current frame number.\n\n Raises:\n IndefiniteSeekError: The renderable has\n :py:attr:`~term_image.renderable.FrameCount.INDEFINITE` frame count.\n ValueError: *offset* is out of range.\n\n The value range for *offset* depends on *whence*:\n\n .. list-table::\n :align: left\n :header-rows: 1\n :widths: auto\n\n * - *whence*\n - Valid value range for *offset*\n\n * - :py:attr:`~term_image.renderable.Seek.START`\n - ``0`` <= *offset* < :py:attr:`frame_count`\n * - :py:attr:`~term_image.renderable.Seek.CURRENT`\n - -:py:meth:`tell` <= *offset* < :py:attr:`frame_count` - :py:meth:`tell`\n * - :py:attr:`~term_image.renderable.Seek.END`\n - -:py:attr:`frame_count` < *offset* <= ``0``\n \"\"\"\n frame_count = self.frame_count\n\n if frame_count is FrameCount.INDEFINITE:\n raise IndefiniteSeekError(\n \"Cannot seek a renderable with INDEFINITE frame count\"\n )\n\n frame = (\n offset\n if whence is Seek.START\n else (\n self._frame + offset\n if whence is Seek.CURRENT\n else frame_count + offset - 1\n )\n )\n if not 0 <= frame < frame_count:\n raise arg_value_error_range(\n \"offset\",\n offset,\n (\n f\"whence={whence.name}, frame_count={frame_count}\"\n + (f\", current={self._frame}\" if whence is Seek.CURRENT else \"\")\n ),\n )\n self._frame = frame\n\n return frame\n\n def tell(self) -> int:\n \"\"\"Returns the current frame number.\n\n Returns:\n Zero, if the renderable is non-animated or has\n :py:attr:`~term_image.renderable.FrameCount.INDEFINITE` frame count.\n Otherwise, the current frame number.\n \"\"\"\n return self._frame\n\n # Extension methods ========================================================\n\n def _animate_(\n self,\n render_data: RenderData,\n render_args: RenderArgs,\n padding: Padding,\n loops: int,\n cache: bool | int,\n output: TextIO,\n ) -> None:\n \"\"\"Animates frames of a renderable.\n\n Args:\n render_data: Render data.\n render_args: Render arguments associated with the renderable's class.\n output: The text I/O stream to which rendered frames will be written.\n\n All other parameters are the same as for :py:meth:`draw`, except that\n *padding* must have **absolute** dimensions if it's an instance of\n :py:class:`~term_image.padding.AlignedPadding`.\n\n This is called by :py:meth:`draw` for animations.\n\n NOTE:\n * The base implementation does not finalize *render_data*.\n * :term:`Render size` validation is expected to have been performed by\n the caller.\n * When called by :py:meth:`draw` (at least, the base implementation),\n *loops* and *cache* wouldn't have been validated.\n \"\"\"\n from term_image.render import RenderIterator\n\n render_size: Size = render_data[Renderable].size\n height = render_size.height\n pad_left, _, _, pad_bottom = padding._get_exact_dimensions_(render_size)\n render_iter = RenderIterator._from_render_data_(\n self,\n render_data,\n render_args,\n padding,\n loops,\n False if loops == 1 else cache,\n finalize=False,\n )\n cursor_to_next_render_line = f\"\\n{cursor_forward(pad_left)}\"\n cursor_to_render_top_left = (\n f\"\\r{cursor_up(height - 1)}{cursor_forward(pad_left)}\"\n )\n write = output.write\n flush = output.flush\n first_frame_written = False\n\n try:\n # first frame\n try:\n frame = next(render_iter)\n except StopIteration: # `INDEFINITE` frame count\n return\n\n try:\n write(frame.render_output)\n flush()\n except KeyboardInterrupt:\n self._handle_interrupted_draw_(render_data, render_args, output)\n return\n else:\n # Move the cursor to the top-left cell of the region occupied by the\n # render output\n write(\n f\"\\r{cursor_up(height + pad_bottom - 1)}{cursor_forward(pad_left)}\"\n )\n flush()\n\n first_frame_written = True\n\n # Padding has been drawn with the first frame, only the actual render is\n # needed henceforth.\n render_iter.set_padding(NO_PADDING)\n\n # render next frame during previous frame's duration\n duration_ms = frame.duration\n start_ns = perf_counter_ns()\n\n for frame in render_iter: # Render next frame\n # left-over of previous frame's duration\n sleep(\n max(0, duration_ms * 10**6 - (perf_counter_ns() - start_ns)) / 10**9\n )\n\n # clear previous frame, if necessary\n self._clear_frame_(render_data, render_args, pad_left + 1, output)\n\n # draw next frame\n try:\n write(frame.render_output.replace(\"\\n\", cursor_to_next_render_line))\n flush()\n except KeyboardInterrupt:\n self._handle_interrupted_draw_(render_data, render_args, output)\n return\n\n write(cursor_to_render_top_left)\n flush()\n\n # render next frame during previous frame's duration\n start_ns = perf_counter_ns()\n duration_ms = frame.duration\n\n # left-over of last frame's duration\n sleep(max(0, duration_ms * 10**6 - (perf_counter_ns() - start_ns)) / 10**9)\n except KeyboardInterrupt:\n pass\n finally:\n render_iter.close()\n if first_frame_written:\n # Move the cursor to the last line to prevent \"overlaid\" output\n write(cursor_down(height + pad_bottom - 1))\n flush()\n\n def _clear_frame_(\n self,\n render_data: RenderData,\n render_args: RenderArgs,\n cursor_x: int,\n output: TextIO,\n ) -> None:\n \"\"\"Clears the previous frame of an animation, if necessary.\n\n Args:\n render_data: Render data.\n render_args: Render arguments.\n cursor_x: Column/horizontal position of the cursor at the point of calling\n this method.\n\n .. note:: The position is **1-based** i.e the leftmost column on the\n screen is at position 1 (one).\n\n output: The text I/O stream to which frames of the animation are being\n written.\n\n Called by the base implementation of :py:meth:`_animate_` just before drawing\n the next frame of an animation.\n\n Upon calling this method, the cursor should be positioned at the top-left-most\n cell of the region occupied by the frame render output on the terminal screen.\n\n Upon return, ensure the cursor is at the same position it was at the point of\n calling this method (at least logically, since *output* shouldn't be flushed\n yet).\n\n The base implementation does nothing.\n\n NOTE:\n * This is required only if drawing the next frame doesn't inherently\n overwrite the previous frame.\n * This is only meant (and should only be used) as a last resort since\n clearing the previous frame before drawing the next may result in\n visible flicker.\n * Ensure whatever this method does doesn't result in the screen being\n scrolled.\n\n TIP:\n To reduce flicker, it's advisable to **not** flush *output*. It will be\n flushed after writing the next frame.\n \"\"\"\n\n @classmethod\n def _finalize_render_data_(cls, render_data: RenderData) -> None:\n \"\"\"Finalizes render data.\n\n Args:\n render_data: Render data.\n\n Typically, an overriding method should\n\n * finalize the data generated by :py:meth:`_get_render_data_` of the\n **same class**, if necessary,\n * call the overridden method, passing on *render_data*.\n\n NOTE:\n * It's recommended to call :py:meth:`RenderData.finalize()\n `\n instead as that assures a single invocation of this method.\n * Any definition of this method should be safe for multiple invocations on\n the same :py:class:`~term_image.renderable.RenderData` instance, just in\n case.\n\n .. seealso::\n :py:meth:`_get_render_data_`,\n :py:meth:`RenderData.finalize()\n `,\n the *finalize* parameter of :py:meth:`_init_render_`.\n \"\"\"\n\n def _get_frame_count_(self) -> int | Literal[FrameCount.INDEFINITE]:\n \"\"\"Implements :py:attr:`~term_image.renderable.FrameCount.POSTPONED` frame\n count evaluation.\n\n Returns:\n The frame count of the renderable. See :py:attr:`frame_count`.\n\n .. note::\n Returning :py:attr:`~term_image.renderable.FrameCount.POSTPONED` or\n ``1`` (one) is invalid and may result in unexpected/undefined behaviour\n across various interfaces defined by this library (and those derived\n from them), since re-postponing evaluation is unsupported and the\n renderable would have been taken to be animated.\n\n The base implementation raises :py:class:`NotImplementedError`.\n \"\"\"\n raise NotImplementedError(\"POSTPONED frame count evaluation isn't implemented\")\n\n def _get_render_data_(self, *, iteration: bool) -> RenderData:\n \"\"\"Generates data required for rendering that's based on internal or\n external state.\n\n Args:\n iteration: Whether the render operation requiring the data involves a\n sequence of :term:`renders` (most likely of different frames), or it's\n a one-off render.\n\n Returns:\n The generated render data.\n\n The render data should include **copies** of any **variable/mutable**\n internal/external state required for rendering and other data generated from\n constant state but which should **persist** throughout a render operation\n (which may involve consecutive/repeated renders of one or more frames).\n\n May also be used to \"allocate\" and initialize storage for mutable/variable\n data specific to a render operation.\n\n Typically, an overriding method should\n\n * call the overridden method,\n * update the namespace for its defining class (i.e\n :py:meth:`render_data[__class__]\n `) within the\n :py:class:`~term_image.renderable.RenderData` instance returned by the\n overridden method,\n * return the same :py:class:`~term_image.renderable.RenderData` instance.\n\n IMPORTANT:\n The :py:class:`~term_image.renderable.RenderData` instance returned must be\n associated [#rd-ass]_ with the type of the renderable on which this method\n is called i.e ``type(self)``. This is always the case for the base\n implementation of this method.\n\n NOTE:\n This method being called doesn't mean the data generated will be used\n immediately.\n\n .. seealso::\n :py:class:`~term_image.renderable.RenderData`,\n :py:meth:`_finalize_render_data_`,\n :py:meth:`~term_image.renderable.Renderable._init_render_`.\n \"\"\"\n render_data = RenderData(type(self))\n renderable_data: RenderableData = render_data[Renderable]\n renderable_data.update(\n size=self._get_render_size_(),\n frame_offset=self._frame,\n seek_whence=Seek.START,\n iteration=iteration,\n )\n if self.animated:\n renderable_data.duration = self._frame_duration\n\n return render_data\n\n @abstractmethod\n def _get_render_size_(self) -> geometry.Size:\n \"\"\"Returns the renderable's :term:`render size`.\n\n Returns:\n The size of the renderable's :term:`render output`.\n\n The base implementation raises :py:class:`NotImplementedError`.\n\n NOTE:\n Both dimensions are expected to be positive.\n\n .. seealso:: :py:attr:`render_size`\n \"\"\"\n raise NotImplementedError\n\n def _handle_interrupted_draw_(\n self, render_data: RenderData, render_args: RenderArgs, output: TextIO\n ) -> None:\n \"\"\"Performs any special handling necessary when an interruption occurs while\n writing a :term:`render output` to a stream.\n\n Args:\n render_data: Render data.\n render_args: Render arguments.\n output: The text I/O stream to which the render output was being written.\n\n Called by the base implementations of :py:meth:`draw` (for non-animations)\n and :py:meth:`_animate_` when :py:class:`KeyboardInterrupt` is raised while\n writing a render output.\n\n The base implementation does nothing.\n\n NOTE:\n *output* should be flushed by this method.\n\n HINT:\n For a renderable that uses SGR sequences in its render output, this method\n may write ``CSI 0 m`` to *output*.\n \"\"\"\n\n # *render_args*, no *padding*; or neither\n @overload\n def _init_render_(\n self,\n renderer: Callable[[RenderData, RenderArgs], T],\n render_args: RenderArgs | None = None,\n *,\n iteration: bool = False,\n finalize: bool = True,\n check_size: bool = False,\n allow_scroll: bool = False,\n ) -> tuple[T, None]: ...\n\n # both *render_args* and *padding*\n @overload\n def _init_render_(\n self,\n renderer: Callable[[RenderData, RenderArgs], T],\n render_args: RenderArgs | None,\n padding: OptionalPaddingT,\n *,\n iteration: bool = False,\n finalize: bool = True,\n check_size: bool = False,\n allow_scroll: bool = False,\n ) -> tuple[T, OptionalPaddingT]: ...\n\n # *padding*, no *render_args*\n @overload\n def _init_render_(\n self,\n renderer: Callable[[RenderData, RenderArgs], T],\n *,\n padding: OptionalPaddingT,\n iteration: bool = False,\n finalize: bool = True,\n check_size: bool = False,\n allow_scroll: bool = False,\n ) -> tuple[T, OptionalPaddingT]: ...\n\n def _init_render_(\n self,\n renderer: Callable[[RenderData, RenderArgs], T],\n render_args: RenderArgs | None = None,\n padding: Padding | None = None,\n *,\n iteration: bool = False,\n finalize: bool = True,\n check_size: bool = False,\n allow_scroll: bool = False,\n ) -> tuple[T, Padding | None]:\n \"\"\"Initiates a render operation.\n\n Args:\n renderer: Performs a render operation or extracts render data and arguments\n for a render operation to be performed later on.\n render_args: Render arguments.\n padding (:py:data:`OptionalPaddingT`): :term:`Render output` padding.\n iteration: Whether the render operation involves a sequence of renders\n (most likely of different frames), or it's a one-off render.\n finalize: Whether to finalize the render data passed to *renderer*\n immediately *renderer* returns.\n check_size: Whether to validate the [padded] :term:`render size` of\n **non-animations**.\n allow_scroll: Whether to validate the [padded] :term:`render height` of\n **non-animations**. Ignored if *check_size* is ``False``.\n\n Returns:\n A tuple containing\n\n * The return value of *renderer*.\n * *padding* (with equivalent **absolute** dimensions if it's an instance of\n :py:class:`~term_image.padding.AlignedPadding`).\n\n Raises:\n IncompatibleRenderArgsError: Incompatible render arguments.\n RenderSizeOutofRangeError: *check_size* is ``True`` and the [padded]\n :term:`render size` cannot fit into the :term:`terminal size`.\n\n :rtype: tuple[T, :py:data:`OptionalPaddingT`]\n\n After preparing render data and processing arguments, *renderer* is called with\n the following positional arguments:\n\n 1. Render data associated with **the renderable's class**\n 2. Render arguments associated with **the renderable's class** and initialized\n with *render_args*\n\n Any exception raised by *renderer* is propagated.\n\n IMPORTANT:\n Beyond this method (i.e any context from *renderer* onwards), use of any\n variable state (internal or external) should be avoided if possible.\n Any variable state (internal or external) required for rendering should\n be provided via :py:meth:`_get_render_data_`.\n\n If at all any variable state has to be used and is not\n reasonable/practicable to be provided via :py:meth:`_get_render_data_`,\n it should be read only once during a single render and passed to any\n nested/subsequent calls that require the value of that state during the\n same render.\n\n This is to prevent inconsistency in data used for the same render which may\n result in unexpected output.\n \"\"\"\n if not (render_args and render_args.render_cls is type(self)):\n # Validate compatibility (and convert, if compatible)\n render_args = RenderArgs(type(self), render_args)\n terminal_size = get_terminal_size()\n render_data = self._get_render_data_(iteration=iteration)\n try:\n if padding and isinstance(padding, AlignedPadding) and padding.relative:\n padding = padding.resolve(terminal_size)\n\n if check_size:\n render_size: Size = render_data[Renderable].size\n width, height = (\n padding.get_padded_size(render_size) if padding else render_size\n )\n terminal_width, terminal_height = terminal_size\n\n if width > terminal_width:\n raise RenderSizeOutofRangeError(\n f\"{'Padded render' if padding else 'Render'} width out of \"\n f\"range (got: {width}; terminal_width={terminal_width})\"\n )\n if not allow_scroll and height > terminal_height:\n raise RenderSizeOutofRangeError(\n f\"{'Padded render' if padding else 'Render'} height out of \"\n f\"range (got: {height}; terminal_height={terminal_height})\"\n )\n\n return renderer(render_data, render_args), padding\n finally:\n if finalize:\n render_data.finalize()\n\n @abstractmethod\n def _render_(self, render_data: RenderData, render_args: RenderArgs) -> Frame:\n \"\"\":term:`Renders` a frame.\n\n Args:\n render_data: Render data.\n render_args: Render arguments.\n\n Returns:\n The rendered frame.\n\n * The :py:attr:`~term_image.renderable.Frame.render_size` field =\n :py:attr:`render_data[Renderable].size\n `.\n * The :py:attr:`~term_image.renderable.Frame.render_output` field holds the\n :term:`render output`. This string should:\n\n * contain as many lines as ``render_size.height`` i.e exactly\n ``render_size.height - 1`` occurrences of ``\\\\n`` (the newline\n sequence).\n * occupy exactly ``render_size.height`` lines and ``render_size.width``\n columns on each line when drawn onto a terminal screen, **at least**\n when the render **size** it not greater than the terminal size on\n either axis.\n\n .. tip::\n If for any reason, the output behaves differently when the render\n **height** is greater than the terminal height, the behaviour, along\n with any possible alternatives or workarounds, should be duely noted.\n This doesn't apply to the **width**.\n\n * **not** end with ``\\\\n`` (the newline sequence).\n\n * As for the :py:attr:`~term_image.renderable.Frame.duration` field, if\n the renderable is:\n\n * **animated**; the value should be determined from the frame data\n source (or a default/fallback value, if undeterminable), if\n :py:attr:`render_data[Renderable].duration\n ` is\n :py:attr:`~term_image.renderable.FrameDuration.DYNAMIC`.\n Otherwise, it should be equal to\n :py:attr:`render_data[Renderable].duration\n `.\n * **non-animated**; the value range is unspecified i.e it may be given\n any value.\n\n Raises:\n StopIteration: End of iteration for an animated renderable with\n :py:attr:`~term_image.renderable.FrameCount.INDEFINITE` frame count.\n RenderError: An error occurred while rendering.\n\n NOTE:\n :py:class:`StopIteration` may be raised if and only if\n :py:attr:`render_data[Renderable].iteration\n ` is ``True``.\n Otherwise, it would be out of place.\n\n .. seealso:: :py:class:`~term_image.renderable.RenderableData`.\n \"\"\"\n raise NotImplementedError", "n_imports_parsed": 14, "n_files_resolved": 7, "n_chars_extracted": 41124}, "tests/test_image/test_others.py::16": {"resolved_imports": ["src/term_image/image/common.py", "src/term_image/image/__init__.py"], "used_names": ["AutoImage", "BaseImage", "Size", "pytest", "python_image", "python_img"], "enclosing_function": "test_auto_image", "extracted_code": "# Source: src/term_image/image/common.py\nclass Size(Enum):\n \"\"\"Enumeration for :term:`automatic sizing`.\"\"\"\n\n #: Equivalent to :py:attr:`ORIGINAL` if it will fit into the\n #: :term:`frame size`, else :py:attr:`FIT`.\n #:\n #: :meta hide-value:\n AUTO = Hidden()\n\n #: The image size is set to fit optimally **within** the :term:`frame size`.\n #:\n #: :meta hide-value:\n FIT = Hidden()\n\n #: The size is set such that the width is exactly the :term:`frame width`,\n #: regardless of the :term:`cell ratio`.\n #:\n #: :meta hide-value:\n FIT_TO_WIDTH = Hidden()\n\n #: The image size is set such that the image is rendered with as many pixels as the\n #: the original image consists of.\n #:\n #: :meta hide-value:\n ORIGINAL = Hidden()\n\nclass BaseImage(metaclass=ImageMeta):\n \"\"\"Base of all render styles.\n\n Args:\n image: Source image.\n width: Can be\n\n * a positive integer; horizontal dimension of the image, in columns.\n * a :py:class:`~term_image.image.Size` enum member.\n\n height: Can be\n\n * a positive integer; vertical dimension of the image, in lines.\n * a :py:class:`~term_image.image.Size` enum member.\n\n Raises:\n TypeError: An argument is of an inappropriate type.\n ValueError: An argument is of an appropriate type but has an\n unexpected/invalid value.\n\n Propagates exceptions raised by :py:meth:`set_size`, if *width* or *height* is\n given.\n\n NOTE:\n * If neither *width* nor *height* is given (or both are ``None``),\n :py:attr:`~term_image.image.Size.FIT` applies.\n * If both width and height are not ``None``, they must be positive integers\n and :term:`manual sizing` applies i.e the image size is set as given without\n preserving aspect ratio.\n * For animated images, the seek position is initialized to the current seek\n position of the given image.\n * It's allowed to set properties for :term:`animated` images on non-animated\n ones, the values are simply ignored.\n\n ATTENTION:\n This class cannot be directly instantiated. Image instances should be created\n from its subclasses.\n \"\"\"\n\n # Data Attributes\n\n _forced_support: bool = False\n _supported: Optional[bool] = None\n _render_method: Optional[str] = None\n _render_methods: Set[str] = set()\n _style_args: Dict[\n str, Tuple[Tuple[FunctionType, str], Tuple[FunctionType, str]]\n ] = {}\n\n # Special Methods\n\n def __init__(\n self,\n image: PIL.Image.Image,\n *,\n width: Union[int, Size, None] = None,\n height: Union[int, Size, None] = None,\n ) -> None:\n \"\"\"See the class description\"\"\"\n if not isinstance(image, Image.Image):\n raise arg_type_error(\"image\", image)\n if 0 in image.size:\n raise ValueError(\"'image' is null-sized\")\n\n self._closed = False\n self._source = image\n self._source_type = ImageSource.PIL_IMAGE\n self._original_size = image.size\n if width is None is height:\n self.size = Size.FIT\n else:\n self.set_size(width, height)\n\n self._is_animated = hasattr(image, \"is_animated\") and image.is_animated\n if self._is_animated:\n self._frame_duration = (image.info.get(\"duration\") or 100) / 1000\n self._seek_position = image.tell()\n self._n_frames = None\n\n def __del__(self) -> None:\n self.close()\n\n def __enter__(self) -> BaseImage:\n return self\n\n def __exit__(self, typ: type, val: Exception, tb: TracebackType) -> bool:\n self.close()\n return False # Currently, no particular exception is suppressed\n\n def __format__(self, spec: str) -> str:\n \"\"\"Renders the image with alignment, padding and transparency control\"\"\"\n # Only the currently set frame is rendered for animated images\n h_align, width, v_align, height, alpha, style_args = self._check_format_spec(\n spec\n )\n\n return self._format_render(\n self._renderer(self._render_image, alpha, **style_args),\n h_align,\n width,\n v_align,\n height,\n )\n\n def __iter__(self) -> ImageIterator:\n return ImageIterator(self, 1, \"1.1\", False)\n\n def __repr__(self) -> str:\n return \"<{}: source_type={} size={} is_animated={}>\".format(\n type(self).__name__,\n self._source_type.name,\n (\n self._size.name\n if isinstance(self._size, Size)\n else \"x\".join(map(str, self._size))\n ),\n self._is_animated,\n )\n\n def __str__(self) -> str:\n \"\"\"Renders the image with transparency enabled and without alignment\"\"\"\n # Only the currently set frame is rendered for animated images\n return self._renderer(self._render_image, _ALPHA_THRESHOLD)\n\n # Properties\n\n closed = property(\n lambda self: self._closed,\n doc=\"\"\"Instance finalization status\n\n :type: bool\n\n GET:\n Returns ``True`` if the instance has been finalized (:py:meth:`close` has\n been called). Otherwise, ``False``.\n \"\"\",\n )\n\n forced_support = ClassProperty(\n lambda self: type(self)._forced_support,\n doc=\"\"\"Forced render style support\n\n :type: bool\n\n GET:\n Returns the forced support status of the invoking class or class of the\n invoking instance.\n\n SET:\n Forced support is enabled or disabled for the invoking class.\n\n Can not be set on an instance.\n\n If forced support is:\n\n * **enabled**, the render style is treated as if it were supported,\n regardless of the return value of :py:meth:`is_supported`.\n * **disabled**, the return value of :py:meth:`is_supported` determines if\n the render style is supported or not.\n\n By **default**, forced support is **disabled** for all render style classes.\n\n NOTE:\n * This property is :term:`descendant`.\n * This doesn't affect the return value of :py:meth:`is_supported` but\n may affect operations that require that a render style be supported e.g\n instantiation of some render style classes.\n \"\"\",\n )\n\n frame_duration = property(\n lambda self: self._frame_duration if self._is_animated else None,\n doc=\"\"\"Duration of a single frame\n\n :type: Optional[float]\n\n GET:\n Returns:\n\n * The duration of a single frame (in seconds), if the image is animated.\n * ``None``, if otherwise.\n\n SET:\n If the image is animated, The frame duration is set.\n Otherwise, nothing is done.\n \"\"\",\n )\n\n @frame_duration.setter\n def frame_duration(self, value: float) -> None:\n if not isinstance(value, float):\n raise arg_type_error(\"frame_duration\", value)\n if value <= 0.0:\n raise arg_value_error_range(\"frame_duration\", value)\n if self._is_animated:\n self._frame_duration = value\n\n height = property(\n lambda self: self._size if isinstance(self._size, Size) else self._size[1],\n lambda self, height: self.set_size(height=height),\n doc=\"\"\"\n Image height\n\n :type: Union[Size, int]\n\n GET:\n Returns:\n\n * The image height (in lines), if the image size is\n :term:`fixed `.\n * A :py:class:`~term_image.image.Size` enum member, if the image size\n is :term:`dynamic `.\n\n SET:\n If set to:\n\n * a positive :py:class:`int`; the image height is set to the given value\n and the width is set proportionally.\n * a :py:class:`~term_image.image.Size` enum member; the image size is set\n as prescibed by the enum member.\n * ``None``; equivalent to :py:attr:`~term_image.image.Size.FIT`.\n\n This results in a :term:`fixed size`.\n \"\"\",\n )\n\n is_animated = property(\n lambda self: self._is_animated,\n doc=\"\"\"\n Animatability of the image\n\n :type: bool\n\n GET:\n Returns ``True`` if the image is :term:`animated`. Otherwise, ``False``.\n \"\"\",\n )\n\n original_size = property(\n lambda self: self._original_size,\n doc=\"\"\"Size of the source (in pixels)\n\n :type: Tuple[int, int]\n\n GET:\n Returns the source size.\n \"\"\",\n )\n\n @property\n def n_frames(self) -> int:\n \"\"\"Image frame count\n\n :type: int\n\n GET:\n Returns the number of frames the image has.\n \"\"\"\n if not self._is_animated:\n return 1\n\n if not self._n_frames:\n img = self._get_image()\n try:\n self._n_frames = img.n_frames\n finally:\n self._close_image(img)\n\n return self._n_frames\n\n rendered_height = property(\n lambda self: (\n self._valid_size(None, self._size)\n if isinstance(self._size, Size)\n else self._size\n )[1],\n doc=\"\"\"\n The height with which the image is :term:`rendered`\n\n :type: int\n\n GET:\n Returns the number of lines the image will occupy when drawn in a terminal.\n \"\"\",\n )\n\n rendered_size = property(\n lambda self: (\n self._valid_size(self._size, None)\n if isinstance(self._size, Size)\n else self._size\n ),\n doc=\"\"\"\n The size with which the image is :term:`rendered`\n\n :type: Tuple[int, int]\n\n GET:\n Returns the number of columns and lines (respectively) the image will\n occupy when drawn in a terminal.\n \"\"\",\n )\n\n rendered_width = property(\n lambda self: (\n self._valid_size(self._size, None)\n if isinstance(self._size, Size)\n else self._size\n )[0],\n doc=\"\"\"\n The width with which the image is :term:`rendered`\n\n :type: int\n\n GET:\n Returns the number of columns the image will occupy when drawn in a\n terminal.\n \"\"\",\n )\n\n size = property(\n lambda self: self._size,\n doc=\"\"\"\n Image size\n\n :type: Union[Size, Tuple[int, int]]\n\n GET:\n Returns:\n\n * The image size, ``(columns, lines)``, if the image size is\n :term:`fixed `.\n * A :py:class:`~term_image.image.Size` enum member, if the image size\n is :term:`dynamic `.\n\n SET:\n If set to a:\n\n * :py:class:`~term_image.image.Size` enum member, the image size is set\n as prescibed by the given member.\n\n This results in a :term:`dynamic size` i.e the size is computed whenever\n the image is :term:`rendered` using the default :term:`frame size`.\n\n * 2-tuple of integers, ``(width, height)``, the image size set as given.\n\n This results in a :term:`fixed size` i.e the size will not change until\n it is re-set.\n \"\"\",\n )\n\n @size.setter\n def size(self, size: Size | Tuple[int, int]) -> None:\n if isinstance(size, Size):\n self._size = size\n elif isinstance(size, tuple):\n if len(size) != 2:\n raise arg_value_error(\"size\", size)\n self.set_size(*size)\n else:\n raise arg_type_error(\"size\", size)\n\n source = property(\n _close_validated(lambda self: getattr(self, self._source_type.value)),\n doc=\"\"\"\n Image :term:`source`\n\n :type: Union[PIL.Image.Image, str]\n\n GET:\n Returns the :term:`source` from which the instance was initialized.\n \"\"\",\n )\n\n source_type = property(\n lambda self: self._source_type,\n doc=\"\"\"\n Image :term:`source` type\n\n :type: ImageSource\n\n GET:\n Returns the type of :term:`source` from which the instance was initialized.\n \"\"\",\n )\n\n width = property(\n lambda self: self._size if isinstance(self._size, Size) else self._size[0],\n lambda self, width: self.set_size(width),\n doc=\"\"\"\n Image width\n\n :type: Union[Size, int]\n\n GET:\n Returns:\n\n * The image width (in columns), if the image size is\n :term:`fixed `.\n * A :py:class:`~term_image.image.Size` enum member; if the image size\n is :term:`dynamic `.\n\n SET:\n If set to:\n\n * a positive :py:class:`int`; the image width is set to the given value\n and the height is set proportionally.\n * a :py:class:`~term_image.image.Size` enum member; the image size is set\n as prescibed by the enum member.\n * ``None``; equivalent to :py:attr:`~term_image.image.Size.FIT`.\n\n This results in a :term:`fixed size`.\n \"\"\",\n )\n\n # # Private\n\n @property\n @abstractmethod\n def _pixel_ratio(self):\n \"\"\"The width-to-height ratio of a pixel drawn in the terminal\"\"\"\n raise NotImplementedError\n\n # Public Methods\n\n def close(self) -> None:\n \"\"\"Finalizes the instance and releases external resources.\n\n * In most cases, it's not necessary to explicitly call this method, as it's\n automatically called when the instance is garbage-collected.\n * This method can be safely called multiple times.\n * If the instance was initialized with a PIL image, the PIL image is never\n finalized.\n \"\"\"\n try:\n if not self._closed:\n if self._source_type is ImageSource.URL:\n try:\n os.remove(self._source)\n except FileNotFoundError:\n pass\n del self._url\n del self._source\n except AttributeError:\n pass # Instance creation or initialization was unsuccessful\n finally:\n self._closed = True\n\n def draw(\n self,\n h_align: Optional[str] = None,\n pad_width: int = 0,\n v_align: Optional[str] = None,\n pad_height: int = -2,\n alpha: Optional[float, str] = _ALPHA_THRESHOLD,\n *,\n animate: bool = True,\n repeat: int = -1,\n cached: Union[bool, int] = 100,\n scroll: bool = False,\n check_size: bool = True,\n **style: Any,\n ) -> None:\n \"\"\"Draws the image to standard output.\n\n Args:\n h_align: Horizontal alignment (\"left\" / \"<\", \"center\" / \"|\" or\n \"right\" / \">\"). Default: center.\n pad_width: Number of columns within which to align the image.\n\n * Excess columns are filled with spaces.\n * Must not be greater than the :term:`terminal width`.\n\n v_align: Vertical alignment (\"top\"/\"^\", \"middle\"/\"-\" or \"bottom\"/\"_\").\n Default: middle.\n pad_height: Number of lines within which to align the image.\n\n * Excess lines are filled with spaces.\n * Must not be greater than the :term:`terminal height`,\n **for animations**.\n\n alpha: Transparency setting.\n\n * If ``None``, transparency is disabled (alpha channel is removed).\n * If a ``float`` (**0.0 <= x < 1.0**), specifies the alpha ratio\n **above** which pixels are taken as **opaque**. **(Applies to only\n text-based render styles)**.\n * If a string, specifies a color to replace transparent background with.\n Can be:\n\n * **\"#\"** -> The terminal's default background color (or black, if\n undetermined) is used.\n * A hex color e.g ``ffffff``, ``7faa52``.\n\n animate: If ``False``, disable animation i.e draw only the current frame of\n an animated image.\n repeat: The number of times to go over all frames of an animated image.\n A negative value implies infinite repetition.\n cached: Determines if :term:`rendered` frames of an animated image will be\n cached (for speed up of subsequent renders of the same frame) or not.\n\n * If :py:class:`bool`, it directly sets if the frames will be cached or\n not.\n * If :py:class:`int`, caching is enabled only if the framecount of the\n image is less than or equal to the given number.\n\n scroll: Only applies to non-animations. If ``True``, allows the image's\n :term:`rendered height` to be greater than the :term:`terminal height`.\n check_size: If ``False``, rendered size validation is not performed for\n non-animations. Does not affect padding size validation.\n style: Style-specific render parameters. See each subclass for it's own\n usage.\n\n Raises:\n TypeError: An argument is of an inappropriate type.\n ValueError: An argument is of an appropriate type but has an\n unexpected/invalid value.\n term_image.exceptions.InvalidSizeError: The image's :term:`rendered size`\n can not fit into the :term:`terminal size`.\n term_image.exceptions.StyleError: Unrecognized style-specific render\n parameter(s).\n term_image.exceptions.RenderError: An error occurred during\n :term:`rendering`.\n\n * If *pad_width* or *pad_height* is:\n\n * positive, it is **absolute** and used as-is.\n * non-positive, it is **relative** to the corresponding terminal dimension\n (**at the point of calling this method**) and equivalent to the absolute\n dimension ``max(terminal_dimension + frame_dimension, 1)``.\n\n * :term:`padding width` is always validated.\n * *animate*, *repeat* and *cached* apply to :term:`animated` images only.\n They are simply ignored for non-animated images.\n * For animations (i.e animated images with *animate* set to ``True``):\n\n * *scroll* is ignored.\n * Image size is always validated, if set.\n * :term:`Padding height` is always validated.\n\n * Animations, **by default**, are infinitely looped and can be terminated\n with :py:data:`~signal.SIGINT` (``CTRL + C``), **without** raising\n :py:class:`KeyboardInterrupt`.\n \"\"\"\n fmt = self._check_formatting(h_align, pad_width, v_align, pad_height)\n\n if alpha is not None:\n if isinstance(alpha, float):\n if not 0.0 <= alpha < 1.0:\n raise arg_value_error_range(\"alpha\", alpha)\n elif isinstance(alpha, str):\n if not _ALPHA_BG_FORMAT.fullmatch(alpha):\n raise arg_value_error_msg(\"Invalid hex color string\", alpha)\n else:\n raise arg_type_error(\"alpha\", alpha)\n\n if self._is_animated and not isinstance(animate, bool):\n raise arg_type_error(\"animate\", animate)\n\n terminal_width, terminal_height = get_terminal_size()\n if pad_width > terminal_width:\n raise arg_value_error_range(\n \"pad_width\", pad_width, got_extra=f\"terminal_width={terminal_width}\"\n )\n\n animation = self._is_animated and animate\n\n if animation and pad_height > terminal_height:\n raise arg_value_error_range(\n \"pad_height\",\n pad_height,\n got_extra=f\"terminal_height={terminal_height}, animation={animation}\",\n )\n\n for arg in (\"scroll\", \"check_size\"):\n arg_value = locals()[arg]\n if not isinstance(arg_value, bool):\n raise arg_type_error(arg, arg_value)\n\n # Checks for *repeat* and *cached* are delegated to `ImageIterator`.\n\n def render(image: PIL.Image.Image) -> None:\n # Hide the cursor immediately if the output is a terminal device\n sys.stdout.isatty() and print(HIDE_CURSOR, end=\"\", flush=True)\n try:\n style_args = self._check_style_args(style)\n if animation:\n self._display_animated(\n image, alpha, fmt, repeat, cached, **style_args\n )\n else:\n try:\n print(\n self._format_render(\n self._render_image(image, alpha, **style_args),\n *fmt,\n ),\n end=\"\",\n flush=True,\n )\n except (KeyboardInterrupt, Exception):\n self._handle_interrupted_draw()\n raise\n finally:\n # Reset color and show the cursor\n print(SGR_DEFAULT, SHOW_CURSOR * sys.stdout.isatty(), sep=\"\")\n\n self._renderer(\n render,\n scroll=scroll,\n check_size=check_size,\n animated=animation,\n )\n\n @classmethod\n def from_file(\n cls,\n filepath: Union[str, os.PathLike],\n **kwargs: Union[None, int],\n ) -> BaseImage:\n \"\"\"Creates an instance from an image file.\n\n Args:\n filepath: Relative/Absolute path to an image file.\n kwargs: Same keyword arguments as the class constructor.\n\n Returns:\n A new instance.\n\n Raises:\n TypeError: *filepath* is of an inappropriate type.\n FileNotFoundError: The given path does not exist.\n\n Propagates exceptions raised (or propagated) by :py:func:`PIL.Image.open` and\n the class constructor.\n \"\"\"\n if not isinstance(filepath, (str, os.PathLike)):\n raise arg_type_error(\"filepath\", filepath)\n\n if isinstance(filepath, os.PathLike):\n filepath = filepath.__fspath__()\n if isinstance(filepath, bytes):\n filepath = filepath.decode()\n\n # Intentionally propagates `IsADirectoryError` since the message is OK\n try:\n img = Image.open(filepath)\n except FileNotFoundError:\n raise FileNotFoundError(f\"No such file: {filepath!r}\") from None\n except UnidentifiedImageError as e:\n e.args = (f\"Could not identify {filepath!r} as an image\",)\n raise\n\n with img:\n new = cls(img, **kwargs)\n # Absolute paths work better with symlinks, as opposed to real paths:\n # less confusing, Filename is as expected, helps in path comparisons\n new._source = os.path.abspath(filepath)\n new._source_type = ImageSource.FILE_PATH\n return new\n\n @classmethod\n def from_url(\n cls,\n url: str,\n **kwargs: Union[None, int],\n ) -> BaseImage:\n \"\"\"Creates an instance from an image URL.\n\n Args:\n url: URL of an image file.\n kwargs: Same keyword arguments as the class constructor.\n\n Returns:\n A new instance.\n\n Raises:\n TypeError: *url* is not a string.\n ValueError: The URL is invalid.\n term_image.exceptions.URLNotFoundError: The URL does not exist.\n PIL.UnidentifiedImageError: Propagated from :py:func:`PIL.Image.open`.\n\n Also propagates connection-related exceptions from :py:func:`requests.get`\n and exceptions raised or propagated by the class constructor.\n\n NOTE:\n This method creates a temporary file, but only after successful\n initialization. The file is removed:\n\n - when :py:meth:`close` is called,\n - upon exiting a ``with`` statement block that uses the instance as a\n context manager, or\n - when the instance is garbage collected.\n \"\"\"\n if not isinstance(url, str):\n raise arg_type_error(\"url\", url)\n if not all(urlparse(url)[:3]):\n raise arg_value_error_msg(\"Invalid URL\", url)\n\n # Propagates connection-related errors.\n response = requests.get(url, stream=True)\n if response.status_code == 404:\n raise URLNotFoundError(f\"URL {url!r} does not exist.\")\n\n # Ensure initialization is successful before writing to file\n try:\n new = cls(Image.open(io.BytesIO(response.content)), **kwargs)\n except UnidentifiedImageError as e:\n e.args = (f\"The URL {url!r} doesn't link to an identifiable image\",)\n raise\n\n fd, filepath = mkstemp(\"-\" + os.path.basename(url), dir=_TEMP_DIR)\n os.write(fd, response.content)\n os.close(fd)\n\n new._source = filepath\n new._source_type = ImageSource.URL\n new._url = url\n return new\n\n @classmethod\n @abstractmethod\n def is_supported(cls) -> bool:\n \"\"\"Checks if the implemented :term:`render style` is supported by the\n :term:`active terminal`.\n\n Returns:\n ``True`` if the render style implemented by the invoking class is supported\n by the :term:`active terminal`. Otherwise, ``False``.\n\n ATTENTION:\n Support checks for most (if not all) render styles require :ref:`querying\n ` the :term:`active terminal` the **first time** they're\n executed.\n\n Hence, it's advisable to perform all necessary support checks (call\n this method on required style classes) at an early stage of a program,\n before user input is expected. If using automatic style selection,\n calling :py:func:`~term_image.image.auto_image_class` only should be\n sufficient.\n \"\"\"\n raise NotImplementedError\n\n def seek(self, pos: int) -> None:\n \"\"\"Changes current image frame.\n\n Args:\n pos: New frame number.\n\n Raises:\n TypeError: An argument is of an inappropriate type.\n ValueError: An argument is of an appropriate type but has an\n unexpected/invalid value.\n\n Frame numbers start from 0 (zero).\n \"\"\"\n if not isinstance(pos, int):\n raise arg_type_error(\"pos\", pos)\n if not 0 <= pos < self.n_frames:\n raise arg_value_error_range(\"pos\", pos, f\"n_frames={self.n_frames}\")\n if self._is_animated:\n self._seek_position = pos\n\n @ClassInstanceMethod\n def set_render_method(cls, method: Optional[str] = None) -> None:\n \"\"\"Sets the :term:`render method` used by instances of a :term:`render style`\n class that implements multiple render methods.\n\n Args:\n method: The render method to be set or ``None`` for a reset\n (case-insensitive).\n\n Raises:\n TypeError: An argument is of an inappropriate type.\n ValueError: An argument is of an appropriate type but has an\n unexpected/invalid value.\n\n See the **Render Methods** section in the description of subclasses that\n implement such for their specific usage.\n\n If *method* is not ``None`` and this method is called via:\n\n - a class, the class-wide render method is set.\n - an instance, the instance-specific render method is set.\n\n If *method* is ``None`` and this method is called via:\n\n - a class, the class-wide render method is unset, so that it uses that of\n its parent style class (if any) or the default.\n - an instance, the instance-specific render method is unset, so that it\n uses the class-wide render method thenceforth.\n\n Any instance without a render method set uses the class-wide render method.\n\n NOTE:\n *method* = ``None`` is always allowed, even if the render style doesn't\n implement multiple render methods.\n\n The **class-wide** render method is :term:`descendant`.\n \"\"\"\n if method is not None and not isinstance(method, str):\n raise arg_type_error(\"method\", method)\n if method is not None and method.lower() not in cls._render_methods:\n raise ValueError(f\"Unknown render method {method!r} for {cls.__name__}\")\n\n if not method:\n if cls._render_methods:\n cls._render_method = cls._default_render_method\n else:\n cls._render_method = method\n\n @set_render_method.instancemethod\n def set_render_method(self, method: Optional[str] = None) -> None:\n if method is not None and not isinstance(method, str):\n raise arg_type_error(\"method\", method)\n if method is not None and method.lower() not in type(self)._render_methods:\n raise ValueError(\n f\"Unknown render method {method!r} for {type(self).__name__}\"\n )\n\n if not method:\n try:\n del self._render_method\n except AttributeError:\n pass\n else:\n self._render_method = method\n\n def set_size(\n self,\n width: Union[int, Size, None] = None,\n height: Union[int, Size, None] = None,\n frame_size: Tuple[int, int] = (0, -2),\n ) -> None:\n \"\"\"Sets the image size (with extended control).\n\n Args:\n width: Can be\n\n * a positive integer; horizontal dimension of the image, in columns.\n * a :py:class:`~term_image.image.Size` enum member.\n\n height: Can be\n\n * a positive integer; vertical dimension of the image, in lines.\n * a :py:class:`~term_image.image.Size` enum member.\n\n frame_size: :term:`Frame size`, ``(columns, lines)``.\n If *columns* or *lines* is\n\n * positive, it is **absolute** and used as-is.\n * non-positive, it is **relative** to the corresponding terminal dimension\n and equivalent to the absolute dimension\n ``max(terminal_dimension + frame_dimension, 1)``.\n\n This is used only when neither *width* nor *height* is an ``int``.\n\n Raises:\n TypeError: An argument is of an inappropriate type.\n ValueError: An argument is of an appropriate type but has an\n unexpected/invalid value.\n\n * If both width and height are not ``None``, they must be positive integers\n and :term:`manual sizing` applies i.e the image size is set as given without\n preserving aspect ratio.\n * If *width* or *height* is a :py:class:`~term_image.image.Size` enum\n member, :term:`automatic sizing` applies as prescribed by the enum member.\n * If neither *width* nor *height* is given (or both are ``None``),\n :py:attr:`~term_image.image.Size.FIT` applies.\n \"\"\"\n width_height = (width, height)\n for arg_name, arg_value in zip((\"width\", \"height\"), width_height):\n if not (arg_value is None or isinstance(arg_value, (Size, int))):\n raise arg_type_error(arg_name, arg_value)\n if isinstance(arg_value, int) and arg_value <= 0:\n raise arg_value_error_range(arg_name, arg_value)\n\n if width is not None is not height:\n if not all(isinstance(x, int) for x in width_height):\n width_type = type(width).__name__\n height_type = type(height).__name__\n raise TypeError(\n \"Both 'width' and 'height' are specified but are not both integers \"\n f\"(got: ({width_type}, {height_type}))\"\n )\n\n self._size = width_height\n return\n\n if not (\n isinstance(frame_size, tuple)\n and all(isinstance(x, int) for x in frame_size)\n ):\n raise arg_type_error(\"frame_size\", frame_size)\n if not len(frame_size) == 2:\n raise arg_value_error(\"frame_size\", frame_size)\n\n self._size = self._valid_size(width, height, frame_size)\n\n def tell(self) -> int:\n \"\"\"Returns the current image frame number.\n\n :rtype: int\n \"\"\"\n return self._seek_position if self._is_animated else 0\n\n # Private Methods\n\n @classmethod\n def _check_format_spec(cls, spec: str) -> Tuple[\n str | None,\n int,\n str | None,\n int,\n Union[None, float, str],\n Dict[str, Any],\n ]:\n \"\"\"Validates a format specifier and translates it into the required values.\n\n Returns:\n A tuple ``(h_align, width, v_align, height, alpha, style_args)`` containing\n values as required by ``_format_render()`` and ``_render_image()``.\n \"\"\"\n match_ = _FORMAT_SPEC.fullmatch(spec)\n if not match_ or _NO_VERTICAL_SPEC.fullmatch(spec):\n raise arg_value_error_msg(\"Invalid format specifier\", spec)\n\n (\n _,\n h_align,\n width,\n _,\n v_align,\n height,\n alpha,\n threshold_or_bg,\n _,\n style_spec,\n ) = match_.groups()\n\n return (\n *cls._check_formatting(\n h_align,\n int(width) if width else 0,\n v_align,\n int(height) if height else -2,\n ),\n (\n threshold_or_bg\n and (\n \"#\" + threshold_or_bg.lstrip(\"#\")\n if _ALPHA_BG_FORMAT.fullmatch(\"#\" + threshold_or_bg.lstrip(\"#\"))\n else float(threshold_or_bg)\n )\n if alpha\n else _ALPHA_THRESHOLD\n ),\n style_spec and cls._check_style_format_spec(style_spec, style_spec) or {},\n )\n\n @staticmethod\n def _check_formatting(\n h_align: str | None = None,\n width: int = 0,\n v_align: str | None = None,\n height: int = -2,\n ) -> Tuple[str | None, int, str | None, int]:\n \"\"\"Validates and transforms formatting arguments.\n\n Returns:\n The respective arguments appropriate for ``_format_render()``.\n \"\"\"\n if not isinstance(h_align, (type(None), str)):\n raise arg_type_error(\"h_align\", h_align)\n if None is not h_align not in set(\"<|>\"):\n align = {\"left\": \"<\", \"center\": \"|\", \"right\": \">\"}.get(h_align)\n if not align:\n raise arg_value_error(\"h_align\", h_align)\n h_align = align\n\n if not isinstance(v_align, (type(None), str)):\n raise arg_type_error(\"v_align\", v_align)\n if None is not v_align not in set(\"^-_\"):\n align = {\"top\": \"^\", \"middle\": \"-\", \"bottom\": \"_\"}.get(v_align)\n if not align:\n raise arg_value_error(\"v_align\", v_align)\n v_align = align\n\n terminal_size = get_terminal_size()\n\n if not isinstance(width, int):\n raise arg_type_error(\"pad_width\", width)\n width = width if width > 0 else max(terminal_size.columns + width, 1)\n\n if not isinstance(height, int):\n raise arg_type_error(\"pad_height\", height)\n height = height if height > 0 else max(terminal_size.lines + height, 1)\n\n return h_align, width, v_align, height\n\n @classmethod\n def _check_style_args(cls, style_args: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"Validates style-specific arguments and translates them into the required\n values.\n\n Removes any argument having a value equal to the default.\n\n Returns:\n A mapping of keyword arguments.\n\n Raises:\n TypeError: An argument is of an inappropriate type.\n ValueError: An argument is of an appropriate type but has an\n unexpected/invalid value.\n term_image.exceptions.StyleError: An unknown style-specific parameter is\n given.\n \"\"\"\n for name, value in tuple(style_args.items()):\n try:\n (\n default,\n (check_type, type_msg),\n (check_value, value_msg),\n ) = cls._style_args[name]\n except KeyError:\n for other_cls in cls.__mro__:\n # less costly than membership tests on every class' __bases__\n if other_cls is __class__:\n raise StyleError(\n f\"Unknown style-specific render parameter {name!r} for \"\n f\"{cls.__name__!r}\"\n )\n\n if not issubclass(\n other_cls, __class__\n ) or \"_style_args\" not in vars(other_cls):\n continue\n\n try:\n (check_type, type_msg), (check_value, value_msg) = super(\n other_cls, cls\n )._style_args[name]\n break\n except KeyError:\n pass\n else:\n raise StyleError(\n f\"Unknown style-specific render parameter {name!r} for \"\n f\"{cls.__name__!r}\"\n )\n\n if not check_type(value):\n raise TypeError(f\"{type_msg} (got: {type(value).__name__})\")\n if not check_value(value):\n raise ValueError(f\"{value_msg} (got: {value!r})\")\n\n # Must not occur before type and value checks to avoid falling prey of\n # operator overloading\n if value == default:\n del style_args[name]\n\n return style_args\n\n @classmethod\n def _check_style_format_spec(cls, spec: str, original: str) -> Dict[str, Any]:\n \"\"\"Validates a style-specific format specifier and translates it into\n the required values.\n\n Returns:\n A mapping of keyword arguments.\n\n Raises:\n term_image.exceptions.StyleError: Invalid style-specific format specifier.\n\n **Every style-specific format spec should be handled as follows:**\n\n Every overriding method should call the overridden method (more on this below).\n At every step in the call chain, the specifier should be of the form::\n\n [parent] [current] [invalid]\n\n where:\n\n - *parent* is the portion to be interpreted at an higher level in the chain\n - *current* is the portion to be interpreted at the current level in the chain\n - the *invalid* portion determines the validity of the format spec\n\n Handle the portions in the order *invalid*, *parent*, *current*, so that\n validity can be determined before any further processing.\n\n At any point in the chain where the *invalid* portion exists (i.e is non-empty),\n the format spec can be correctly taken to be invalid.\n\n An overriding method must call the overridden method with the *parent* portion\n and the original format spec, **if** *parent* **is not empty**, such that every\n successful check ends up at `BaseImage._check_style_args()` or when *parent* is\n empty.\n\n :py:meth:`_get_style_format_spec` may be used to parse the format spec at each\n level of the call chain.\n \"\"\"\n if spec:\n raise StyleError(\n f\"Invalid style-specific format specifier {original!r} \"\n f\"for {cls.__name__!r}\"\n + (f\", detected at {spec!r}\" if spec != original else \"\")\n )\n return {}\n\n @classmethod\n def _clear_frame(cls) -> bool:\n \"\"\"Clears an animation frame on-screen.\n\n Called by :py:meth:`_display_animated` just before drawing a new frame.\n\n | Only required by styles wherein an image is not overwritten by another image\n e.g some graphics-based styles.\n | The base implementation does nothing and should be overridden only if\n required.\n\n Returns:\n ``True`` if the frame was cleared. Otherwise, ``False``.\n \"\"\"\n return False\n\n def _close_image(self, img: PIL.Image.Image) -> None:\n \"\"\"Closes the given PIL image instance if it isn't the instance' source.\"\"\"\n if img is not self._source:\n img.close()\n\n def _display_animated(\n self,\n img: PIL.Image.Image,\n alpha: Union[None, float, str],\n fmt: Tuple[str | None, int, str | None, int],\n repeat: int,\n cached: Union[bool, int],\n **style_args: Any,\n ) -> None:\n \"\"\"Displays an animated GIF image in the terminal.\"\"\"\n lines = max(fmt[-1], self.rendered_height)\n prev_seek_pos = self._seek_position\n duration = self._frame_duration\n image_it = ImageIterator(self, repeat, \"\", cached)\n image_it._animator = image_it._animate(img, alpha, fmt, style_args)\n cursor_up = CURSOR_UP % (lines - 1)\n cursor_down = CURSOR_DOWN % lines\n\n try:\n print(next(image_it._animator), end=\"\", flush=True) # First frame\n\n # Render next frame during current frame's duration\n start = time.time()\n for frame in image_it._animator: # Renders next frame\n # Left-over of current frame's duration\n time.sleep(max(0, duration - (time.time() - start)))\n\n # Clear the current frame, if necessary,\n # move cursor up to the beginning of the first line of the image\n # and print the new current frame.\n self._clear_frame()\n print(\"\\r\", cursor_up, frame, sep=\"\", end=\"\", flush=True)\n\n # Render next frame during current frame's duration\n start = time.time()\n except KeyboardInterrupt:\n self._handle_interrupted_draw()\n except Exception:\n self._handle_interrupted_draw()\n raise\n finally:\n image_it.close()\n self._close_image(img)\n self._seek_position = prev_seek_pos\n # Move the cursor to the last line of the image to prevent \"overlaid\"\n # output in the terminal\n print(cursor_down, end=\"\")\n\n def _format_render(\n self,\n render: str,\n h_align: str | None,\n width: int,\n v_align: str | None,\n height: int,\n ) -> str:\n \"\"\"Pads and aligns a primary :term:`render` output.\n\n NOTE:\n * All arguments should be passed through ``_check_formatting()`` first.\n * Only **absolute** padding dimensions are expected.\n \"\"\"\n cols, lines = self.rendered_size\n\n if width > cols:\n if h_align == \"<\": # left\n left = \"\"\n right = \" \" * (width - cols)\n elif h_align == \">\": # right\n left = \" \" * (width - cols)\n right = \"\"\n else: # center\n left = \" \" * ((width - cols) // 2)\n right = \" \" * (width - cols - len(left))\n render = render.replace(\"\\n\", f\"{right}\\n{left}\")\n else:\n left = right = \"\"\n\n if height > lines:\n if v_align == \"^\": # top\n top = 0\n bottom = height - lines\n elif v_align == \"_\": # bottom\n top = height - lines\n bottom = 0\n else: # middle\n top = (height - lines) // 2\n bottom = height - lines - top\n top = f\"{' ' * width}\\n\" * top\n bottom = f\"\\n{' ' * width}\" * bottom\n else:\n top = bottom = \"\"\n\n return (\n \"\".join((top, left, render, right, bottom))\n if width > cols or height > lines\n else render\n )\n\n @_close_validated\n def _get_image(self) -> PIL.Image.Image:\n \"\"\"Returns the PIL image instance corresponding to the image source as-is\"\"\"\n return (\n Image.open(self._source) if isinstance(self._source, str) else self._source\n )\n\n def _get_render_data(\n self,\n img: PIL.Image.Image,\n alpha: Union[None, float, str],\n *,\n size: Optional[Tuple[int, int]] = None,\n pixel_data: bool = True,\n round_alpha: bool = False,\n frame: bool = False,\n ) -> Tuple[\n PIL.Image.Image, Optional[List[Tuple[int, int, int]]], Optional[List[int]]\n ]:\n \"\"\"Returns the PIL image instance and pixel data required to render an image.\n\n Args:\n size: If given (in pixels), it is used instead of the pixel-equivalent of\n the image size.\n pixel_data: If ``False``, ``None`` is returned for all pixel data.\n round_alpha: Only applies when *alpha* is a ``float``.\n\n If ``True``, returned alpha values are bi-level (``0`` or ``255``), based\n on the given alpha threshold.\n Also, the image is blended with the active terminal's BG color (or black,\n if undetermined) while leaving the alpha intact.\n\n frame: If ``True``, implies *img* is being used by :py:class`ImageIterator`,\n hence, *img* is not closed.\n\n The returned image is appropriately converted, resized and composited\n (if need be).\n\n The pixel data are the last two items of the returned tuple ``(rgb, a)``, where:\n * ``rgb`` is a list of ``(r, g, b)`` tuples containing the colour channels of\n the image's pixels in a flattened row-major order where ``r``, ``g``, ``b``\n are integers in the range [0, 255].\n * ``a`` is a list of integers in the range [0, 255] representing the alpha\n channel of the image's pixels in a flattened row-major order.\n \"\"\"\n\n def convert_resize_img(mode: str):\n nonlocal img\n\n if img.mode != mode:\n prev_img = img\n try:\n img = img.convert(mode)\n # Possible for images in some modes e.g \"La\"\n except Exception as e:\n raise RenderError(\"Unable to convert image\") from e\n finally:\n if frame_img is not prev_img:\n self._close_image(prev_img)\n\n if img.size != size:\n prev_img = img\n try:\n img = img.resize(size, Image.Resampling.BOX)\n # Highly unlikely since render size can never be zero\n except Exception as e:\n raise RenderError(\"Unable to resize image\") from e\n finally:\n if frame_img is not prev_img:\n self._close_image(prev_img)\n\n frame_img = img if frame else None\n if self._is_animated:\n img.seek(self._seek_position)\n if not size:\n size = self._get_render_size()\n\n if alpha is None or img.mode in {\"1\", \"L\", \"RGB\", \"HSV\", \"CMYK\"}:\n convert_resize_img(\"RGB\")\n if pixel_data:\n rgb = list(img.getdata())\n a = [255] * mul(*size)\n else:\n convert_resize_img(\"RGBA\")\n if isinstance(alpha, str):\n if alpha == \"#\":\n alpha = get_fg_bg_colors(hex=True)[1] or \"#000000\"\n bg = Image.new(\"RGBA\", img.size, alpha)\n bg.alpha_composite(img)\n if frame_img is not img:\n self._close_image(img)\n img = bg.convert(\"RGB\")\n if pixel_data:\n a = [255] * mul(*size)\n else:\n if pixel_data:\n a = list(img.getdata(3))\n if round_alpha:\n alpha = round(alpha * 255)\n a = [0 if val < alpha else 255 for val in a]\n if round_alpha:\n bg = Image.new(\n \"RGBA\", img.size, get_fg_bg_colors(hex=True)[1] or \"#000000\"\n )\n bg.alpha_composite(img)\n bg.putalpha(img.getchannel(\"A\"))\n if frame_img is not img:\n self._close_image(img)\n img = bg\n\n if pixel_data:\n rgb = list((img if img.mode == \"RGB\" else img.convert(\"RGB\")).getdata())\n\n return (img, *(pixel_data and (rgb, a) or (None, None)))\n\n @abstractmethod\n def _get_render_size(self) -> Tuple[int, int]:\n \"\"\"Returns the size (in pixels) required to render the image.\"\"\"\n raise NotImplementedError\n\n @classmethod\n def _get_style_format_spec(\n cls, spec: str, original: str\n ) -> Tuple[str, List[Union[None, str, Tuple[Optional[str]]]]]:\n \"\"\"Parses a style-specific format specifier.\n\n See :py:meth:`_check_format_spec`.\n\n Returns:\n The *parent* portion and a list of matches for the respective fields of the\n *current* portion of the spec.\n\n * Any absent field of *current* is ``None``.\n * For a field containing groups, the match, if present, is a tuple\n containing the full match followed by the matches for each group.\n * All matches are in the same order as the fields (including their groups).\n\n Raises:\n term_image.exceptions.StyleError: The *invalid* portion exists.\n\n NOTE:\n Please avoid common fields in the format specs of parent and child classes\n (i.e fields that can match the same portion of a given string) as they\n result in ambiguities.\n \"\"\"\n patterns = iter(cls._FORMAT_SPEC)\n fields = []\n for pattern in patterns:\n match = pattern.search(spec)\n if match:\n fields.append(\n (match.group(), *match.groups())\n if pattern.groups\n else match.group()\n )\n start = match.start()\n end = match.end()\n break\n else:\n fields.append(\n (None,) * (pattern.groups + 1) if pattern.groups else None\n )\n else:\n start = end = len(spec)\n\n for pattern in patterns:\n match = pattern.match(spec, pos=end)\n if match:\n fields.append(\n (match.group(), *match.groups())\n if pattern.groups\n else match.group()\n )\n end = match.end()\n else:\n fields.append(\n (None,) * (pattern.groups + 1) if pattern.groups else None\n )\n\n parent, invalid = spec[:start], spec[end:]\n if invalid:\n raise StyleError(\n f\"Invalid style-specific format specifier {original!r} \"\n f\"for {cls.__name__!r}, detected at {invalid!r}\"\n )\n\n return parent, fields\n\n @staticmethod\n def _handle_interrupted_draw():\n \"\"\"Performs any necessary actions when image drawing is interrupted.\"\"\"\n\n @staticmethod\n @abstractmethod\n def _pixels_cols(\n *, pixels: Optional[int] = None, cols: Optional[int] = None\n ) -> int:\n \"\"\"Returns the number of pixels represented by a given number of columns\n or vice-versa.\n \"\"\"\n raise NotImplementedError\n\n @staticmethod\n @abstractmethod\n def _pixels_lines(\n *, pixels: Optional[int] = None, lines: Optional[int] = None\n ) -> int:\n \"\"\"Returns the number of pixels represented by a given number of lines\n or vice-versa.\n \"\"\"\n raise NotImplementedError\n\n @abstractmethod\n def _render_image(\n self,\n img: PIL.Image.Image,\n alpha: Union[None, float, str],\n *,\n frame: bool = False, # For `ImageIterator`\n ) -> str:\n \"\"\"Converts an image into a string which reproduces the image when printed\n to the terminal.\n\n NOTE:\n This method is not meant to be used directly, use it via `_renderer()`\n instead.\n \"\"\"\n raise NotImplementedError\n\n def _renderer(\n self,\n renderer: FunctionType,\n *args: Any,\n scroll: bool = False,\n check_size: bool = False,\n animated: bool = False,\n **kwargs,\n ) -> Any:\n \"\"\"Performs common render preparations and a rendering operation.\n\n Args:\n renderer: The function to perform the specific rendering operation for the\n caller of this method, ``_renderer()``.\n\n This function must accept at least one positional argument, the\n :py:class:`PIL.Image.Image` instance corresponding to the source.\n\n args: Positional arguments to pass on to *renderer*, after the\n :py:class:`PIL.Image.Image` instance.\n scroll: See *scroll* in :py:meth:`draw`.\n check_size: See *check_size* in :py:meth:`draw`.\n animated: If ``True``, *scroll* and *check_size* are ignored and the size\n is validated.\n kwargs: Keyword arguments to pass on to *renderer*.\n\n Returns:\n The return value of *renderer*.\n\n Raises:\n term_image.exceptions.InvalidSizeError: *check_size* or *animated* is\n ``True`` and the image's :term:`rendered size` can not fit into the\n :term:`terminal size`.\n term_image.exceptions.TermImageError: The image has been finalized.\n \"\"\"\n _size = self._size\n try:\n if isinstance(_size, Size):\n self.set_size(_size)\n elif check_size or animated:\n terminal_size = get_terminal_size()\n if any(\n map(\n gt,\n # The compared height will be 0 if *scroll* is `True`.\n # So, the height comparison will always be `False`\n # since the terminal height should never be < 0.\n map(mul, self.rendered_size, (1, not scroll)),\n terminal_size,\n )\n ):\n raise InvalidSizeError(\n \"The \"\n + (\"animation\" if animated else \"image\")\n + \" cannot fit into the terminal size\"\n )\n\n # Reaching here means it's either valid or *scroll* is `True`.\n if animated and self.rendered_height > terminal_size.lines:\n raise InvalidSizeError(\n \"The rendered height is greater than the terminal height for \"\n \"an animation\"\n )\n\n return renderer(self._get_image(), *args, **kwargs)\n\n finally:\n if isinstance(_size, Size):\n self.size = _size\n\n def _valid_size(\n self,\n width: Union[int, Size, None] = None,\n height: Union[int, Size, None] = None,\n frame_size: Tuple[int, int] = (0, -2),\n ) -> Tuple[int, int]:\n \"\"\"Returns an image size tuple.\n\n See :py:meth:`set_size` for the description of the parameters.\n \"\"\"\n ori_width, ori_height = self._original_size\n columns, lines = map(\n lambda frame_dim, terminal_dim: (\n frame_dim if frame_dim > 0 else max(terminal_dim + frame_dim, 1)\n ),\n frame_size,\n get_terminal_size(),\n )\n frame_width = self._pixels_cols(cols=columns)\n frame_height = self._pixels_lines(lines=lines)\n\n # As for cell ratio...\n #\n # Take for example, pixel ratio = 2.0\n # (i.e cell ratio = 1.0; square character cells).\n # To adjust the image to the proper scale, we either reduce the\n # width (i.e divide by 2.0) or increase the height (i.e multiply by 2.0).\n #\n # On the other hand, if the pixel ratio = 0.5\n # (i.e cell ratio = 0.25; vertically oblong character cells).\n # To adjust the image to the proper scale, we either increase the width\n # (i.e divide by the 0.5) or reduce the height (i.e multiply by the 0.5).\n #\n # Therefore, for the height, we always multiply by the pixel ratio\n # and for the width, we always divide by the pixel ratio.\n # The non-constraining axis is always the one directly adjusted.\n\n if all(not isinstance(x, int) for x in (width, height)):\n if Size.AUTO in (width, height):\n width = height = (\n Size.FIT\n if (\n ori_width > frame_width\n or round(ori_height * self._pixel_ratio) > frame_height\n )\n else Size.ORIGINAL\n )\n elif Size.FIT_TO_WIDTH in (width, height):\n return (\n self._pixels_cols(pixels=frame_width) or 1,\n self._pixels_lines(\n pixels=round(\n self._width_height_px(w=frame_width) * self._pixel_ratio\n )\n )\n or 1,\n )\n\n if Size.ORIGINAL in (width, height):\n return (\n self._pixels_cols(pixels=ori_width) or 1,\n self._pixels_lines(pixels=round(ori_height * self._pixel_ratio))\n or 1,\n )\n\n # The smaller fraction will fit on both axis.\n # Hence, the axis with the smaller ratio is the constraining axis.\n # Constraining by the axis with the larger ratio will cause the image\n # to not fit into the axis with the smaller ratio.\n width_ratio = frame_width / ori_width\n height_ratio = frame_height / ori_height\n smaller_ratio = min(width_ratio, height_ratio)\n\n # Set the dimension on the constraining axis to exactly its corresponding\n # frame dimension and the dimension on the other axis to the same ratio of\n # its corresponding original image dimension\n _width_px = ori_width * smaller_ratio\n _height_px = ori_height * smaller_ratio\n\n # The cell ratio should directly affect the non-constraining axis since the\n # constraining axis is already fully occupied at this point\n if height_ratio > width_ratio:\n _height_px = _height_px * self._pixel_ratio\n # If height becomes greater than the max, reduce it to the max\n height_px = min(_height_px, frame_height)\n # Calculate the corresponding width\n width_px = round((height_px / _height_px) * _width_px)\n # Round the height\n height_px = round(height_px)\n else:\n _width_px = _width_px / self._pixel_ratio\n # If width becomes greater than the max, reduce it to the max\n width_px = min(_width_px, frame_width)\n # Calculate the corresponding height\n height_px = round((width_px / _width_px) * _height_px)\n # Round the width\n width_px = round(width_px)\n return (\n self._pixels_cols(pixels=width_px) or 1,\n self._pixels_lines(pixels=height_px) or 1,\n )\n elif width is None:\n width_px = round(\n self._width_height_px(h=self._pixels_lines(lines=height))\n / self._pixel_ratio\n )\n width = self._pixels_cols(pixels=width_px)\n elif height is None:\n height_px = round(\n self._width_height_px(w=self._pixels_cols(cols=width))\n * self._pixel_ratio\n )\n height = self._pixels_lines(pixels=height_px)\n\n return (width or 1, height or 1)\n\n def _width_height_px(\n self, *, w: Optional[int] = None, h: Optional[int] = None\n ) -> float:\n \"\"\"Converts the given width (in pixels) to the **unrounded** proportional height\n (in pixels) OR vice-versa.\n \"\"\"\n ori_width, ori_height = self._original_size\n return (\n (w / ori_width) * ori_height\n if w is not None\n else (h / ori_height) * ori_width\n )\n\n\n# Source: src/term_image/image/__init__.py\ndef AutoImage(\n image: PIL.Image.Image,\n *,\n width: Optional[int] = None,\n height: Optional[int] = None,\n) -> BaseImage:\n \"\"\"Creates an image instance from a PIL image instance.\n\n Returns:\n An instance of the automatically selected image render style (as returned by\n :py:func:`auto_image_class`).\n\n Same arguments and raised exceptions as the :py:class:`BaseImage` class constructor.\n \"\"\"\n return auto_image_class()(image, width=width, height=height)", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 61583}, "tests/renderable/test_renderable.py::1014": {"resolved_imports": ["src/term_image/_ctlseqs.py", "src/term_image/geometry.py", "src/term_image/padding.py", "src/term_image/renderable/_enum.py", "src/term_image/renderable/_exceptions.py", "src/term_image/renderable/_renderable.py", "src/term_image/renderable/_types.py"], "used_names": ["AlignedPadding", "RenderArgs", "sys"], "enclosing_function": "test_default", "extracted_code": "# Source: src/term_image/padding.py\nclass AlignedPadding(Padding):\n \"\"\"Aligned :term:`render output` padding.\n\n Args:\n width: Minimum :term:`render width`.\n height: Minimum :term:`render height`.\n h_align: Horizontal alignment.\n v_align: Vertical alignment.\n\n If *width* or *height* is:\n\n * positive, it is **absolute** and used as-is.\n * non-positive, it is **relative** to the corresponding terminal dimension\n (**at the point of resolution**) and equivalent to the absolute dimension\n ``max(terminal_dimension + relative_dimension, 1)``.\n\n The *padded render dimension* (i.e the dimension of a :term:`render output` after\n it's padded) on each axis is given by::\n\n padded_dimension = max(render_dimension, absolute_minimum_dimension)\n\n In words... If the **absolute** *minimum render dimension* on an axis is less than\n or equal to the corresponding *render dimension*, there is no padding on that axis\n and the *padded render dimension* on that axis is equal to the *render dimension*.\n Otherwise, the render output will be padded along that axis and the *padded render\n dimension* on that axis is equal to the *minimum render dimension*.\n\n The amount of padding to each side depends on the alignment, defined by *h_align*\n and *v_align*.\n\n IMPORTANT:\n :py:class:`RelativePaddingDimensionError` is raised if any padding-related\n computation/operation (basically, calling any method other than\n :py:meth:`resolve`) is performed on an instance with **relative** *minimum\n render dimension(s)* i.e if :py:attr:`relative` is ``True``.\n\n NOTE:\n Any interface receiving an instance with **relative** dimension(s) should\n typically resolve it/them upon reception.\n\n TIP:\n * Instances are immutable and hashable.\n * Instances with equal fields compare equal.\n \"\"\"\n\n # Class Attributes =========================================================\n\n __slots__ = (\"width\", \"height\", \"h_align\", \"v_align\", \"relative\")\n\n # Instance Attributes ======================================================\n\n width: int\n \"\"\"Minimum :term:`render width`\"\"\"\n\n height: int\n \"\"\"Minimum :term:`render height`\"\"\"\n\n h_align: HAlign\n \"\"\"Horizontal alignment\"\"\"\n\n v_align: VAlign\n \"\"\"Vertical alignment\"\"\"\n\n fill: str\n\n relative: bool\n \"\"\"``True`` if either or both *minimum render dimension(s)* is/are relative i.e\n non-positive. Otherwise, ``False``.\n \"\"\"\n\n # Special Methods ==========================================================\n\n def __init__(\n self,\n width: int,\n height: int,\n h_align: HAlign = HAlign.CENTER,\n v_align: VAlign = VAlign.MIDDLE,\n fill: str = \" \",\n ):\n super().__init__(fill)\n\n _setattr = super().__setattr__\n _setattr(\"width\", width)\n _setattr(\"height\", height)\n _setattr(\"h_align\", h_align)\n _setattr(\"v_align\", v_align)\n _setattr(\"relative\", not width > 0 < height)\n\n def __repr__(self) -> str:\n return \"{}(width={}, height={}, h_align={}, v_align={}, fill={!r})\".format(\n type(self).__name__,\n self.width,\n self.height,\n self.h_align.name,\n self.v_align.name,\n self.fill,\n )\n\n # Properties ===============================================================\n\n @property\n def size(self) -> RawSize:\n \"\"\"Minimum :term:`render size`\n\n GET:\n Returns the *minimum render dimensions*.\n \"\"\"\n return _RawSize(self.width, self.height)\n\n # Public Methods ===========================================================\n\n @override\n def get_padded_size(self, render_size: Size) -> Size:\n \"\"\"Computes an expected padded :term:`render size`.\n\n See :py:meth:`Padding.get_padded_size`.\n\n Raises:\n RelativePaddingDimensionError: Relative *minimum render dimension(s)*.\n \"\"\"\n if self.relative:\n raise RelativePaddingDimensionError(\"Relative minimum render dimension(s)\")\n\n return _Size(max(self.width, render_size[0]), max(self.height, render_size[1]))\n\n def resolve(self, terminal_size: os.terminal_size) -> AlignedPadding:\n \"\"\"Resolves **relative** *minimum render dimensions*.\n\n Args:\n terminal_size: The terminal size against which to resolve relative\n dimensions.\n\n Returns:\n An instance with equivalent **absolute** dimensions.\n \"\"\"\n if not self.relative:\n return self\n\n width, height, *args, _ = astuple(self)\n terminal_width, terminal_height = terminal_size\n if width <= 0:\n width = max(terminal_width + width, 1)\n if height <= 0:\n height = max(terminal_height + height, 1)\n\n return type(self)(width, height, *args)\n\n # Extension methods ========================================================\n\n @override\n def _get_exact_dimensions_(self, render_size: Size) -> tuple[int, int, int, int]:\n if self.relative:\n raise RelativePaddingDimensionError(\"Relative minimum render dimension(s)\")\n\n width, height, h_align, v_align = astuple(self)[:4]\n render_width, render_height = render_size\n\n if width > render_width:\n padding_width = width - render_width\n numerator, denominator = _ALIGN_RATIOS[h_align]\n left = padding_width * numerator // denominator\n right = padding_width - left\n else:\n left = right = 0\n\n if height > render_height:\n padding_height = height - render_height\n numerator, denominator = _ALIGN_RATIOS[v_align]\n top = padding_height * numerator // denominator\n bottom = padding_height - top\n else:\n top = bottom = 0\n\n return left, top, right, bottom\n\n\n# Source: src/term_image/renderable/_types.py\nclass RenderArgs(RenderArgsData):\n \"\"\"RenderArgs(render_cls, /, *namespaces)\n RenderArgs(render_cls, init_render_args, /, *namespaces)\n\n Render arguments.\n\n Args:\n render_cls: A :term:`render class`.\n init_render_args (RenderArgs | None): A set of render arguments.\n If not ``None``,\n\n * it must be compatible [#ra-com]_ with *render_cls*,\n * it'll be used to initialize the render arguments.\n\n namespaces: Render argument namespaces compatible [#an-com]_ with *render_cls*.\n\n .. note:: If multiple namespaces associated with the same :term:`render\n class` are given, the last of them takes precedence.\n\n Raises:\n IncompatibleRenderArgsError: *init_render_args* is incompatible [#ra-com]_ with\n *render_cls*.\n IncompatibleArgsNamespaceError: Incompatible [#an-com]_ render argument\n namespace.\n\n A set of render arguments (an instance of this class) is basically a container of\n render argument namespaces (instances of\n :py:class:`~term_image.renderable.ArgsNamespace`); one for\n each :term:`render class`, which has render arguments, in the Method Resolution\n Order of its associated [#ra-ass]_ render class.\n\n The namespace for each render class is derived from the following sources, in\n [descending] order of precedence:\n\n * *namespaces*\n * *init_render_args*\n * default render argument namespaces\n\n NOTE:\n Instances are immutable but updated copies can be created via :py:meth:`update`.\n\n .. seealso::\n\n :py:attr:`~term_image.renderable.Renderable.Args`\n Render class-specific render arguments.\n\n .. Completed in /docs/source/api/renderable.rst\n \"\"\"\n\n # Class Attributes =========================================================\n\n __slots__ = ()\n\n _interned: ClassVar[dict[type[Renderable], Self]] = {}\n _namespaces: MappingProxyType[type[Renderable], ArgsNamespace]\n\n # Instance Attributes ======================================================\n\n render_cls: type[Renderable]\n \"\"\"The associated :term:`render class`\"\"\"\n\n # Special Methods ==========================================================\n\n def __new__(\n cls,\n render_cls: type[Renderable],\n init_or_namespace: RenderArgs | ArgsNamespace | None = None,\n *namespaces: ArgsNamespace,\n ) -> Self:\n if init_or_namespace is None:\n init_render_args = None\n elif isinstance(init_or_namespace, RenderArgs):\n init_render_args = init_or_namespace\n else:\n init_render_args = None\n namespaces = (init_or_namespace, *namespaces)\n\n if init_render_args and not issubclass(render_cls, init_render_args.render_cls):\n raise IncompatibleRenderArgsError(\n f\"'init_render_args' (associated with \"\n f\"{init_render_args.render_cls.__name__!r}) is incompatible with \"\n f\"{render_cls.__name__!r} \"\n )\n\n if not namespaces:\n # has default namespaces only\n if (\n not init_render_args\n or init_render_args is BASE_RENDER_ARGS\n or cls._interned.get(init_render_args.render_cls) is init_render_args\n ):\n try:\n return cls._interned[render_cls]\n except KeyError:\n pass\n\n if (\n init_render_args\n and type(init_render_args) is cls\n and init_render_args.render_cls is render_cls\n ):\n return init_render_args\n\n return super().__new__(cls)\n\n def __init__(\n self,\n render_cls: type[Renderable],\n init_or_namespace: RenderArgs | ArgsNamespace | None = None,\n *namespaces: ArgsNamespace,\n ) -> None:\n if init_or_namespace is None:\n init_render_args = None\n elif isinstance(init_or_namespace, RenderArgs):\n init_render_args = init_or_namespace\n else:\n init_render_args = None\n namespaces = (init_or_namespace, *namespaces)\n\n # has default namespaces only\n if not namespaces and (\n not init_render_args\n or init_render_args is BASE_RENDER_ARGS\n or (\n type(self)._interned.get(init_render_args.render_cls)\n is init_render_args\n )\n ):\n if render_cls in type(self)._interned: # has been initialized\n return\n intern = True\n else:\n intern = False\n\n if init_render_args is self:\n return\n\n namespaces_dict = render_cls._ALL_DEFAULT_ARGS.copy()\n\n # if `init_render_args` is non-default\n if init_render_args and BASE_RENDER_ARGS is not init_render_args is not (\n type(self)._interned.get(init_render_args.render_cls)\n ):\n namespaces_dict.update(init_render_args._namespaces)\n\n for index, namespace in enumerate(namespaces):\n if namespace._RENDER_CLS not in namespaces_dict:\n raise IncompatibleArgsNamespaceError(\n f\"'namespaces[{index}]' (associated with \"\n f\"{namespace._RENDER_CLS.__name__!r}) is incompatible with \"\n f\"{render_cls.__name__!r} \"\n )\n namespaces_dict[namespace._RENDER_CLS] = namespace\n\n super().__init__(render_cls, namespaces_dict)\n\n if intern:\n type(self)._interned[render_cls] = self\n\n def __init_subclass__(cls, **kwargs: Any) -> None:\n cls._interned = {}\n super().__init_subclass__(**kwargs)\n\n def __contains__(self, namespace: ArgsNamespace) -> bool:\n \"\"\"Checks if a render argument namespace is contained in this set of render\n arguments.\n\n Args:\n namespace: A render argument namespace.\n\n Returns:\n ``True`` if the given namespace is equal to any of the namespaces\n contained in this set of render arguments. Otherwise, ``False``.\n \"\"\"\n return None is not self._namespaces.get(namespace._RENDER_CLS) == namespace\n\n def __eq__(self, other: object) -> bool:\n \"\"\"Compares this set of render arguments with another.\n\n Args:\n other: Another set of render arguments.\n\n Returns:\n ``True`` if both are associated with the same :term:`render class`\n and have equal argument values. Otherwise, ``False``.\n \"\"\"\n if isinstance(other, RenderArgs):\n return (\n self is other\n or self.render_cls is other.render_cls\n and self._namespaces == other._namespaces\n )\n\n return NotImplemented\n\n def __getitem__(self, render_cls: type[Renderable]) -> Any:\n \"\"\"Returns a constituent namespace.\n\n Args:\n render_cls: A :term:`render class` of which :py:attr:`render_cls` is a\n subclass (which may be :py:attr:`render_cls` itself) and which has\n render arguments.\n\n Returns:\n The constituent namespace associated with *render_cls*.\n\n Raises:\n TypeError: *render_cls* is not a render class.\n ValueError: :py:attr:`render_cls` is not a subclass of *render_cls*.\n NoArgsNamespaceError: *render_cls* has no render arguments.\n\n NOTE:\n The return type hint is :py:class:`~typing.Any` only for compatibility\n with static type checking, as this aspect of the interface seems too\n dynamic to be correctly expressed with the exisiting type system.\n\n Regardless, the return value is guaranteed to always be an instance\n of a render argument namespace class associated with *render_cls*.\n For instance, the following would always be valid for\n :py:class:`~term_image.renderable.Renderable`::\n\n renderable_args: RenderableArgs = render_args[Renderable]\n\n and similar idioms are encouraged to be used for other render classes.\n \"\"\"\n try:\n return self._namespaces[render_cls]\n except TypeError:\n raise arg_type_error(\"render_cls\", render_cls) from None\n except KeyError:\n if not isinstance(render_cls, RenderableMeta):\n raise arg_type_error(\"render_cls\", render_cls) from None\n\n if issubclass(self.render_cls, render_cls):\n raise NoArgsNamespaceError(\n f\"{render_cls.__name__!r} has no render arguments\"\n ) from None\n\n raise ValueError(\n f\"{self.render_cls.__name__!r} is not a subclass of \"\n f\"{render_cls.__name__!r}\"\n ) from None\n\n def __hash__(self) -> int:\n \"\"\"Computes the hash of the render arguments.\n\n Returns:\n The computed hash.\n\n IMPORTANT:\n Like tuples, an instance is hashable if and only if the constituent\n namespaces are hashable.\n \"\"\"\n # Namespaces are always in the same order, wrt their respective associated\n # render classes, for all instances associated with the same render class.\n return hash((self.render_cls, tuple(self._namespaces.values())))\n\n def __iter__(self) -> Iterator[ArgsNamespace]:\n \"\"\"Returns an iterator that yields the constituent namespaces.\n\n Returns:\n An iterator that yields the constituent namespaces.\n\n WARNING:\n The number and order of namespaces is guaranteed to be the same across all\n instances associated [#ra-ass]_ with the same :term:`render class` but\n beyond this, should not be relied upon as the details (such as the\n specific number or order) may change without notice.\n\n The order is an implementation detail of the Renderable API and the number\n should be considered alike with respect to the associated render class.\n \"\"\"\n return iter(self._namespaces.values())\n\n def __repr__(self) -> str:\n return \"\".join(\n (\n f\"{type(self).__name__}({self.render_cls.__name__}\",\n \", \" if self._namespaces else \"\",\n \", \".join(map(repr, self._namespaces.values())),\n \")\",\n )\n )\n\n # Public Methods ===========================================================\n\n def convert(self, render_cls: type[Renderable]) -> RenderArgs:\n \"\"\"Converts the set of render arguments to one for a related render class.\n\n Args:\n render_cls: A :term:`render class` of which :py:attr:`render_cls` is a\n parent or child (which may be :py:attr:`render_cls` itself).\n\n Returns:\n A set of render arguments associated [#ra-ass]_ with *render_cls* and\n initialized with all constituent namespaces (of this set of render\n arguments, *self*) that are compatible [#an-com]_ with *render_cls*.\n\n Raises:\n ValueError: *render_cls* is not a parent or child of :py:attr:`render_cls`.\n \"\"\"\n if render_cls is self.render_cls:\n return self\n\n if issubclass(render_cls, self.render_cls):\n return RenderArgs(render_cls, self)\n\n if issubclass(self.render_cls, render_cls):\n render_cls_args_mro = render_cls._ALL_DEFAULT_ARGS\n return RenderArgs(\n render_cls,\n *[\n namespace\n for cls, namespace in self._namespaces.items()\n if cls in render_cls_args_mro\n ],\n )\n\n raise ValueError(\n f\"{render_cls.__name__!r} is not a parent or child of \"\n f\"{self.render_cls.__name__!r}\"\n )\n\n @overload\n def update(\n self,\n namespace: ArgsNamespace,\n /,\n *namespaces: ArgsNamespace,\n ) -> RenderArgs: ...\n\n @overload\n def update(\n self,\n render_cls: type[Renderable],\n /,\n **fields: Any,\n ) -> RenderArgs: ...\n\n def update(\n self,\n render_cls_or_namespace: type[Renderable] | ArgsNamespace,\n /,\n *namespaces: ArgsNamespace,\n **fields: Any,\n ) -> RenderArgs:\n \"\"\"update(namespace, /, *namespaces) -> RenderArgs\n update(render_cls, /, **fields) -> RenderArgs\n\n Replaces or updates render argument namespaces.\n\n Args:\n namespace (ArgsNamespace): Prepended to *namespaces*.\n namespaces: Render argument namespaces compatible [#an-com]_ with\n :py:attr:`render_cls`.\n\n .. note:: If multiple namespaces associated with the same :term:`render\n class` are given, the last of them takes precedence.\n\n render_cls (type[Renderable]): A :term:`render class` of which\n :py:attr:`render_cls` is a subclass (which may be :py:attr:`render_cls`\n itself) and which has render arguments.\n fields: Render argument fields.\n\n The keywords must be names of render argument fields for *render_cls*.\n\n Returns:\n For the **first** form, an instance with the namespaces for the respective\n associated :term:`render classes` of the given namespaces replaced.\n\n For the **second** form, an instance with the given render argument fields\n for *render_cls* updated, if any.\n\n Raises:\n TypeError: The arguments given do not conform to any of the expected forms.\n\n Propagates exceptions raised by:\n\n * the class constructor, for the **first** form.\n * :py:meth:`__getitem__` and :py:meth:`ArgsNamespace.update()\n `, for the **second** form.\n \"\"\"\n if isinstance(render_cls_or_namespace, RenderableMeta):\n if namespaces:\n raise TypeError(\n \"No other positional argument is expected when the first argument \"\n \"is a render class\"\n )\n render_cls = render_cls_or_namespace\n else:\n if fields:\n raise TypeError(\n \"No keyword argument is expected when the first argument is \"\n \"a render argument namespace\"\n )\n render_cls = None\n namespaces = (render_cls_or_namespace, *namespaces)\n\n return RenderArgs(\n self.render_cls,\n self,\n *((self[render_cls].update(**fields),) if render_cls else namespaces),\n )", "n_imports_parsed": 14, "n_files_resolved": 7, "n_chars_extracted": 20781}, "tests/test_color.py::48": {"resolved_imports": ["src/term_image/color.py"], "used_names": ["Color"], "enclosing_function": "test_is_tuple", "extracted_code": "# Source: src/term_image/color.py\nclass Color(_DummyColor):\n \"\"\"A color.\n\n Args:\n r: The red channel.\n g: The green channel.\n b: The blue channel.\n a: The alpha channel (opacity).\n\n Raises:\n ValueError: The value of a channel is not within the valid range.\n\n NOTE:\n The valid value range for all channels is 0 to 255, both inclusive.\n\n TIP:\n This class is a :py:class:`~typing.NamedTuple` of four fields.\n\n WARNING:\n In the case of multiple inheritance i.e if subclassing this class along with\n other classes, this class should appear last (i.e to the far right) in the\n base class list.\n \"\"\"\n\n __slots__ = ()\n\n # Overrides these descriptors in order to speed up attribute resolution and to\n # simplify auto documentation.\n r: int = _DummyColor.r\n r.__doc__ = \"\"\"The red channel\"\"\"\n\n g: int = _DummyColor.g\n g.__doc__ = \"\"\"The green channel\"\"\"\n\n b: int = _DummyColor.b\n b.__doc__ = \"\"\"The blue channel\"\"\"\n\n a: int = _DummyColor.a\n a.__doc__ = \"\"\"The alpha channel (opacity)\"\"\"\n\n def __new__(cls, r: int, g: int, b: int, a: int = 255) -> Self:\n # Only the 8 LSb may be set for any value within the range [0, 255].\n # `x & ~255` unsets the 8 LSb. Hence, if the result is non-zero (i.e any\n # of the bits above the lowest 8 is set), it implies `x` is out of range.\n #\n # Actually benchmarked *this* against the \"simpler\" logically-negated chained\n # comparison (i.e `0 <= x <= 255`) and *this* was significantly faster for all\n # cases i.e within, on the boundaries, and outside (on both sides).\n if (r | g | b | a) & ~255: # First test to see if *any* is out of range\n if r & ~255:\n raise arg_value_error_range(\"r\", r)\n if g & ~255:\n raise arg_value_error_range(\"g\", g)\n if b & ~255:\n raise arg_value_error_range(\"b\", b)\n # There's no point checking since at least one is out of range\n raise arg_value_error_range(\"a\", a)\n\n # Using `tuple` directly instead of `super()` for performance\n return tuple.__new__(cls, (r, g, b, a))\n\n @property\n def hex(self) -> str:\n \"\"\"Converts the color to its RGBA hexadecimal representation.\n\n Returns:\n The RGBA hex color string, starting with the ``#`` character i.e\n ``#rrggbbaa``.\n\n Each channel is represented by two **lowercase** hex digits ranging from\n ``00`` to ``ff``.\n \"\"\"\n return \"#%02x%02x%02x%02x\" % self\n\n @property\n def rgb(self) -> tuple[int, int, int]:\n \"\"\"Extracts the R, G and B channels of the color.\n\n Returns:\n A 3-tuple containing the red, green and blue channel values.\n \"\"\"\n return self[:3]\n\n @property\n def rgb_hex(self) -> str:\n \"\"\"Converts the color to its RGB hexadecimal representation.\n\n Returns:\n The RGB hex color string, starting with the ``#`` character i.e ``#rrggbb``.\n\n Each channel is represented by two **lowercase** hex digits ranging from\n ``00`` to ``ff``.\n \"\"\"\n return \"#%02x%02x%02x\" % self[:3]\n\n @classmethod\n def from_hex(cls, color: str) -> Self:\n \"\"\"Creates a new instance from a hexadecimal color string.\n\n Args:\n color: A **case-insensitive** RGB or RGBA hex color string, **optionally**\n starting with the ``#`` (pound) character i.e ``[#]rrggbb[aa]``.\n\n Returns:\n A new instance representing the given hex color string.\n\n Raises:\n ValueError: Invalid hex color string.\n\n NOTE:\n For an RGB hex color string, the value of A (the alpha channel) is\n taken to be 255.\n \"\"\"\n if not (match := _RGBA_HEX_RE.fullmatch(color)):\n raise ValueError(f\"Invalid hex color string (got: {color!r})\")\n\n return tuple.__new__(cls, [int(x, 16) for x in match.groups(\"ff\")])\n\n @classmethod\n def _new(cls, r: int, g: int, b: int, a: int = 255) -> Self:\n \"\"\"Alternate constructor for internal use only.\"\"\"\n return tuple.__new__(cls, (r, g, b, a))", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 4255}, "tests/widget/urwid/test_main.py::112": {"resolved_imports": ["src/term_image/__init__.py", "src/term_image/_ctlseqs.py", "src/term_image/exceptions.py", "src/term_image/image/block.py", "src/term_image/image/common.py", "src/term_image/image/iterm2.py", "src/term_image/image/kitty.py", "src/term_image/widget/_urwid.py"], "used_names": ["_ALPHA_THRESHOLD"], "enclosing_function": "_test_output", "extracted_code": "", "n_imports_parsed": 10, "n_files_resolved": 8, "n_chars_extracted": 0}, "tests/test_image/test_kitty.py::206": {"resolved_imports": ["src/term_image/__init__.py", "src/term_image/_ctlseqs.py", "src/term_image/exceptions.py", "src/term_image/image/__init__.py", "src/term_image/image/kitty.py"], "used_names": ["decompress", "io", "standard_b64decode"], "enclosing_function": "decode_image", "extracted_code": "", "n_imports_parsed": 12, "n_files_resolved": 5, "n_chars_extracted": 0}, "tests/renderable/test_renderable.py::254": {"resolved_imports": ["src/term_image/_ctlseqs.py", "src/term_image/geometry.py", "src/term_image/padding.py", "src/term_image/renderable/_enum.py", "src/term_image/renderable/_exceptions.py", "src/term_image/renderable/_renderable.py", "src/term_image/renderable/_types.py"], "used_names": ["MappingProxyType", "Renderable"], "enclosing_function": "test_base", "extracted_code": "# Source: src/term_image/renderable/_renderable.py\nclass Renderable(metaclass=RenderableMeta, _base=True):\n \"\"\"A renderable.\n\n Args:\n frame_count: Number of frames. If it's a\n\n * positive integer, the number of frames is as given.\n * :py:class:`~term_image.renderable.FrameCount` enum member, see the\n member's description.\n\n If equal to 1 (one), the renderable is non-animated.\n Otherwise, it is animated.\n\n frame_duration: The duration of a frame. If it's a\n\n * positive integer, it implies a static duration (in **milliseconds**)\n i.e the same duration applies to every frame.\n * :py:class:`~term_image.renderable.FrameDuration` enum member, see the\n member's description.\n\n This argument is ignored if *frame_count* equals 1 (one)\n i.e the renderable is non-animated.\n\n Raises:\n ValueError: An argument has an invalid value.\n\n ATTENTION:\n This is an abstract base class. Hence, only **concrete** subclasses can be\n instantiated.\n\n .. seealso::\n\n :ref:`renderable-ext-api`\n :py:class:`Renderable`\\\\ 's Extension API\n \"\"\"\n\n # Class Attributes =========================================================\n\n # Initialized by `RenderableMeta` and may be updated by `ArgsNamespaceMeta`\n Args: ClassVar[type[ArgsNamespace] | None]\n \"\"\":term:`Render class`\\\\ -specific render arguments.\n\n This is either:\n\n - a render argument namespace class (subclass of :py:class:`ArgsNamespace`)\n associated [#an-ass]_ with the render class, or\n - :py:data:`None`, if the render class has no render arguments.\n\n If this is a class, an instance of it (or a subclass thereof) is contained within\n any :py:class:`RenderArgs` instance associated [#ra-ass]_ with the render class or\n any of its subclasses. Also, an instance of this class (or a subclass of it) is\n returned by :py:meth:`render_args[render_cls]\n `; where *render_args* is\n an instance of :py:class:`~term_image.renderable.RenderArgs` as previously\n described and *render_cls* is the render class with which this namespace class\n is associated [#an-ass]_.\n\n .. collapse:: Example\n\n >>> class Foo(Renderable):\n ... pass\n ...\n ... class FooArgs(ArgsNamespace, render_cls=Foo):\n ... foo: str | None = None\n ...\n >>> Foo.Args is FooArgs\n True\n >>>\n >>> # default\n >>> foo_args = Foo.Args()\n >>> foo_args\n FooArgs(foo=None)\n >>> foo_args.foo is None\n True\n >>>\n >>> render_args = RenderArgs(Foo)\n >>> render_args[Foo]\n FooArgs(foo=None)\n >>>\n >>> # non-default\n >>> foo_args = Foo.Args(\"FOO\")\n >>> foo_args\n FooArgs(foo='FOO')\n >>> foo_args.foo\n 'FOO'\n >>>\n >>> render_args = RenderArgs(Foo, foo_args.update(foo=\"bar\"))\n >>> render_args[Foo]\n FooArgs(foo='bar')\n\n On the other hand, if this is :py:data:`None`, it implies the render class has no\n render arguments.\n\n .. collapse:: Example\n\n >>> class Bar(Renderable):\n ... pass\n ...\n >>> Bar.Args is None\n True\n >>> render_args = RenderArgs(Bar)\n >>> render_args[Bar]\n Traceback (most recent call last):\n ...\n NoArgsNamespaceError: 'Bar' has no render arguments\n \"\"\"\n\n # Initialized by `RenderableMeta` and may be updated by `DataNamespaceMeta`\n _Data_: ClassVar[type[DataNamespace] | None]\n \"\"\":term:`Render class`\\\\ -specific render data.\n\n This is either:\n\n - a render data namespace class (subclass of :py:class:`DataNamespace`)\n associated [#dn-ass]_ with the render class, or\n - :py:data:`None`, if the render class has no render data.\n\n If this is a class, an instance of it (or a subclass thereof) is contained within\n any :py:class:`RenderData` instance associated [#rd-ass]_ with the render class or\n any of its subclasses. Also, an instance of this class (or a subclass of it) is\n returned by :py:meth:`render_data[render_cls]\n `; where *render_data* is\n an instance of :py:class:`~term_image.renderable.RenderData` as previously\n described and *render_cls* is the render class with which this namespace class\n is associated [#dn-ass]_.\n\n .. collapse:: Example\n\n >>> class Foo(Renderable):\n ... pass\n ...\n ... class _Data_(DataNamespace, render_cls=Foo):\n ... foo: str | None\n ...\n >>> Foo._Data_ is FooData\n True\n >>>\n >>> foo_data = Foo._Data_()\n >>> foo_data\n >\n >>> foo_data.foo\n Traceback (most recent call last):\n ...\n UninitializedDataFieldError: The render data field 'foo' of 'Foo' has not \\\nbeen initialized\n >>>\n >>> foo_data.foo = \"FOO\"\n >>> foo_data\n \n >>> foo_data.foo\n 'FOO'\n >>>\n >>> render_data = RenderData(Foo)\n >>> render_data[Foo]\n >\n >>>\n >>> render_data[Foo].foo = \"bar\"\n >>> render_data[Foo]\n \n\n On the other hand, if this is :py:data:`None`, it implies the render class has no\n render data.\n\n .. collapse:: Example\n\n >>> class Bar(Renderable):\n ... pass\n ...\n >>> Bar._Data_ is None\n True\n >>>\n >>> render_data = RenderData(Bar)\n >>> render_data[Bar]\n Traceback (most recent call last):\n ...\n NoDataNamespaceError: 'Bar' has no render data\n\n .. seealso::\n\n :py:class:`~term_image.renderable.RenderableData`\n Render data for :py:class:`~term_image.renderable.Renderable`.\n \"\"\"\n\n _EXPORTED_ATTRS_: ClassVar[tuple[str, ...]]\n \"\"\"Exported attributes.\n\n This specifies class attributes defined by the class (not a parent) on itself\n **but not** its subclasses which should be exported to definitions of the class\n in subprocesses.\n\n These attributes are typically assigned using ``__class__.*`` within methods.\n\n NOTE:\n * Defining this is optional.\n * The attributes are exported for a class if and only if they are defined\n on that class when starting a subprocess.\n * The attributes are exported only for subprocesses started via\n :py:class:`multiprocessing.Process`.\n\n TIP:\n This can be used to export \"private\" attributes of the class across\n subprocesses.\n \"\"\"\n\n _EXPORTED_DESCENDANT_ATTRS_: ClassVar[tuple[str, ...]]\n \"\"\"Exported :term:`descendant` attributes.\n\n This specifies class attributes defined by the class (not a parent) on itself\n **and** its subclasses (i.e :term:`descendant` attributes) which should be exported\n to definitions of the class and its subclasses in subprocesses.\n\n These attributes are typically assigned using ``cls.*`` within class methods.\n\n This extends the exported descendant attributes of parent classes i.e all\n exported descendant attributes of a class are also exported for its subclasses.\n\n NOTE:\n * Defining this is optional.\n * The attributes are exported for a class if and only if they are defined\n on that class when starting a subprocess.\n * The attributes are exported only for subprocesses started via\n :py:class:`multiprocessing.Process`.\n\n TIP:\n This can be used to export \"private\" :term:`descendant` attributes of the\n class across subprocesses.\n \"\"\"\n\n _ALL_DEFAULT_ARGS: ClassVar[MappingProxyType[type[Renderable], ArgsNamespace]]\n _RENDER_DATA_MRO: ClassVar[MappingProxyType[type[Renderable], type[DataNamespace]]]\n _ALL_EXPORTED_ATTRS: ClassVar[tuple[str, ...]]\n\n # Instance Attributes ======================================================\n\n animated: bool\n \"\"\"``True`` if the renderable is :term:`animated`. Otherwise, ``False``.\"\"\"\n\n _frame: int\n _frame_count: int | FrameCount\n _frame_duration: int | FrameDuration\n\n # Special Methods ==========================================================\n\n def __init__(\n self,\n frame_count: int | FrameCount,\n frame_duration: int | FrameDuration,\n ) -> None:\n if isinstance(frame_count, int) and frame_count < 1:\n raise arg_value_error_range(\"frame_count\", frame_count)\n\n if frame_count != 1:\n if isinstance(frame_duration, int) and frame_duration <= 0:\n raise arg_value_error_range(\"frame_duration\", frame_duration)\n self._frame_duration = frame_duration\n\n self.animated = frame_count != 1\n self._frame_count = frame_count\n self._frame = 0\n\n def __iter__(self) -> term_image.render.RenderIterator:\n \"\"\"Returns a render iterator.\n\n Returns:\n A render iterator (with frame caching disabled and all other optional\n arguments to :py:class:`~term_image.render.RenderIterator` being the\n default values).\n\n Raises:\n NonAnimatedRenderableError: The renderable is non-animated.\n\n :term:`Animated` renderables are iterable i.e they can be used with various\n means of iteration such as the ``for`` statement and iterable unpacking.\n \"\"\"\n from term_image.render import RenderIterator\n\n try:\n return RenderIterator(self, cache=False)\n except ValueError:\n raise NonAnimatedRenderableError(\n \"Non-animated renderables are not iterable\"\n ) from None\n\n def __repr__(self) -> str:\n return f\"<{type(self).__name__}: frame_count={self._frame_count}>\"\n\n def __str__(self) -> str:\n \"\"\":term:`Renders` the current frame with default arguments and no padding.\n\n Returns:\n The frame :term:`render output`.\n\n Raises:\n RenderError: An error occurred during :term:`rendering`.\n \"\"\"\n return self._init_render_(self._render_)[0].render_output\n\n # Properties ===============================================================\n\n @property\n def frame_count(self) -> int | Literal[FrameCount.INDEFINITE]:\n \"\"\"Frame count\n\n GET:\n Returns either\n\n * the number of frames the renderable has, or\n * :py:attr:`~term_image.renderable.FrameCount.INDEFINITE`.\n \"\"\"\n if self._frame_count is FrameCount.POSTPONED:\n self._frame_count = self._get_frame_count_()\n\n return self._frame_count\n\n @property\n def frame_duration(self) -> int | FrameDuration:\n \"\"\"Frame duration\n\n GET:\n Returns\n\n * a positive integer, a static duration (in **milliseconds**) i.e the\n same duration applies to every frame; or\n * :py:attr:`~term_image.renderable.FrameDuration.DYNAMIC`.\n\n SET:\n If the value is\n\n * a positive integer, it implies a static duration (in **milliseconds**)\n i.e the same duration applies to every frame.\n * :py:attr:`~term_image.renderable.FrameDuration.DYNAMIC`, see the\n enum member's description.\n\n Raises:\n NonAnimatedRenderableError: The renderable is non-animated.\n \"\"\"\n try:\n return self._frame_duration\n except AttributeError:\n if not self.animated:\n raise NonAnimatedRenderableError(\n \"Non-animated renderables have no frame duration\"\n ) from None\n raise\n\n @frame_duration.setter\n def frame_duration(self, duration: int | FrameDuration) -> None:\n if not self.animated:\n raise NonAnimatedRenderableError(\n \"Cannot set frame duration for a non-animated renderable\"\n )\n\n if isinstance(duration, int) and duration <= 0:\n raise arg_value_error_range(\"frame_duration\", duration)\n\n self._frame_duration = duration\n\n @property\n def render_size(self) -> geometry.Size:\n \"\"\":term:`Render size`\n\n GET:\n Returns the size of the renderable's :term:`render output`.\n \"\"\"\n return self._get_render_size_()\n\n # Public Methods ===========================================================\n\n def draw(\n self,\n render_args: RenderArgs | None = None,\n padding: Padding = AlignedPadding(0, -2),\n *,\n animate: bool = True,\n loops: int = -1,\n cache: bool | int = 100,\n check_size: bool = True,\n allow_scroll: bool = False,\n hide_cursor: bool = True,\n echo_input: bool = False,\n ) -> None:\n \"\"\"Draws the current frame or an animation to standard output.\n\n Args:\n render_args: Render arguments.\n padding: :term:`Render output` padding.\n animate: Whether to enable animation for :term:`animated` renderables.\n If disabled, only the current frame is drawn.\n loops: See :py:class:`~term_image.render.RenderIterator`\n (applies to **animations only**).\n cache: See :py:class:`~term_image.render.RenderIterator`.\n (applies to **animations only**).\n check_size: Whether to validate the padded :term:`render size` of\n **non-animations**.\n allow_scroll: Whether to validate the padded :term:`render height` of\n **non-animations**. Ignored if *check_size* is ``False``.\n hide_cursor: Whether to hide the cursor **while drawing**.\n echo_input: Whether to display input **while drawing** (applies on **Unix\n only**).\n\n .. note::\n * If disabled (default), input is not read/consumed, it's just not\n displayed.\n * If enabled, echoed input may affect cursor positioning and\n therefore, the output (especially for animations).\n\n Raises:\n RenderSizeOutofRangeError: The padded :term:`render size` can not fit into\n the :term:`terminal size`.\n IncompatibleRenderArgsError: Incompatible render arguments.\n RenderError: An error occurred during :term:`rendering`.\n\n If *check_size* is ``True`` (or it's an animation),\n\n * the padded :term:`render width` must not be greater than the\n :term:`terminal width`.\n * and *allow_scroll* is ``False`` (or it's an animation), the padded\n :term:`render height` must not be greater than the :term:`terminal height`.\n\n NOTE:\n * *hide_cursor* and *echo_input* apply if and only if the output stream\n is connected to a terminal.\n * For animations (i.e animated renderables with *animate* = ``True``),\n the padded :term:`render size` is always validated.\n * Animations with **definite** frame count, **by default**, are infinitely\n looped but can be terminated with :py:data:`~signal.SIGINT`\n (``CTRL + C``), **without** raising :py:class:`KeyboardInterrupt`.\n \"\"\"\n animation = self.animated and animate\n output = sys.stdout\n not_echo_input = OS_IS_UNIX and not echo_input and output.isatty()\n hide_cursor = hide_cursor and output.isatty()\n\n # Validate size and get render data and args\n render_data: RenderData\n real_render_args: RenderArgs\n (render_data, real_render_args), padding = self._init_render_(\n lambda *args: args,\n render_args,\n padding,\n iteration=animation,\n finalize=False,\n check_size=animation or check_size,\n allow_scroll=not animation and allow_scroll,\n )\n\n if not_echo_input:\n output_fd = output.fileno()\n old_attr = termios.tcgetattr(output_fd)\n new_attr = termios.tcgetattr(output_fd)\n new_attr[3] &= ~termios.ECHO\n try:\n if hide_cursor:\n output.write(HIDE_CURSOR)\n if not_echo_input:\n termios.tcsetattr(output_fd, termios.TCSAFLUSH, new_attr)\n\n if animation:\n self._animate_(\n render_data, real_render_args, padding, loops, cache, output\n )\n else:\n frame = self._render_(render_data, real_render_args)\n padded_size = padding.get_padded_size(frame.render_size)\n render = (\n frame.render_output\n if frame.render_size == padded_size\n else padding.pad(frame.render_output, frame.render_size)\n )\n try:\n output.write(render)\n output.flush()\n except KeyboardInterrupt:\n self._handle_interrupted_draw_(\n render_data, real_render_args, output\n )\n raise\n finally:\n output.write(\"\\n\")\n if hide_cursor:\n output.write(SHOW_CURSOR)\n output.flush()\n if not_echo_input:\n termios.tcsetattr(output_fd, termios.TCSANOW, old_attr)\n render_data.finalize()\n\n def render(\n self,\n render_args: RenderArgs | None = None,\n padding: Padding = NO_PADDING,\n ) -> Frame:\n \"\"\":term:`Renders` the current frame.\n\n Args:\n render_args: Render arguments.\n padding: :term:`Render output` padding.\n\n Returns:\n The rendered frame.\n\n Raises:\n IncompatibleRenderArgsError: Incompatible render arguments.\n RenderError: An error occurred during :term:`rendering`.\n \"\"\"\n frame, padding = self._init_render_(self._render_, render_args, padding)\n padded_size = padding.get_padded_size(frame.render_size)\n\n return (\n frame\n if frame.render_size == padded_size\n else Frame(\n frame.number,\n frame.duration,\n padded_size,\n padding.pad(frame.render_output, frame.render_size),\n )\n )\n\n def seek(self, offset: int, whence: Seek = Seek.START) -> int:\n \"\"\"Sets the current frame number.\n\n Args:\n offset: Frame offset (relative to *whence*).\n whence: Reference position for *offset*.\n\n Returns:\n The new current frame number.\n\n Raises:\n IndefiniteSeekError: The renderable has\n :py:attr:`~term_image.renderable.FrameCount.INDEFINITE` frame count.\n ValueError: *offset* is out of range.\n\n The value range for *offset* depends on *whence*:\n\n .. list-table::\n :align: left\n :header-rows: 1\n :widths: auto\n\n * - *whence*\n - Valid value range for *offset*\n\n * - :py:attr:`~term_image.renderable.Seek.START`\n - ``0`` <= *offset* < :py:attr:`frame_count`\n * - :py:attr:`~term_image.renderable.Seek.CURRENT`\n - -:py:meth:`tell` <= *offset* < :py:attr:`frame_count` - :py:meth:`tell`\n * - :py:attr:`~term_image.renderable.Seek.END`\n - -:py:attr:`frame_count` < *offset* <= ``0``\n \"\"\"\n frame_count = self.frame_count\n\n if frame_count is FrameCount.INDEFINITE:\n raise IndefiniteSeekError(\n \"Cannot seek a renderable with INDEFINITE frame count\"\n )\n\n frame = (\n offset\n if whence is Seek.START\n else (\n self._frame + offset\n if whence is Seek.CURRENT\n else frame_count + offset - 1\n )\n )\n if not 0 <= frame < frame_count:\n raise arg_value_error_range(\n \"offset\",\n offset,\n (\n f\"whence={whence.name}, frame_count={frame_count}\"\n + (f\", current={self._frame}\" if whence is Seek.CURRENT else \"\")\n ),\n )\n self._frame = frame\n\n return frame\n\n def tell(self) -> int:\n \"\"\"Returns the current frame number.\n\n Returns:\n Zero, if the renderable is non-animated or has\n :py:attr:`~term_image.renderable.FrameCount.INDEFINITE` frame count.\n Otherwise, the current frame number.\n \"\"\"\n return self._frame\n\n # Extension methods ========================================================\n\n def _animate_(\n self,\n render_data: RenderData,\n render_args: RenderArgs,\n padding: Padding,\n loops: int,\n cache: bool | int,\n output: TextIO,\n ) -> None:\n \"\"\"Animates frames of a renderable.\n\n Args:\n render_data: Render data.\n render_args: Render arguments associated with the renderable's class.\n output: The text I/O stream to which rendered frames will be written.\n\n All other parameters are the same as for :py:meth:`draw`, except that\n *padding* must have **absolute** dimensions if it's an instance of\n :py:class:`~term_image.padding.AlignedPadding`.\n\n This is called by :py:meth:`draw` for animations.\n\n NOTE:\n * The base implementation does not finalize *render_data*.\n * :term:`Render size` validation is expected to have been performed by\n the caller.\n * When called by :py:meth:`draw` (at least, the base implementation),\n *loops* and *cache* wouldn't have been validated.\n \"\"\"\n from term_image.render import RenderIterator\n\n render_size: Size = render_data[Renderable].size\n height = render_size.height\n pad_left, _, _, pad_bottom = padding._get_exact_dimensions_(render_size)\n render_iter = RenderIterator._from_render_data_(\n self,\n render_data,\n render_args,\n padding,\n loops,\n False if loops == 1 else cache,\n finalize=False,\n )\n cursor_to_next_render_line = f\"\\n{cursor_forward(pad_left)}\"\n cursor_to_render_top_left = (\n f\"\\r{cursor_up(height - 1)}{cursor_forward(pad_left)}\"\n )\n write = output.write\n flush = output.flush\n first_frame_written = False\n\n try:\n # first frame\n try:\n frame = next(render_iter)\n except StopIteration: # `INDEFINITE` frame count\n return\n\n try:\n write(frame.render_output)\n flush()\n except KeyboardInterrupt:\n self._handle_interrupted_draw_(render_data, render_args, output)\n return\n else:\n # Move the cursor to the top-left cell of the region occupied by the\n # render output\n write(\n f\"\\r{cursor_up(height + pad_bottom - 1)}{cursor_forward(pad_left)}\"\n )\n flush()\n\n first_frame_written = True\n\n # Padding has been drawn with the first frame, only the actual render is\n # needed henceforth.\n render_iter.set_padding(NO_PADDING)\n\n # render next frame during previous frame's duration\n duration_ms = frame.duration\n start_ns = perf_counter_ns()\n\n for frame in render_iter: # Render next frame\n # left-over of previous frame's duration\n sleep(\n max(0, duration_ms * 10**6 - (perf_counter_ns() - start_ns)) / 10**9\n )\n\n # clear previous frame, if necessary\n self._clear_frame_(render_data, render_args, pad_left + 1, output)\n\n # draw next frame\n try:\n write(frame.render_output.replace(\"\\n\", cursor_to_next_render_line))\n flush()\n except KeyboardInterrupt:\n self._handle_interrupted_draw_(render_data, render_args, output)\n return\n\n write(cursor_to_render_top_left)\n flush()\n\n # render next frame during previous frame's duration\n start_ns = perf_counter_ns()\n duration_ms = frame.duration\n\n # left-over of last frame's duration\n sleep(max(0, duration_ms * 10**6 - (perf_counter_ns() - start_ns)) / 10**9)\n except KeyboardInterrupt:\n pass\n finally:\n render_iter.close()\n if first_frame_written:\n # Move the cursor to the last line to prevent \"overlaid\" output\n write(cursor_down(height + pad_bottom - 1))\n flush()\n\n def _clear_frame_(\n self,\n render_data: RenderData,\n render_args: RenderArgs,\n cursor_x: int,\n output: TextIO,\n ) -> None:\n \"\"\"Clears the previous frame of an animation, if necessary.\n\n Args:\n render_data: Render data.\n render_args: Render arguments.\n cursor_x: Column/horizontal position of the cursor at the point of calling\n this method.\n\n .. note:: The position is **1-based** i.e the leftmost column on the\n screen is at position 1 (one).\n\n output: The text I/O stream to which frames of the animation are being\n written.\n\n Called by the base implementation of :py:meth:`_animate_` just before drawing\n the next frame of an animation.\n\n Upon calling this method, the cursor should be positioned at the top-left-most\n cell of the region occupied by the frame render output on the terminal screen.\n\n Upon return, ensure the cursor is at the same position it was at the point of\n calling this method (at least logically, since *output* shouldn't be flushed\n yet).\n\n The base implementation does nothing.\n\n NOTE:\n * This is required only if drawing the next frame doesn't inherently\n overwrite the previous frame.\n * This is only meant (and should only be used) as a last resort since\n clearing the previous frame before drawing the next may result in\n visible flicker.\n * Ensure whatever this method does doesn't result in the screen being\n scrolled.\n\n TIP:\n To reduce flicker, it's advisable to **not** flush *output*. It will be\n flushed after writing the next frame.\n \"\"\"\n\n @classmethod\n def _finalize_render_data_(cls, render_data: RenderData) -> None:\n \"\"\"Finalizes render data.\n\n Args:\n render_data: Render data.\n\n Typically, an overriding method should\n\n * finalize the data generated by :py:meth:`_get_render_data_` of the\n **same class**, if necessary,\n * call the overridden method, passing on *render_data*.\n\n NOTE:\n * It's recommended to call :py:meth:`RenderData.finalize()\n `\n instead as that assures a single invocation of this method.\n * Any definition of this method should be safe for multiple invocations on\n the same :py:class:`~term_image.renderable.RenderData` instance, just in\n case.\n\n .. seealso::\n :py:meth:`_get_render_data_`,\n :py:meth:`RenderData.finalize()\n `,\n the *finalize* parameter of :py:meth:`_init_render_`.\n \"\"\"\n\n def _get_frame_count_(self) -> int | Literal[FrameCount.INDEFINITE]:\n \"\"\"Implements :py:attr:`~term_image.renderable.FrameCount.POSTPONED` frame\n count evaluation.\n\n Returns:\n The frame count of the renderable. See :py:attr:`frame_count`.\n\n .. note::\n Returning :py:attr:`~term_image.renderable.FrameCount.POSTPONED` or\n ``1`` (one) is invalid and may result in unexpected/undefined behaviour\n across various interfaces defined by this library (and those derived\n from them), since re-postponing evaluation is unsupported and the\n renderable would have been taken to be animated.\n\n The base implementation raises :py:class:`NotImplementedError`.\n \"\"\"\n raise NotImplementedError(\"POSTPONED frame count evaluation isn't implemented\")\n\n def _get_render_data_(self, *, iteration: bool) -> RenderData:\n \"\"\"Generates data required for rendering that's based on internal or\n external state.\n\n Args:\n iteration: Whether the render operation requiring the data involves a\n sequence of :term:`renders` (most likely of different frames), or it's\n a one-off render.\n\n Returns:\n The generated render data.\n\n The render data should include **copies** of any **variable/mutable**\n internal/external state required for rendering and other data generated from\n constant state but which should **persist** throughout a render operation\n (which may involve consecutive/repeated renders of one or more frames).\n\n May also be used to \"allocate\" and initialize storage for mutable/variable\n data specific to a render operation.\n\n Typically, an overriding method should\n\n * call the overridden method,\n * update the namespace for its defining class (i.e\n :py:meth:`render_data[__class__]\n `) within the\n :py:class:`~term_image.renderable.RenderData` instance returned by the\n overridden method,\n * return the same :py:class:`~term_image.renderable.RenderData` instance.\n\n IMPORTANT:\n The :py:class:`~term_image.renderable.RenderData` instance returned must be\n associated [#rd-ass]_ with the type of the renderable on which this method\n is called i.e ``type(self)``. This is always the case for the base\n implementation of this method.\n\n NOTE:\n This method being called doesn't mean the data generated will be used\n immediately.\n\n .. seealso::\n :py:class:`~term_image.renderable.RenderData`,\n :py:meth:`_finalize_render_data_`,\n :py:meth:`~term_image.renderable.Renderable._init_render_`.\n \"\"\"\n render_data = RenderData(type(self))\n renderable_data: RenderableData = render_data[Renderable]\n renderable_data.update(\n size=self._get_render_size_(),\n frame_offset=self._frame,\n seek_whence=Seek.START,\n iteration=iteration,\n )\n if self.animated:\n renderable_data.duration = self._frame_duration\n\n return render_data\n\n @abstractmethod\n def _get_render_size_(self) -> geometry.Size:\n \"\"\"Returns the renderable's :term:`render size`.\n\n Returns:\n The size of the renderable's :term:`render output`.\n\n The base implementation raises :py:class:`NotImplementedError`.\n\n NOTE:\n Both dimensions are expected to be positive.\n\n .. seealso:: :py:attr:`render_size`\n \"\"\"\n raise NotImplementedError\n\n def _handle_interrupted_draw_(\n self, render_data: RenderData, render_args: RenderArgs, output: TextIO\n ) -> None:\n \"\"\"Performs any special handling necessary when an interruption occurs while\n writing a :term:`render output` to a stream.\n\n Args:\n render_data: Render data.\n render_args: Render arguments.\n output: The text I/O stream to which the render output was being written.\n\n Called by the base implementations of :py:meth:`draw` (for non-animations)\n and :py:meth:`_animate_` when :py:class:`KeyboardInterrupt` is raised while\n writing a render output.\n\n The base implementation does nothing.\n\n NOTE:\n *output* should be flushed by this method.\n\n HINT:\n For a renderable that uses SGR sequences in its render output, this method\n may write ``CSI 0 m`` to *output*.\n \"\"\"\n\n # *render_args*, no *padding*; or neither\n @overload\n def _init_render_(\n self,\n renderer: Callable[[RenderData, RenderArgs], T],\n render_args: RenderArgs | None = None,\n *,\n iteration: bool = False,\n finalize: bool = True,\n check_size: bool = False,\n allow_scroll: bool = False,\n ) -> tuple[T, None]: ...\n\n # both *render_args* and *padding*\n @overload\n def _init_render_(\n self,\n renderer: Callable[[RenderData, RenderArgs], T],\n render_args: RenderArgs | None,\n padding: OptionalPaddingT,\n *,\n iteration: bool = False,\n finalize: bool = True,\n check_size: bool = False,\n allow_scroll: bool = False,\n ) -> tuple[T, OptionalPaddingT]: ...\n\n # *padding*, no *render_args*\n @overload\n def _init_render_(\n self,\n renderer: Callable[[RenderData, RenderArgs], T],\n *,\n padding: OptionalPaddingT,\n iteration: bool = False,\n finalize: bool = True,\n check_size: bool = False,\n allow_scroll: bool = False,\n ) -> tuple[T, OptionalPaddingT]: ...\n\n def _init_render_(\n self,\n renderer: Callable[[RenderData, RenderArgs], T],\n render_args: RenderArgs | None = None,\n padding: Padding | None = None,\n *,\n iteration: bool = False,\n finalize: bool = True,\n check_size: bool = False,\n allow_scroll: bool = False,\n ) -> tuple[T, Padding | None]:\n \"\"\"Initiates a render operation.\n\n Args:\n renderer: Performs a render operation or extracts render data and arguments\n for a render operation to be performed later on.\n render_args: Render arguments.\n padding (:py:data:`OptionalPaddingT`): :term:`Render output` padding.\n iteration: Whether the render operation involves a sequence of renders\n (most likely of different frames), or it's a one-off render.\n finalize: Whether to finalize the render data passed to *renderer*\n immediately *renderer* returns.\n check_size: Whether to validate the [padded] :term:`render size` of\n **non-animations**.\n allow_scroll: Whether to validate the [padded] :term:`render height` of\n **non-animations**. Ignored if *check_size* is ``False``.\n\n Returns:\n A tuple containing\n\n * The return value of *renderer*.\n * *padding* (with equivalent **absolute** dimensions if it's an instance of\n :py:class:`~term_image.padding.AlignedPadding`).\n\n Raises:\n IncompatibleRenderArgsError: Incompatible render arguments.\n RenderSizeOutofRangeError: *check_size* is ``True`` and the [padded]\n :term:`render size` cannot fit into the :term:`terminal size`.\n\n :rtype: tuple[T, :py:data:`OptionalPaddingT`]\n\n After preparing render data and processing arguments, *renderer* is called with\n the following positional arguments:\n\n 1. Render data associated with **the renderable's class**\n 2. Render arguments associated with **the renderable's class** and initialized\n with *render_args*\n\n Any exception raised by *renderer* is propagated.\n\n IMPORTANT:\n Beyond this method (i.e any context from *renderer* onwards), use of any\n variable state (internal or external) should be avoided if possible.\n Any variable state (internal or external) required for rendering should\n be provided via :py:meth:`_get_render_data_`.\n\n If at all any variable state has to be used and is not\n reasonable/practicable to be provided via :py:meth:`_get_render_data_`,\n it should be read only once during a single render and passed to any\n nested/subsequent calls that require the value of that state during the\n same render.\n\n This is to prevent inconsistency in data used for the same render which may\n result in unexpected output.\n \"\"\"\n if not (render_args and render_args.render_cls is type(self)):\n # Validate compatibility (and convert, if compatible)\n render_args = RenderArgs(type(self), render_args)\n terminal_size = get_terminal_size()\n render_data = self._get_render_data_(iteration=iteration)\n try:\n if padding and isinstance(padding, AlignedPadding) and padding.relative:\n padding = padding.resolve(terminal_size)\n\n if check_size:\n render_size: Size = render_data[Renderable].size\n width, height = (\n padding.get_padded_size(render_size) if padding else render_size\n )\n terminal_width, terminal_height = terminal_size\n\n if width > terminal_width:\n raise RenderSizeOutofRangeError(\n f\"{'Padded render' if padding else 'Render'} width out of \"\n f\"range (got: {width}; terminal_width={terminal_width})\"\n )\n if not allow_scroll and height > terminal_height:\n raise RenderSizeOutofRangeError(\n f\"{'Padded render' if padding else 'Render'} height out of \"\n f\"range (got: {height}; terminal_height={terminal_height})\"\n )\n\n return renderer(render_data, render_args), padding\n finally:\n if finalize:\n render_data.finalize()\n\n @abstractmethod\n def _render_(self, render_data: RenderData, render_args: RenderArgs) -> Frame:\n \"\"\":term:`Renders` a frame.\n\n Args:\n render_data: Render data.\n render_args: Render arguments.\n\n Returns:\n The rendered frame.\n\n * The :py:attr:`~term_image.renderable.Frame.render_size` field =\n :py:attr:`render_data[Renderable].size\n `.\n * The :py:attr:`~term_image.renderable.Frame.render_output` field holds the\n :term:`render output`. This string should:\n\n * contain as many lines as ``render_size.height`` i.e exactly\n ``render_size.height - 1`` occurrences of ``\\\\n`` (the newline\n sequence).\n * occupy exactly ``render_size.height`` lines and ``render_size.width``\n columns on each line when drawn onto a terminal screen, **at least**\n when the render **size** it not greater than the terminal size on\n either axis.\n\n .. tip::\n If for any reason, the output behaves differently when the render\n **height** is greater than the terminal height, the behaviour, along\n with any possible alternatives or workarounds, should be duely noted.\n This doesn't apply to the **width**.\n\n * **not** end with ``\\\\n`` (the newline sequence).\n\n * As for the :py:attr:`~term_image.renderable.Frame.duration` field, if\n the renderable is:\n\n * **animated**; the value should be determined from the frame data\n source (or a default/fallback value, if undeterminable), if\n :py:attr:`render_data[Renderable].duration\n ` is\n :py:attr:`~term_image.renderable.FrameDuration.DYNAMIC`.\n Otherwise, it should be equal to\n :py:attr:`render_data[Renderable].duration\n `.\n * **non-animated**; the value range is unspecified i.e it may be given\n any value.\n\n Raises:\n StopIteration: End of iteration for an animated renderable with\n :py:attr:`~term_image.renderable.FrameCount.INDEFINITE` frame count.\n RenderError: An error occurred while rendering.\n\n NOTE:\n :py:class:`StopIteration` may be raised if and only if\n :py:attr:`render_data[Renderable].iteration\n ` is ``True``.\n Otherwise, it would be out of place.\n\n .. seealso:: :py:class:`~term_image.renderable.RenderableData`.\n \"\"\"\n raise NotImplementedError", "n_imports_parsed": 14, "n_files_resolved": 7, "n_chars_extracted": 41124}, "tests/test_image/test_block.py::58": {"resolved_imports": ["src/term_image/_ctlseqs.py", "src/term_image/image/block.py", "src/term_image/image/common.py"], "used_names": ["SGR_BG_DIRECT", "SGR_DEFAULT", "set_fg_bg_colors"], "enclosing_function": "test_background_colour", "extracted_code": "# Source: src/term_image/_ctlseqs.py\nSGR_BG_DIRECT = SGR % f\"48;2;{Pm(3)}\"\n\nSGR_DEFAULT = SGR % \"\"", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 98}, "tests/test_image/test_base.py::213": {"resolved_imports": ["src/term_image/__init__.py", "src/term_image/_ctlseqs.py", "src/term_image/exceptions.py", "src/term_image/image/block.py", "src/term_image/image/common.py"], "used_names": ["BlockImage", "pytest", "python_img"], "enclosing_function": "test_frame_duration", "extracted_code": "# Source: src/term_image/image/block.py\nclass BlockImage(TextImage):\n \"\"\"A render style using unicode half blocks and direct-color colour escape\n sequences.\n\n See :py:class:`TextImage` for the description of the constructor.\n \"\"\"\n\n @classmethod\n def is_supported(cls):\n if cls._supported is None:\n COLORTERM = os.environ.get(\"COLORTERM\") or \"\"\n TERM = os.environ.get(\"TERM\") or \"\"\n cls._supported = (\n \"truecolor\" in COLORTERM or \"24bit\" in COLORTERM or \"256color\" in TERM\n )\n\n return cls._supported\n\n def _get_render_size(self) -> Tuple[int, int]:\n return tuple(map(mul, self.rendered_size, (1, 2)))\n\n @staticmethod\n def _pixels_cols(\n *, pixels: Optional[int] = None, cols: Optional[int] = None\n ) -> int:\n return pixels if pixels is not None else cols\n\n @staticmethod\n def _pixels_lines(\n *, pixels: Optional[int] = None, lines: Optional[int] = None\n ) -> int:\n return ceil(pixels / 2) if pixels is not None else lines * 2\n\n def _render_image(\n self,\n img: PIL.Image.Image,\n alpha: Union[None, float, str],\n *,\n frame: bool = False,\n split_cells: bool = False,\n ) -> str:\n # NOTE:\n # It's more efficient to write separate strings to the buffer separately\n # than concatenate and write together.\n\n def update_buffer():\n if alpha:\n no_alpha = False\n if a_cluster1 == 0 == a_cluster2:\n buf_write(SGR_DEFAULT)\n buf_write(blank * n)\n elif a_cluster1 == 0: # up is transparent\n buf_write(SGR_DEFAULT)\n buf_write(SGR_FG_DIRECT % cluster2)\n buf_write(lower_pixel * n)\n elif a_cluster2 == 0: # down is transparent\n buf_write(SGR_DEFAULT)\n buf_write(SGR_FG_DIRECT % cluster1)\n buf_write(upper_pixel * n)\n else:\n no_alpha = True\n\n if not alpha or no_alpha:\n r, g, b = cluster2\n # Kitty does not render BG colors equal to the default BG color\n if is_on_kitty and cluster2 == bg_color:\n r += r < 255 or -1\n buf_write(SGR_BG_DIRECT % (r, g, b))\n if cluster1 == cluster2:\n buf_write(blank * n)\n else:\n buf_write(SGR_FG_DIRECT % cluster1)\n buf_write(upper_pixel * n)\n\n buffer = io.StringIO()\n buf_write = buffer.write # Eliminate attribute resolution cost\n\n bg_color = get_fg_bg_colors()[1]\n is_on_kitty = self._is_on_kitty()\n if split_cells:\n blank = \" \\0\"\n lower_pixel = LOWER_PIXEL + \"\\0\"\n upper_pixel = UPPER_PIXEL + \"\\0\"\n else:\n blank = \" \"\n lower_pixel = LOWER_PIXEL\n upper_pixel = UPPER_PIXEL\n end_of_line = SGR_DEFAULT + \"\\n\"\n\n width, height = self._get_render_size()\n frame_img = img if frame else None\n img, rgb, a = self._get_render_data(img, alpha, round_alpha=True, frame=frame)\n alpha = img.mode == \"RGBA\"\n\n # clean up (ImageIterator uses one PIL image throughout)\n if frame_img is not img:\n self._close_image(img)\n\n rgb_pairs = (\n (\n zip(rgb[x : x + width], rgb[x + width : x + width * 2]),\n (rgb[x], rgb[x + width]),\n )\n for x in range(0, len(rgb), width * 2)\n )\n a_pairs = (\n (\n zip(a[x : x + width], a[x + width : x + width * 2]),\n (a[x], a[x + width]),\n )\n for x in range(0, len(a), width * 2)\n )\n\n row_no = 0\n # Two rows of pixels per line\n for (rgb_pair, (cluster1, cluster2)), (a_pair, (a_cluster1, a_cluster2)) in zip(\n rgb_pairs, a_pairs\n ):\n row_no += 2\n n = 0\n for (px1, px2), (a1, a2) in zip(rgb_pair, a_pair):\n # Color-code characters and write to buffer\n # when upper and/or lower pixel color/alpha-level changes\n if not (alpha and a1 == a_cluster1 == 0 == a_cluster2 == a2) and (\n px1 != cluster1\n or px2 != cluster2\n or alpha\n and (\n # From non-transparent to transparent\n a_cluster1 != a1 == 0\n or a_cluster2 != a2 == 0\n # From transparent to non-transparent\n or 0 == a_cluster1 != a1\n or 0 == a_cluster2 != a2\n )\n ):\n update_buffer()\n cluster1 = px1\n cluster2 = px2\n if alpha:\n a_cluster1 = a1\n a_cluster2 = a2\n n = 0\n n += 1\n\n update_buffer() # Rest of the line\n if split_cells:\n # Set the last \"\\0\" to be overwritten by the next byte\n buffer.seek(buffer.tell() - 1)\n if row_no < height: # last line not yet rendered\n buf_write(end_of_line)\n\n buf_write(SGR_DEFAULT) # Reset color after last line\n\n with buffer:\n return buffer.getvalue()", "n_imports_parsed": 16, "n_files_resolved": 5, "n_chars_extracted": 5566}, "tests/test_top_level.py::63": {"resolved_imports": ["src/term_image/__init__.py", "src/term_image/utils.py", "src/term_image/exceptions.py", "src/term_image/geometry.py"], "used_names": ["AutoCellRatio", "Size", "get_cell_ratio", "reset_cell_size_ratio", "set_cell_ratio", "set_cell_size"], "enclosing_function": "test_dynamic", "extracted_code": "# Source: src/term_image/__init__.py\nclass AutoCellRatio(Enum):\n \"\"\":ref:`auto-cell-ratio` enumeration and support status.\n\n .. seealso:: :py:func:`set_cell_ratio`.\n \"\"\"\n\n FIXED = auto()\n \"\"\"Fixed cell ratio.\n\n :meta hide-value:\n \"\"\"\n\n DYNAMIC = auto()\n \"\"\"Dynamic cell ratio.\n\n :meta hide-value:\n \"\"\"\n\n is_supported: ClassVar[bool | None]\n \"\"\"Auto cell ratio support status. Can be\n\n :meta hide-value:\n\n - ``None`` -> support status not yet determined\n - ``True`` -> supported\n - ``False`` -> not supported\n\n Can be explicitly set when using auto cell ratio but want to avoid the support\n check in a situation where the support status is foreknown. Can help to avoid\n being wrongly detected as unsupported on a :ref:`queried `\n terminal that doesn't respond on time.\n\n For instance, when using multiprocessing, if the support status has been\n determined in the main process, this value can simply be passed on to and set\n within the child processes.\n \"\"\"\n\ndef get_cell_ratio() -> float:\n \"\"\"Returns the global :term:`cell ratio`.\n\n .. seealso:: :py:func:`set_cell_ratio`.\n \"\"\"\n # `(1, 2)` is a fallback in case the terminal doesn't respond in time\n return _cell_ratio or truediv(*(get_cell_size() or (1, 2)))\n\ndef set_cell_ratio(ratio: float | AutoCellRatio) -> None:\n \"\"\"Sets the global :term:`cell ratio`.\n\n Args:\n ratio: Can be one of the following values.\n\n * A positive :py:class:`float` value.\n * :py:attr:`AutoCellRatio.FIXED`, the ratio is immediately determined from\n the :term:`active terminal`.\n * :py:attr:`AutoCellRatio.DYNAMIC`, the ratio is determined from the\n :term:`active terminal` whenever :py:func:`get_cell_ratio` is called,\n though with some caching involved, such that the ratio is re-determined\n only if the terminal size changes.\n\n Raises:\n ValueError: *ratio* is a non-positive :py:class:`float`.\n term_image.exceptions.TermImageError: Auto cell ratio is not supported\n in the :term:`active terminal` or on the current platform.\n\n This value is taken into consideration when setting image sizes for **text-based**\n render styles, in order to preserve the aspect ratio of images drawn to the\n terminal.\n\n NOTE:\n Changing the cell ratio does not automatically affect any image that has a\n :term:`fixed size`. For a change in cell ratio to take effect, the image's\n size has to be re-set.\n\n IMPORTANT:\n See :ref:`auto-cell-ratio` for details about the auto modes.\n \"\"\"\n global _cell_ratio\n\n if isinstance(ratio, AutoCellRatio):\n if AutoCellRatio.is_supported is None:\n AutoCellRatio.is_supported = get_cell_size() is not None\n\n if not AutoCellRatio.is_supported:\n raise TermImageError(\n \"Auto cell ratio is not supported in the active terminal or on the \"\n \"current platform\"\n )\n elif ratio is AutoCellRatio.FIXED:\n # `(1, 2)` is a fallback in case the terminal doesn't respond in time\n _cell_ratio = truediv(*(get_cell_size() or (1, 2)))\n else:\n _cell_ratio = None\n else:\n if ratio <= 0.0:\n raise arg_value_error_range(\"ratio\", ratio)\n _cell_ratio = ratio\n\n\n# Source: src/term_image/geometry.py\nclass Size(RawSize):\n \"\"\"The dimensions of a rectangular region.\n\n Raises:\n ValueError: Either dimension is non-positive.\n\n Same as :py:class:`RawSize`, except that both dimensions must be **positive**.\n\n IMPORTANT:\n In the case of multiple inheritance i.e if subclassing this class along with\n other classes, this class should appear last (i.e to the far right) in the\n base class list.\n \"\"\"\n\n __slots__ = ()\n\n def __new__(cls, width: int, height: int) -> Self:\n if width < 1:\n raise arg_value_error_range(\"width\", width)\n if height < 1:\n raise arg_value_error_range(\"height\", height)\n\n # Using `tuple` directly instead of `super()` for performance\n return tuple.__new__(cls, (width, height))", "n_imports_parsed": 6, "n_files_resolved": 4, "n_chars_extracted": 4235}, "tests/test_color.py::155": {"resolved_imports": ["src/term_image/color.py"], "used_names": ["Color"], "enclosing_function": "test_instance_type", "extracted_code": "# Source: src/term_image/color.py\nclass Color(_DummyColor):\n \"\"\"A color.\n\n Args:\n r: The red channel.\n g: The green channel.\n b: The blue channel.\n a: The alpha channel (opacity).\n\n Raises:\n ValueError: The value of a channel is not within the valid range.\n\n NOTE:\n The valid value range for all channels is 0 to 255, both inclusive.\n\n TIP:\n This class is a :py:class:`~typing.NamedTuple` of four fields.\n\n WARNING:\n In the case of multiple inheritance i.e if subclassing this class along with\n other classes, this class should appear last (i.e to the far right) in the\n base class list.\n \"\"\"\n\n __slots__ = ()\n\n # Overrides these descriptors in order to speed up attribute resolution and to\n # simplify auto documentation.\n r: int = _DummyColor.r\n r.__doc__ = \"\"\"The red channel\"\"\"\n\n g: int = _DummyColor.g\n g.__doc__ = \"\"\"The green channel\"\"\"\n\n b: int = _DummyColor.b\n b.__doc__ = \"\"\"The blue channel\"\"\"\n\n a: int = _DummyColor.a\n a.__doc__ = \"\"\"The alpha channel (opacity)\"\"\"\n\n def __new__(cls, r: int, g: int, b: int, a: int = 255) -> Self:\n # Only the 8 LSb may be set for any value within the range [0, 255].\n # `x & ~255` unsets the 8 LSb. Hence, if the result is non-zero (i.e any\n # of the bits above the lowest 8 is set), it implies `x` is out of range.\n #\n # Actually benchmarked *this* against the \"simpler\" logically-negated chained\n # comparison (i.e `0 <= x <= 255`) and *this* was significantly faster for all\n # cases i.e within, on the boundaries, and outside (on both sides).\n if (r | g | b | a) & ~255: # First test to see if *any* is out of range\n if r & ~255:\n raise arg_value_error_range(\"r\", r)\n if g & ~255:\n raise arg_value_error_range(\"g\", g)\n if b & ~255:\n raise arg_value_error_range(\"b\", b)\n # There's no point checking since at least one is out of range\n raise arg_value_error_range(\"a\", a)\n\n # Using `tuple` directly instead of `super()` for performance\n return tuple.__new__(cls, (r, g, b, a))\n\n @property\n def hex(self) -> str:\n \"\"\"Converts the color to its RGBA hexadecimal representation.\n\n Returns:\n The RGBA hex color string, starting with the ``#`` character i.e\n ``#rrggbbaa``.\n\n Each channel is represented by two **lowercase** hex digits ranging from\n ``00`` to ``ff``.\n \"\"\"\n return \"#%02x%02x%02x%02x\" % self\n\n @property\n def rgb(self) -> tuple[int, int, int]:\n \"\"\"Extracts the R, G and B channels of the color.\n\n Returns:\n A 3-tuple containing the red, green and blue channel values.\n \"\"\"\n return self[:3]\n\n @property\n def rgb_hex(self) -> str:\n \"\"\"Converts the color to its RGB hexadecimal representation.\n\n Returns:\n The RGB hex color string, starting with the ``#`` character i.e ``#rrggbb``.\n\n Each channel is represented by two **lowercase** hex digits ranging from\n ``00`` to ``ff``.\n \"\"\"\n return \"#%02x%02x%02x\" % self[:3]\n\n @classmethod\n def from_hex(cls, color: str) -> Self:\n \"\"\"Creates a new instance from a hexadecimal color string.\n\n Args:\n color: A **case-insensitive** RGB or RGBA hex color string, **optionally**\n starting with the ``#`` (pound) character i.e ``[#]rrggbb[aa]``.\n\n Returns:\n A new instance representing the given hex color string.\n\n Raises:\n ValueError: Invalid hex color string.\n\n NOTE:\n For an RGB hex color string, the value of A (the alpha channel) is\n taken to be 255.\n \"\"\"\n if not (match := _RGBA_HEX_RE.fullmatch(color)):\n raise ValueError(f\"Invalid hex color string (got: {color!r})\")\n\n return tuple.__new__(cls, [int(x, 16) for x in match.groups(\"ff\")])\n\n @classmethod\n def _new(cls, r: int, g: int, b: int, a: int = 255) -> Self:\n \"\"\"Alternate constructor for internal use only.\"\"\"\n return tuple.__new__(cls, (r, g, b, a))", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 4255}, "tests/test_image/test_iterm2.py::233": {"resolved_imports": ["src/term_image/__init__.py", "src/term_image/_ctlseqs.py", "src/term_image/exceptions.py", "src/term_image/image/__init__.py", "src/term_image/image/iterm2.py"], "used_names": ["ITerm2Image", "pytest", "python_img"], "enclosing_function": "test_native_anim_max_bytes", "extracted_code": "", "n_imports_parsed": 15, "n_files_resolved": 5, "n_chars_extracted": 0}, "tests/widget/urwid/test_main.py::151": {"resolved_imports": ["src/term_image/__init__.py", "src/term_image/_ctlseqs.py", "src/term_image/exceptions.py", "src/term_image/image/block.py", "src/term_image/image/common.py", "src/term_image/image/iterm2.py", "src/term_image/image/kitty.py", "src/term_image/widget/_urwid.py"], "used_names": ["Size", "UrwidImage"], "enclosing_function": "test_upscale_false", "extracted_code": "# Source: src/term_image/image/common.py\nclass Size(Enum):\n \"\"\"Enumeration for :term:`automatic sizing`.\"\"\"\n\n #: Equivalent to :py:attr:`ORIGINAL` if it will fit into the\n #: :term:`frame size`, else :py:attr:`FIT`.\n #:\n #: :meta hide-value:\n AUTO = Hidden()\n\n #: The image size is set to fit optimally **within** the :term:`frame size`.\n #:\n #: :meta hide-value:\n FIT = Hidden()\n\n #: The size is set such that the width is exactly the :term:`frame width`,\n #: regardless of the :term:`cell ratio`.\n #:\n #: :meta hide-value:\n FIT_TO_WIDTH = Hidden()\n\n #: The image size is set such that the image is rendered with as many pixels as the\n #: the original image consists of.\n #:\n #: :meta hide-value:\n ORIGINAL = Hidden()\n\n\n# Source: src/term_image/widget/_urwid.py\nclass UrwidImage(urwid.Widget):\n \"\"\"Image widget (box/flow) for the urwid TUI framework.\n\n Args:\n image: The image to be rendered by the widget.\n format_spec: :ref:`Render format specifier `. Padding width and\n height are ignored.\n upscale: If ``True``, the image will be upscaled to fit maximally within the\n available size, if necessary, while still preserving the aspect ratio.\n Otherwise, the image is never upscaled.\n\n Raises:\n TypeError: An argument is of an inappropriate type.\n ValueError: An argument is of an appropriate type but has an\n unexpected/invalid value.\n term_image.exceptions.StyleError: Invalid style-specific format specifier.\n term_image.exceptions.UrwidImageError: Too many image widgets rendering images\n with the *kitty* render style.\n\n | Any ample space in the widget's render size is filled with spaces.\n | For animated images, the current frame (at render-time) is rendered.\n\n TIP:\n If *image* is of a :ref:`graphics-based ` render style and the\n widget is being used as or within a **flow** widget, with overlays or in any\n other case where the canvas will require vertical trimming, make sure to use a\n render method that splits images across lines such as the **LINES** render\n method for *kitty* and *iterm2* render styles.\n\n NOTE:\n * The `z-index` style-specific format spec field for\n :py:class:`~term_image.image.KittyImage` is ignored as this is used\n internally.\n * A **maximum** of ``2**32 - 2`` instances initialized with\n :py:class:`~term_image.image.KittyImage` instances may exist at the same time.\n\n IMPORTANT:\n This is defined if and only if the ``urwid`` package is available.\n \"\"\"\n\n _sizing = frozenset((urwid.BOX, urwid.FLOW))\n ignore_focus = True\n\n _ti_error_placeholder = None\n\n # For kitty images\n _ti_disguise_state = 0\n _ti_free_z_indexes = set()\n\n # Progresses thus: 1, -1, 2, -2, 3, ..., 2**31 - 1, -(2**31 - 1)\n # This sequence results in shorter image escape sequences compared to starting\n # from -(2**31)\n _ti_next_z_index = 1\n\n def __init__(\n self, image: BaseImage, format_spec: str = \"\", *, upscale: bool = False\n ) -> None:\n if not isinstance(image, BaseImage):\n raise arg_type_error(\"image\", image)\n\n if not isinstance(format_spec, str):\n raise arg_type_error(\"format_spec\", format_spec)\n *fmt, alpha, style_args = image._check_format_spec(format_spec)\n\n if not isinstance(upscale, bool):\n raise arg_type_error(\"upscale\", upscale)\n\n super().__init__()\n self._ti_image = image\n self._ti_h_align, _, self._ti_v_align, _ = fmt\n self._ti_alpha = alpha\n self._ti_style_args = style_args\n self._ti_sizing = Size.FIT if upscale else Size.AUTO\n\n if isinstance(image, TextImage):\n style_args[\"split_cells\"] = True\n elif isinstance(image, KittyImage):\n style_args[\"z_index\"] = self._ti_z_index = self._ti_get_z_index()\n\n # Since Konsole doesn't blend images placed at the same location and\n # z-index, unlike Kitty (and potentially others), `blend=True` is\n # better on Konsole as it reduces/eliminates flicker.\n if get_terminal_name_version()[0] != \"konsole\":\n # To clear directly overlapped images when urwid redraws a line without\n # a change in image position\n style_args[\"blend\"] = False\n\n def __del__(self) -> None:\n if hasattr(self, \"_ti_z_index\"):\n __class__._ti_free_z_indexes.add(self._ti_z_index)\n\n image = property(\n lambda self: self._ti_image,\n doc=\"\"\"\n The image rendered by the widget\n\n :type: BaseImage\n\n GET:\n Returns the image instance rendered by the widget.\n \"\"\",\n )\n\n def render(self, size: Tuple[int, int], focus: bool = False) -> urwid.Canvas:\n image = self._ti_image\n\n if len(size) == 2: # box\n image.set_size(self._ti_sizing, frame_size=size)\n elif len(size) == 1: # flow\n if self._ti_sizing is Size.FIT:\n image.set_size(size[0])\n else:\n fit_size = self._ti_image._valid_size(size[0])\n ori_size = self._ti_image._valid_size(Size.ORIGINAL)\n image._size = (\n ori_size\n if ori_size[0] <= fit_size[0] and ori_size[1] <= fit_size[1]\n else fit_size\n )\n size = (size[0], image._size[1])\n else: # fixed\n raise UrwidImageError(\"Not a fixed widget\")\n\n try:\n render = image._format_render(\n image._renderer(\n image._render_image, self._ti_alpha, **self._ti_style_args\n ),\n self._ti_h_align,\n size[0],\n self._ti_v_align,\n size[1],\n )\n except Exception:\n if type(self)._ti_error_placeholder is None:\n raise\n canv = type(self)._ti_error_placeholder.render(size, focus)\n else:\n canv = UrwidImageCanvas(render, size, image._size)\n\n return canv\n\n def rows(self, size: Tuple[int], focus: bool = False) -> int:\n fit_size = self._ti_image._valid_size(size[0])\n if self._ti_sizing is Size.FIT:\n n_rows = fit_size[1]\n else:\n ori_size = self._ti_image._valid_size(Size.ORIGINAL)\n n_rows = (\n ori_size[1]\n if ori_size[0] <= fit_size[0] and ori_size[1] <= fit_size[1]\n else fit_size[1]\n )\n\n return n_rows\n\n @classmethod\n def set_error_placeholder(cls, widget: Optional[urwid.Widget]) -> None:\n \"\"\"Sets the widget to be rendered in place of an image when rendering fails.\n\n Args:\n widget: The placeholder widget or ``None`` to remove the placeholder.\n\n Raises:\n TypeError: *widget* is not an urwid widget.\n\n If set, any exception raised during rendering is **suppressed** and the\n placeholder is rendered in place of the image.\n \"\"\"\n if not isinstance(widget, urwid.Widget):\n raise arg_type_error(\"widget\", widget)\n\n cls._ti_error_placeholder = widget\n\n @staticmethod\n def _ti_get_z_index() -> int:\n if __class__._ti_free_z_indexes:\n return __class__._ti_free_z_indexes.pop()\n\n z_index = __class__._ti_next_z_index\n if z_index == 2**31:\n raise UrwidImageError(\"Too many image widgets with the kitty render style\")\n __class__._ti_next_z_index = -z_index if z_index > 0 else -z_index + 1\n\n return z_index\n\n def _ti_change_disguise(self) -> None:\n \"\"\"See :py:meth`UrwidImageCanvas._ti_change_disguise`.\"\"\"\n self._ti_disguise_state = (self._ti_disguise_state + 1) % 3", "n_imports_parsed": 10, "n_files_resolved": 8, "n_chars_extracted": 7948}, "tests/test_image/test_block.py::66": {"resolved_imports": ["src/term_image/_ctlseqs.py", "src/term_image/image/block.py", "src/term_image/image/common.py"], "used_names": ["SGR_BG_DIRECT", "SGR_DEFAULT", "set_fg_bg_colors"], "enclosing_function": "test_background_colour", "extracted_code": "# Source: src/term_image/_ctlseqs.py\nSGR_BG_DIRECT = SGR % f\"48;2;{Pm(3)}\"\n\nSGR_DEFAULT = SGR % \"\"", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 98}, "tests/test_geometry.py::10": {"resolved_imports": ["src/term_image/geometry.py"], "used_names": ["RawSize", "pytest"], "enclosing_function": "test_width", "extracted_code": "# Source: src/term_image/geometry.py\nclass RawSize(NamedTuple):\n \"\"\"The dimensions of a rectangular region.\n\n Args:\n width: The horizontal dimension\n height: The vertical dimension\n\n NOTE:\n * A dimension may be non-positive but the validity and meaning would be\n determined by the receiving interface.\n * This is a subclass of :py:class:`tuple`. Hence, instances can be used anyway\n and anywhere tuples can.\n \"\"\"\n\n width: int\n height: int\n\n @classmethod\n def _new(cls, width: int, height: int) -> Self:\n \"\"\"Alternate constructor for internal use only.\"\"\"\n return tuple.__new__(cls, (width, height))", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 682}, "tests/test_padding.py::156": {"resolved_imports": ["src/term_image/_ctlseqs.py", "src/term_image/geometry.py", "src/term_image/padding.py"], "used_names": ["AlignedPadding", "HAlign", "pytest"], "enclosing_function": "test_non_default", "extracted_code": "# Source: src/term_image/padding.py\nclass HAlign(IntEnum):\n \"\"\"Horizontal alignment enumeration\"\"\"\n\n LEFT = 0\n \"\"\"Left horizontal alignment\n\n :meta hide-value:\n \"\"\"\n\n CENTER = auto()\n \"\"\"Center horizontal alignment\n\n :meta hide-value:\n \"\"\"\n\n RIGHT = auto()\n \"\"\"Right horizontal alignment\n\n :meta hide-value:\n \"\"\"\n\nclass AlignedPadding(Padding):\n \"\"\"Aligned :term:`render output` padding.\n\n Args:\n width: Minimum :term:`render width`.\n height: Minimum :term:`render height`.\n h_align: Horizontal alignment.\n v_align: Vertical alignment.\n\n If *width* or *height* is:\n\n * positive, it is **absolute** and used as-is.\n * non-positive, it is **relative** to the corresponding terminal dimension\n (**at the point of resolution**) and equivalent to the absolute dimension\n ``max(terminal_dimension + relative_dimension, 1)``.\n\n The *padded render dimension* (i.e the dimension of a :term:`render output` after\n it's padded) on each axis is given by::\n\n padded_dimension = max(render_dimension, absolute_minimum_dimension)\n\n In words... If the **absolute** *minimum render dimension* on an axis is less than\n or equal to the corresponding *render dimension*, there is no padding on that axis\n and the *padded render dimension* on that axis is equal to the *render dimension*.\n Otherwise, the render output will be padded along that axis and the *padded render\n dimension* on that axis is equal to the *minimum render dimension*.\n\n The amount of padding to each side depends on the alignment, defined by *h_align*\n and *v_align*.\n\n IMPORTANT:\n :py:class:`RelativePaddingDimensionError` is raised if any padding-related\n computation/operation (basically, calling any method other than\n :py:meth:`resolve`) is performed on an instance with **relative** *minimum\n render dimension(s)* i.e if :py:attr:`relative` is ``True``.\n\n NOTE:\n Any interface receiving an instance with **relative** dimension(s) should\n typically resolve it/them upon reception.\n\n TIP:\n * Instances are immutable and hashable.\n * Instances with equal fields compare equal.\n \"\"\"\n\n # Class Attributes =========================================================\n\n __slots__ = (\"width\", \"height\", \"h_align\", \"v_align\", \"relative\")\n\n # Instance Attributes ======================================================\n\n width: int\n \"\"\"Minimum :term:`render width`\"\"\"\n\n height: int\n \"\"\"Minimum :term:`render height`\"\"\"\n\n h_align: HAlign\n \"\"\"Horizontal alignment\"\"\"\n\n v_align: VAlign\n \"\"\"Vertical alignment\"\"\"\n\n fill: str\n\n relative: bool\n \"\"\"``True`` if either or both *minimum render dimension(s)* is/are relative i.e\n non-positive. Otherwise, ``False``.\n \"\"\"\n\n # Special Methods ==========================================================\n\n def __init__(\n self,\n width: int,\n height: int,\n h_align: HAlign = HAlign.CENTER,\n v_align: VAlign = VAlign.MIDDLE,\n fill: str = \" \",\n ):\n super().__init__(fill)\n\n _setattr = super().__setattr__\n _setattr(\"width\", width)\n _setattr(\"height\", height)\n _setattr(\"h_align\", h_align)\n _setattr(\"v_align\", v_align)\n _setattr(\"relative\", not width > 0 < height)\n\n def __repr__(self) -> str:\n return \"{}(width={}, height={}, h_align={}, v_align={}, fill={!r})\".format(\n type(self).__name__,\n self.width,\n self.height,\n self.h_align.name,\n self.v_align.name,\n self.fill,\n )\n\n # Properties ===============================================================\n\n @property\n def size(self) -> RawSize:\n \"\"\"Minimum :term:`render size`\n\n GET:\n Returns the *minimum render dimensions*.\n \"\"\"\n return _RawSize(self.width, self.height)\n\n # Public Methods ===========================================================\n\n @override\n def get_padded_size(self, render_size: Size) -> Size:\n \"\"\"Computes an expected padded :term:`render size`.\n\n See :py:meth:`Padding.get_padded_size`.\n\n Raises:\n RelativePaddingDimensionError: Relative *minimum render dimension(s)*.\n \"\"\"\n if self.relative:\n raise RelativePaddingDimensionError(\"Relative minimum render dimension(s)\")\n\n return _Size(max(self.width, render_size[0]), max(self.height, render_size[1]))\n\n def resolve(self, terminal_size: os.terminal_size) -> AlignedPadding:\n \"\"\"Resolves **relative** *minimum render dimensions*.\n\n Args:\n terminal_size: The terminal size against which to resolve relative\n dimensions.\n\n Returns:\n An instance with equivalent **absolute** dimensions.\n \"\"\"\n if not self.relative:\n return self\n\n width, height, *args, _ = astuple(self)\n terminal_width, terminal_height = terminal_size\n if width <= 0:\n width = max(terminal_width + width, 1)\n if height <= 0:\n height = max(terminal_height + height, 1)\n\n return type(self)(width, height, *args)\n\n # Extension methods ========================================================\n\n @override\n def _get_exact_dimensions_(self, render_size: Size) -> tuple[int, int, int, int]:\n if self.relative:\n raise RelativePaddingDimensionError(\"Relative minimum render dimension(s)\")\n\n width, height, h_align, v_align = astuple(self)[:4]\n render_width, render_height = render_size\n\n if width > render_width:\n padding_width = width - render_width\n numerator, denominator = _ALIGN_RATIOS[h_align]\n left = padding_width * numerator // denominator\n right = padding_width - left\n else:\n left = right = 0\n\n if height > render_height:\n padding_height = height - render_height\n numerator, denominator = _ALIGN_RATIOS[v_align]\n top = padding_height * numerator // denominator\n bottom = padding_height - top\n else:\n top = bottom = 0\n\n return left, top, right, bottom", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 6290}, "tests/test_geometry.py::31": {"resolved_imports": ["src/term_image/geometry.py"], "used_names": ["RawSize"], "enclosing_function": "test_instance_type", "extracted_code": "# Source: src/term_image/geometry.py\nclass RawSize(NamedTuple):\n \"\"\"The dimensions of a rectangular region.\n\n Args:\n width: The horizontal dimension\n height: The vertical dimension\n\n NOTE:\n * A dimension may be non-positive but the validity and meaning would be\n determined by the receiving interface.\n * This is a subclass of :py:class:`tuple`. Hence, instances can be used anyway\n and anywhere tuples can.\n \"\"\"\n\n width: int\n height: int\n\n @classmethod\n def _new(cls, width: int, height: int) -> Self:\n \"\"\"Alternate constructor for internal use only.\"\"\"\n return tuple.__new__(cls, (width, height))", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 682}, "tests/test_image/test_url.py::28": {"resolved_imports": ["src/term_image/exceptions.py", "src/term_image/image/block.py", "src/term_image/image/common.py", "src/term_image/image/__init__.py"], "used_names": ["BlockImage", "ImageSource", "Size", "URLNotFoundError", "UnidentifiedImageError", "from_url", "os", "pytest"], "enclosing_function": "test_from_url", "extracted_code": "# Source: src/term_image/exceptions.py\nclass URLNotFoundError(TermImageError, FileNotFoundError):\n \"\"\"Raised for 404 errors.\"\"\"\n\n\n# Source: src/term_image/image/block.py\nclass BlockImage(TextImage):\n \"\"\"A render style using unicode half blocks and direct-color colour escape\n sequences.\n\n See :py:class:`TextImage` for the description of the constructor.\n \"\"\"\n\n @classmethod\n def is_supported(cls):\n if cls._supported is None:\n COLORTERM = os.environ.get(\"COLORTERM\") or \"\"\n TERM = os.environ.get(\"TERM\") or \"\"\n cls._supported = (\n \"truecolor\" in COLORTERM or \"24bit\" in COLORTERM or \"256color\" in TERM\n )\n\n return cls._supported\n\n def _get_render_size(self) -> Tuple[int, int]:\n return tuple(map(mul, self.rendered_size, (1, 2)))\n\n @staticmethod\n def _pixels_cols(\n *, pixels: Optional[int] = None, cols: Optional[int] = None\n ) -> int:\n return pixels if pixels is not None else cols\n\n @staticmethod\n def _pixels_lines(\n *, pixels: Optional[int] = None, lines: Optional[int] = None\n ) -> int:\n return ceil(pixels / 2) if pixels is not None else lines * 2\n\n def _render_image(\n self,\n img: PIL.Image.Image,\n alpha: Union[None, float, str],\n *,\n frame: bool = False,\n split_cells: bool = False,\n ) -> str:\n # NOTE:\n # It's more efficient to write separate strings to the buffer separately\n # than concatenate and write together.\n\n def update_buffer():\n if alpha:\n no_alpha = False\n if a_cluster1 == 0 == a_cluster2:\n buf_write(SGR_DEFAULT)\n buf_write(blank * n)\n elif a_cluster1 == 0: # up is transparent\n buf_write(SGR_DEFAULT)\n buf_write(SGR_FG_DIRECT % cluster2)\n buf_write(lower_pixel * n)\n elif a_cluster2 == 0: # down is transparent\n buf_write(SGR_DEFAULT)\n buf_write(SGR_FG_DIRECT % cluster1)\n buf_write(upper_pixel * n)\n else:\n no_alpha = True\n\n if not alpha or no_alpha:\n r, g, b = cluster2\n # Kitty does not render BG colors equal to the default BG color\n if is_on_kitty and cluster2 == bg_color:\n r += r < 255 or -1\n buf_write(SGR_BG_DIRECT % (r, g, b))\n if cluster1 == cluster2:\n buf_write(blank * n)\n else:\n buf_write(SGR_FG_DIRECT % cluster1)\n buf_write(upper_pixel * n)\n\n buffer = io.StringIO()\n buf_write = buffer.write # Eliminate attribute resolution cost\n\n bg_color = get_fg_bg_colors()[1]\n is_on_kitty = self._is_on_kitty()\n if split_cells:\n blank = \" \\0\"\n lower_pixel = LOWER_PIXEL + \"\\0\"\n upper_pixel = UPPER_PIXEL + \"\\0\"\n else:\n blank = \" \"\n lower_pixel = LOWER_PIXEL\n upper_pixel = UPPER_PIXEL\n end_of_line = SGR_DEFAULT + \"\\n\"\n\n width, height = self._get_render_size()\n frame_img = img if frame else None\n img, rgb, a = self._get_render_data(img, alpha, round_alpha=True, frame=frame)\n alpha = img.mode == \"RGBA\"\n\n # clean up (ImageIterator uses one PIL image throughout)\n if frame_img is not img:\n self._close_image(img)\n\n rgb_pairs = (\n (\n zip(rgb[x : x + width], rgb[x + width : x + width * 2]),\n (rgb[x], rgb[x + width]),\n )\n for x in range(0, len(rgb), width * 2)\n )\n a_pairs = (\n (\n zip(a[x : x + width], a[x + width : x + width * 2]),\n (a[x], a[x + width]),\n )\n for x in range(0, len(a), width * 2)\n )\n\n row_no = 0\n # Two rows of pixels per line\n for (rgb_pair, (cluster1, cluster2)), (a_pair, (a_cluster1, a_cluster2)) in zip(\n rgb_pairs, a_pairs\n ):\n row_no += 2\n n = 0\n for (px1, px2), (a1, a2) in zip(rgb_pair, a_pair):\n # Color-code characters and write to buffer\n # when upper and/or lower pixel color/alpha-level changes\n if not (alpha and a1 == a_cluster1 == 0 == a_cluster2 == a2) and (\n px1 != cluster1\n or px2 != cluster2\n or alpha\n and (\n # From non-transparent to transparent\n a_cluster1 != a1 == 0\n or a_cluster2 != a2 == 0\n # From transparent to non-transparent\n or 0 == a_cluster1 != a1\n or 0 == a_cluster2 != a2\n )\n ):\n update_buffer()\n cluster1 = px1\n cluster2 = px2\n if alpha:\n a_cluster1 = a1\n a_cluster2 = a2\n n = 0\n n += 1\n\n update_buffer() # Rest of the line\n if split_cells:\n # Set the last \"\\0\" to be overwritten by the next byte\n buffer.seek(buffer.tell() - 1)\n if row_no < height: # last line not yet rendered\n buf_write(end_of_line)\n\n buf_write(SGR_DEFAULT) # Reset color after last line\n\n with buffer:\n return buffer.getvalue()\n\n\n# Source: src/term_image/image/common.py\nclass ImageSource(Enum):\n \"\"\"Image source type.\"\"\"\n\n #: The instance was derived from a path to a local image file.\n #:\n #: :meta hide-value:\n FILE_PATH = SourceAttr(\"_source\")\n\n #: The instance was derived from a PIL image instance.\n #:\n #: :meta hide-value:\n PIL_IMAGE = SourceAttr(\"_source\")\n\n #: The instance was derived from an image URL.\n #:\n #: :meta hide-value:\n URL = SourceAttr(\"_url\")\n\nclass Size(Enum):\n \"\"\"Enumeration for :term:`automatic sizing`.\"\"\"\n\n #: Equivalent to :py:attr:`ORIGINAL` if it will fit into the\n #: :term:`frame size`, else :py:attr:`FIT`.\n #:\n #: :meta hide-value:\n AUTO = Hidden()\n\n #: The image size is set to fit optimally **within** the :term:`frame size`.\n #:\n #: :meta hide-value:\n FIT = Hidden()\n\n #: The size is set such that the width is exactly the :term:`frame width`,\n #: regardless of the :term:`cell ratio`.\n #:\n #: :meta hide-value:\n FIT_TO_WIDTH = Hidden()\n\n #: The image size is set such that the image is rendered with as many pixels as the\n #: the original image consists of.\n #:\n #: :meta hide-value:\n ORIGINAL = Hidden()\n\n\n# Source: src/term_image/image/__init__.py\ndef from_url(\n url: str,\n **kwargs: Union[None, int],\n) -> BaseImage:\n \"\"\"Creates an image instance from an image URL.\n\n Returns:\n An instance of the automatically selected image render style (as returned by\n :py:func:`auto_image_class`).\n\n Same arguments and raised exceptions as :py:meth:`BaseImage.from_url`.\n \"\"\"\n return auto_image_class().from_url(url, **kwargs)", "n_imports_parsed": 6, "n_files_resolved": 4, "n_chars_extracted": 7364}, "tests/widget/urwid/test_screen.py::302": {"resolved_imports": ["src/term_image/__init__.py", "src/term_image/_ctlseqs.py", "src/term_image/image/block.py", "src/term_image/image/iterm2.py", "src/term_image/image/kitty.py", "src/term_image/widget/_urwid.py"], "used_names": ["get_terminal_name_version", "set_terminal_name_version"], "enclosing_function": "test_move_top_widget", "extracted_code": "", "n_imports_parsed": 10, "n_files_resolved": 6, "n_chars_extracted": 0}, "tests/test_top_level.py::34": {"resolved_imports": ["src/term_image/__init__.py", "src/term_image/utils.py", "src/term_image/exceptions.py", "src/term_image/geometry.py"], "used_names": ["get_cell_ratio", "pytest", "reset_cell_size_ratio", "set_cell_ratio"], "enclosing_function": "test_valid", "extracted_code": "# Source: src/term_image/__init__.py\ndef get_cell_ratio() -> float:\n \"\"\"Returns the global :term:`cell ratio`.\n\n .. seealso:: :py:func:`set_cell_ratio`.\n \"\"\"\n # `(1, 2)` is a fallback in case the terminal doesn't respond in time\n return _cell_ratio or truediv(*(get_cell_size() or (1, 2)))\n\ndef set_cell_ratio(ratio: float | AutoCellRatio) -> None:\n \"\"\"Sets the global :term:`cell ratio`.\n\n Args:\n ratio: Can be one of the following values.\n\n * A positive :py:class:`float` value.\n * :py:attr:`AutoCellRatio.FIXED`, the ratio is immediately determined from\n the :term:`active terminal`.\n * :py:attr:`AutoCellRatio.DYNAMIC`, the ratio is determined from the\n :term:`active terminal` whenever :py:func:`get_cell_ratio` is called,\n though with some caching involved, such that the ratio is re-determined\n only if the terminal size changes.\n\n Raises:\n ValueError: *ratio* is a non-positive :py:class:`float`.\n term_image.exceptions.TermImageError: Auto cell ratio is not supported\n in the :term:`active terminal` or on the current platform.\n\n This value is taken into consideration when setting image sizes for **text-based**\n render styles, in order to preserve the aspect ratio of images drawn to the\n terminal.\n\n NOTE:\n Changing the cell ratio does not automatically affect any image that has a\n :term:`fixed size`. For a change in cell ratio to take effect, the image's\n size has to be re-set.\n\n IMPORTANT:\n See :ref:`auto-cell-ratio` for details about the auto modes.\n \"\"\"\n global _cell_ratio\n\n if isinstance(ratio, AutoCellRatio):\n if AutoCellRatio.is_supported is None:\n AutoCellRatio.is_supported = get_cell_size() is not None\n\n if not AutoCellRatio.is_supported:\n raise TermImageError(\n \"Auto cell ratio is not supported in the active terminal or on the \"\n \"current platform\"\n )\n elif ratio is AutoCellRatio.FIXED:\n # `(1, 2)` is a fallback in case the terminal doesn't respond in time\n _cell_ratio = truediv(*(get_cell_size() or (1, 2)))\n else:\n _cell_ratio = None\n else:\n if ratio <= 0.0:\n raise arg_value_error_range(\"ratio\", ratio)\n _cell_ratio = ratio", "n_imports_parsed": 6, "n_files_resolved": 4, "n_chars_extracted": 2390}, "tests/test_image/test_iterm2.py::583": {"resolved_imports": ["src/term_image/__init__.py", "src/term_image/_ctlseqs.py", "src/term_image/exceptions.py", "src/term_image/image/__init__.py", "src/term_image/image/iterm2.py"], "used_names": ["GifImageFile", "Image", "PngImageFile", "WebPImageFile", "io", "standard_b64decode"], "enclosing_function": "decode_image", "extracted_code": "", "n_imports_parsed": 15, "n_files_resolved": 5, "n_chars_extracted": 0}, "tests/render/test_iterator.py::455": {"resolved_imports": ["src/term_image/geometry.py", "src/term_image/padding.py", "src/term_image/render/_iterator.py", "src/term_image/renderable/_enum.py", "src/term_image/renderable/_renderable.py", "src/term_image/renderable/_types.py"], "used_names": ["IndefiniteSpace", "RenderIterator", "Seek", "pytest"], "enclosing_function": "test_indefinite", "extracted_code": "# Source: src/term_image/render/_iterator.py\nclass RenderIterator:\n \"\"\"An iterator for efficient iteration over :term:`rendered` frames of an\n :term:`animated` renderable.\n\n Args:\n renderable: An animated renderable.\n render_args: Render arguments.\n padding: :term:`Render output` padding.\n loops: The number of times to go over all frames.\n\n * ``< 0`` -> loop infinitely.\n * ``0`` -> invalid.\n * ``> 0`` -> loop the given number of times.\n\n .. note::\n The value is ignored and taken to be ``1`` (one), if *renderable* has\n :py:class:`~term_image.renderable.FrameCount.INDEFINITE` frame count.\n\n cache: Determines if :term:`rendered` frames are cached.\n\n If the value is ``True`` or a positive integer greater than or equal to the\n frame count of *renderable*, caching is enabled. Otherwise i.e ``False`` or\n a positive integer less than the frame count, caching is disabled.\n\n .. note::\n The value is ignored and taken to be ``False``, if *renderable* has\n :py:class:`~term_image.renderable.FrameCount.INDEFINITE` frame count.\n\n Raises:\n ValueError: An argument has an invalid value.\n IncompatibleRenderArgsError: Incompatible render arguments.\n\n The iterator yields a :py:class:`~term_image.renderable.Frame` instance on every\n iteration.\n\n NOTE:\n * Seeking the underlying renderable\n (via :py:meth:`Renderable.seek() `)\n does not affect an iterator, use :py:meth:`RenderIterator.seek` instead.\n Likewise, the iterator does not modify the underlying renderable's current\n frame number.\n * Changes to the underlying renderable's :term:`render size` does not affect\n an iterator's :term:`render outputs`, use :py:meth:`set_render_size` instead.\n * Changes to the underlying renderable's\n :py:attr:`~term_image.renderable.Renderable.frame_duration` does not affect\n the value yiedled by an iterator, the value when initializing the iterator\n is what it will use.\n * :py:exc:`StopDefiniteIterationError` is raised when a renderable with\n *definite* frame count raises :py:exc:`StopIteration` when rendering a frame.\n\n .. seealso::\n\n :py:meth:`Renderable.__iter__() `\n Renderables are iterable\n\n :ref:`render-iterator-ext-api`\n :py:class:`RenderIterator`\\\\ 's Extension API\n \"\"\"\n\n # Instance Attributes ======================================================\n\n loop: int\n \"\"\"Iteration loop countdown\n\n * A negative integer, if iteration is infinite.\n * Otherwise, the current iteration loop countdown value.\n\n * Starts from the value of the *loops* constructor argument,\n * decreases by one upon rendering the first frame of every loop after the\n first,\n * and ends at zero after the iterator is exhausted.\n\n NOTE:\n Modifying this doesn't affect the iterator.\n \"\"\"\n\n _cached: bool\n _closed: bool\n _finalize_data: bool\n _iterator: Generator[Frame, None, None]\n _loops: int\n _padding: Padding\n _padded_size: Size\n _render_args: RenderArgs\n _render_data: RenderData\n _renderable: Renderable\n _renderable_data: RenderableData\n\n # Special Methods ==========================================================\n\n def __init__(\n self,\n renderable: Renderable,\n render_args: RenderArgs | None = None,\n padding: Padding = ExactPadding(),\n loops: int = 1,\n cache: bool | int = 100,\n ) -> None:\n self._init(renderable, render_args, padding, loops, cache)\n self._iterator, self._padding = renderable._init_render_(\n self._iterate, render_args, padding, iteration=True, finalize=False\n )\n self._finalize_data = True\n next(self._iterator)\n\n def __del__(self) -> None:\n try:\n self.close()\n except AttributeError:\n pass\n\n def __iter__(self) -> Self:\n return self\n\n def __next__(self) -> Frame:\n try:\n return next(self._iterator)\n except StopIteration:\n self.close()\n raise StopIteration(\"Iteration has ended\") from None\n except AttributeError:\n if self._closed:\n raise StopIteration(\"This iterator has been finalized\") from None\n else:\n self.close()\n raise\n except Exception:\n self.close()\n raise\n\n def __repr__(self) -> str:\n return (\n f\"<{type(self).__name__}: \"\n f\"type(renderable)={type(self._renderable).__name__}, \"\n f\"frame_count={self._renderable.frame_count}, loops={self._loops}, \"\n f\"loop={self.loop}, cached={self._cached}>\"\n )\n\n # Public Methods ===========================================================\n\n def close(self) -> None:\n \"\"\"Finalizes the iterator and releases resources used.\n\n NOTE:\n This method is automatically called when the iterator is exhausted or\n garbage-collected but it's recommended to call it manually if iteration\n is ended prematurely (i.e before the iterator itself is exhausted),\n especially if frames are cached.\n\n This method is safe for multiple invocations.\n \"\"\"\n if not self._closed:\n self._iterator.close()\n del self._iterator\n if self._finalize_data:\n self._render_data.finalize()\n del self._render_data\n self._closed = True\n\n def seek(self, offset: int, whence: Seek = Seek.START) -> None:\n \"\"\"Sets the frame to be rendered on the next iteration, without affecting\n the loop count.\n\n Args:\n offset: Frame offset (relative to *whence*).\n whence: Reference position for *offset*.\n\n Raises:\n FinalizedIteratorError: The iterator has been finalized.\n ValueError: *offset* is out of range.\n\n The value range for *offset* depends on the\n :py:attr:`~term_image.renderable.Renderable.frame_count` of the underlying\n renderable and *whence*:\n\n .. list-table:: *definite* frame count\n :align: left\n :header-rows: 1\n :width: 90%\n :widths: auto\n\n * - *whence*\n - Valid value range for *offset*\n\n * - :py:attr:`~term_image.renderable.Seek.START`\n - ``0`` <= *offset*\n < :py:attr:`~term_image.renderable.Renderable.frame_count`\n * - :py:attr:`~term_image.renderable.Seek.CURRENT`\n - -*next_frame_number* [#ri-nf]_ <= *offset*\n < :py:attr:`~term_image.renderable.Renderable.frame_count`\n - *next_frame_number*\n * - :py:attr:`~term_image.renderable.Seek.END`\n - -:py:attr:`~term_image.renderable.Renderable.frame_count` < *offset*\n <= ``0``\n\n .. list-table:: :py:attr:`~term_image.renderable.FrameCount.INDEFINITE` frame\n count\n :align: left\n :header-rows: 1\n :width: 90%\n :widths: auto\n\n * - *whence*\n - Valid value range for *offset*\n\n * - :py:attr:`~term_image.renderable.Seek.START`\n - ``0`` <= *offset*\n * - :py:attr:`~term_image.renderable.Seek.CURRENT`\n - *any value*\n * - :py:attr:`~term_image.renderable.Seek.END`\n - *offset* <= ``0``\n\n NOTE:\n If the underlying renderable has *definite* frame count, seek operations\n have **immeditate** effect. Hence, multiple consecutive seek operations,\n starting with any kind and followed by one or more with *whence* =\n :py:attr:`~term_image.renderable.Seek.CURRENT`, between any two\n consecutive renders have a **cumulative** effect. In particular, any seek\n operation with *whence* = :py:attr:`~term_image.renderable.Seek.CURRENT`\n is relative to the frame to be rendered next [#ri-nf]_.\n\n .. collapse:: Example\n\n >>> animated_renderable.frame_count\n 10\n >>> render_iter = RenderIterator(animated_renderable) # next = 0\n >>> render_iter.seek(5) # next = 5\n >>> next(render_iter).number # next = 5 + 1 = 6\n 5\n >>> # cumulative\n >>> render_iter.seek(2, Seek.CURRENT) # next = 6 + 2 = 8\n >>> render_iter.seek(-4, Seek.CURRENT) # next = 8 - 4 = 4\n >>> next(render_iter).number # next = 4 + 1 = 5\n 4\n >>> # cumulative\n >>> render_iter.seek(7) # next = 7\n >>> render_iter.seek(1, Seek.CURRENT) # next = 7 + 1 = 8\n >>> render_iter.seek(-5, Seek.CURRENT) # next = 8 - 5 = 3\n >>> next(render_iter).number # next = 3 + 1 = 4\n 3\n >>> # NOT cumulative\n >>> render_iter.seek(3, Seek.CURRENT) # next = 4 + 3 = 7\n >>> render_iter.seek(2) # next = 2\n >>> next(render_iter).number # next = 2 + 1 = 3\n 2\n\n On the other hand, if the underlying renderable has\n :py:attr:`~term_image.renderable.FrameCount.INDEFINITE` frame count, seek\n operations don't take effect **until the next render**. Hence, multiple\n consecutive seek operations between any two consecutive renders do **not**\n have a **cumulative** effect; rather, only **the last one** takes effect.\n In particular, any seek operation with *whence* =\n :py:attr:`~term_image.renderable.Seek.CURRENT` is relative to the frame\n after that which was rendered last.\n\n .. collapse:: Example\n\n >>> animated_renderable.frame_count is FrameCount.INDEFINITE\n True\n >>> # iterating normally without seeking\n >>> [frame.render_output for frame in animated_renderable]\n ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', ...]\n >>>\n >>> # Assuming the renderable implements all kinds of seek operations\n >>> render_iter = RenderIterator(animated_renderable) # next = 0\n >>> render_iter.seek(5) # next = 5\n >>> next(render_iter).render_output # next = 5 + 1 = 6\n '5'\n >>> render_iter.seek(2, Seek.CURRENT) # next = 6 + 2 = 8\n >>> render_iter.seek(-4, Seek.CURRENT) # next = 6 - 4 = 2\n >>> next(render_iter).render_output # next = 2 + 1 = 3\n '2'\n >>> render_iter.seek(7) # next = 7\n >>> render_iter.seek(3, Seek.CURRENT) # next = 3 + 3 = 6\n >>> next(render_iter).render_output # next = 6 + 1 = 7\n '6'\n\n A renderable with :py:attr:`~term_image.renderable.FrameCount.INDEFINITE`\n frame count may not support/implement all kinds of seek operations or any\n at all. If the underlying renderable doesn't support/implement a given\n seek operation, the seek operation should simply have no effect on\n iteration i.e the next frame should be the one after that which was\n rendered last. See each :term:`render class` that implements\n :py:attr:`~term_image.renderable.FrameCount.INDEFINITE` frame count for\n the seek operations it supports and any other specific related details.\n \"\"\"\n if self._closed:\n raise FinalizedIteratorError(\"This iterator has been finalized\") from None\n\n frame_count = self._renderable.frame_count\n renderable_data = self._renderable_data\n if frame_count is FrameCount.INDEFINITE:\n if whence is Seek.START and offset < 0 or whence is Seek.END and offset > 0:\n raise arg_value_error_range(\"offset\", offset, f\"whence={whence.name}\")\n renderable_data.update(frame_offset=offset, seek_whence=whence)\n else:\n frame = (\n offset\n if whence is Seek.START\n else (\n renderable_data.frame_offset + offset\n if whence is Seek.CURRENT\n else frame_count + offset - 1\n )\n )\n if not 0 <= frame < frame_count:\n raise arg_value_error_range(\n \"offset\",\n offset,\n (\n f\"whence={whence.name}, frame_count={frame_count}\"\n + (\n f\", next={renderable_data.frame_offset}\"\n if whence is Seek.CURRENT\n else \"\"\n )\n ),\n )\n renderable_data.update(frame_offset=frame, seek_whence=Seek.START)\n\n def set_frame_duration(self, duration: int | FrameDuration) -> None:\n \"\"\"Sets the frame duration.\n\n Args:\n duration: Frame duration (see\n :py:attr:`~term_image.renderable.Renderable.frame_duration`).\n\n Raises:\n FinalizedIteratorError: The iterator has been finalized.\n ValueError: *duration* is out of range.\n\n NOTE:\n Takes effect from the next [#ri-nf]_ rendered frame.\n \"\"\"\n if self._closed:\n raise FinalizedIteratorError(\"This iterator has been finalized\") from None\n\n if isinstance(duration, int) and duration <= 0:\n raise arg_value_error_range(\"duration\", duration)\n\n self._renderable_data.duration = duration\n\n def set_padding(self, padding: Padding) -> None:\n \"\"\"Sets the :term:`render output` padding.\n\n Args:\n padding: Render output padding.\n\n Raises:\n FinalizedIteratorError: The iterator has been finalized.\n\n NOTE:\n Takes effect from the next [#ri-nf]_ rendered frame.\n \"\"\"\n if self._closed:\n raise FinalizedIteratorError(\"This iterator has been finalized\") from None\n\n self._padding = (\n padding.resolve(get_terminal_size())\n if isinstance(padding, AlignedPadding) and padding.relative\n else padding\n )\n self._padded_size = padding.get_padded_size(self._renderable_data.size)\n\n def set_render_args(self, render_args: RenderArgs) -> None:\n \"\"\"Sets the render arguments.\n\n Args:\n render_args: Render arguments.\n\n Raises:\n FinalizedIteratorError: The iterator has been finalized.\n IncompatibleRenderArgsError: Incompatible render arguments.\n\n NOTE:\n Takes effect from the next [#ri-nf]_ rendered frame.\n \"\"\"\n if self._closed:\n raise FinalizedIteratorError(\"This iterator has been finalized\") from None\n\n render_cls = type(self._renderable)\n self._render_args = (\n render_args\n if render_args.render_cls is render_cls\n # Validate compatibility (and convert, if compatible)\n else RenderArgs(render_cls, render_args)\n )\n\n def set_render_size(self, render_size: Size) -> None:\n \"\"\"Sets the :term:`render size`.\n\n Args:\n render_size: Render size.\n\n Raises:\n FinalizedIteratorError: The iterator has been finalized.\n\n NOTE:\n Takes effect from the next [#ri-nf]_ rendered frame.\n \"\"\"\n if self._closed:\n raise FinalizedIteratorError(\"This iterator has been finalized\") from None\n\n self._renderable_data.size = render_size\n self._padded_size = self._padding.get_padded_size(render_size)\n\n # Extension methods ========================================================\n\n @classmethod\n def _from_render_data_(\n cls,\n renderable: Renderable,\n render_data: RenderData,\n render_args: RenderArgs | None = None,\n padding: Padding = ExactPadding(),\n *args: Any,\n finalize: bool = True,\n **kwargs: Any,\n ) -> Self:\n \"\"\"Constructs an iterator with pre-generated render data.\n\n Args:\n renderable: An animated renderable.\n render_data: Render data.\n render_args: Render arguments.\n args: Other positional arguments accepted by the class constructor.\n finalize: Whether *render_data* is finalized along with the iterator.\n kwargs: Other keyword arguments accepted by the class constructor.\n\n Returns:\n A new iterator instance.\n\n Raises the same exceptions as the class constructor.\n\n NOTE:\n *render_data* may be modified by the iterator or the underlying renderable.\n \"\"\"\n new = cls.__new__(cls)\n new._init(renderable, render_args, padding, *args, **kwargs)\n\n if render_data.render_cls is not type(renderable):\n raise arg_value_error_msg(\n \"Invalid render data for renderable of type \"\n f\"{type(renderable).__name__!r}\",\n render_data,\n )\n if render_data.finalized:\n raise ValueError(\"The render data has been finalized\")\n if not render_data[Renderable].iteration:\n raise arg_value_error_msg(\"Invalid render data for iteration\", render_data)\n\n if not (render_args and render_args.render_cls is type(renderable)):\n # Validate compatibility (and convert, if compatible)\n render_args = RenderArgs(type(renderable), render_args)\n\n new._padding = (\n padding.resolve(get_terminal_size())\n if isinstance(padding, AlignedPadding) and padding.relative\n else padding\n )\n new._iterator = new._iterate(render_data, render_args)\n new._finalize_data = finalize\n next(new._iterator)\n\n return new\n\n # Private Methods ==========================================================\n\n def _init(\n self,\n renderable: Renderable,\n render_args: RenderArgs | None = None,\n padding: Padding = ExactPadding(),\n loops: int = 1,\n cache: bool | int = 100,\n ) -> None:\n \"\"\"Partially initializes an instance.\n\n Performs the part of the initialization common to all constructors.\n \"\"\"\n if not renderable.animated:\n raise arg_value_error_msg(\"'renderable' is not animated\", renderable)\n if not loops:\n raise arg_value_error(\"loops\", loops)\n if False is not cache <= 0:\n raise arg_value_error_range(\"cache\", cache)\n\n indefinite = renderable.frame_count is FrameCount.INDEFINITE\n self._closed = False\n self._renderable = renderable\n self.loop = self._loops = 1 if indefinite else loops\n self._cached = (\n False\n if indefinite\n else (\n cache\n # `isinstance` is much costlier on failure and `bool` cannot be\n # subclassed\n if type(cache) is bool\n else renderable.frame_count <= cache # type: ignore[operator]\n )\n )\n\n def _iterate(\n self,\n render_data: RenderData,\n render_args: RenderArgs,\n ) -> Generator[Frame, None, None]:\n \"\"\"Performs the actual render iteration operation.\"\"\"\n # Instance init completion\n self._render_data = render_data\n self._render_args = render_args\n renderable_data: RenderableData\n self._renderable_data = renderable_data = render_data[Renderable]\n self._padded_size = self._padding.get_padded_size(renderable_data.size)\n\n # Setup\n renderable = self._renderable\n frame_count = renderable.frame_count\n if frame_count is FrameCount.INDEFINITE:\n frame_count = 1\n definite = frame_count > 1\n loop = self.loop\n CURRENT = Seek.CURRENT\n renderable_data.frame_offset = 0\n cache: list[tuple[Frame | None, Size, int | FrameDuration, RenderArgs]] | None\n cache = (\n [(None,) * 4] * frame_count # type: ignore[list-item]\n if self._cached\n else None\n )\n\n # Initial dummy frame, yielded but unused by initializers.\n # Acts as a breakpoint between completion of instance init + iteration setup\n # and render iteration.\n yield DUMMY_FRAME\n\n # Render iteration\n frame_no = renderable_data.frame_offset * definite\n while loop:\n while frame_no < frame_count:\n if cache:\n frame = (cache_entry := cache[frame_no])[0]\n frame_details = cache_entry[1:]\n else:\n frame = None\n\n if not frame or frame_details != (\n renderable_data.size,\n renderable_data.duration,\n self._render_args,\n ):\n # NOTE: Re-render is required even when only `duration` changes\n # and the new value is *static* because frame duration may affect\n # the render output of some renderables.\n try:\n frame = renderable._render_(render_data, self._render_args)\n except StopIteration as exc:\n if definite:\n raise StopDefiniteIterationError(\n f\"{renderable!r} with definite frame count raised \"\n \"`StopIteration` when rendering a frame\"\n ) from exc\n self.loop = 0\n return\n\n if cache:\n cache[frame_no] = (\n frame,\n renderable_data.size,\n renderable_data.duration,\n self._render_args,\n )\n\n if self._padded_size != frame.render_size:\n frame = Frame(\n frame.number,\n frame.duration,\n self._padded_size,\n self._padding.pad(frame.render_output, frame.render_size),\n )\n\n if definite:\n renderable_data.frame_offset += 1\n elif (\n renderable_data.frame_offset\n or renderable_data.seek_whence != CURRENT\n ): # was seeked\n renderable_data.update(frame_offset=0, seek_whence=CURRENT)\n\n yield frame\n\n if definite:\n frame_no = renderable_data.frame_offset\n\n # INDEFINITE can never reach here\n frame_no = renderable_data.frame_offset = 0\n if loop > 0: # Avoid infinitely large negative numbers\n self.loop = loop = loop - 1\n\n\n# Source: src/term_image/renderable/_enum.py\nclass Seek(IntEnum):\n \"\"\"Relative seek enumeration\n\n TIP:\n * Each member's value is that of the corresponding\n :py:data:`os.SEEK_* ` constant.\n * Every member can be used directly as an integer since\n :py:class:`enum.IntEnum` is a base class.\n\n .. seealso::\n :py:meth:`Renderable.seek`,\n :py:meth:`RenderIterator.seek() `\n \"\"\"\n\n START = SET = os.SEEK_SET\n \"\"\"Start position\"\"\"\n\n CURRENT = CUR = os.SEEK_CUR\n \"\"\"Current position\"\"\"\n\n END = os.SEEK_END\n \"\"\"End position\"\"\"", "n_imports_parsed": 9, "n_files_resolved": 6, "n_chars_extracted": 23994}, "tests/renderable/test_renderable.py::1664": {"resolved_imports": ["src/term_image/_ctlseqs.py", "src/term_image/geometry.py", "src/term_image/padding.py", "src/term_image/renderable/_enum.py", "src/term_image/renderable/_exceptions.py", "src/term_image/renderable/_renderable.py", "src/term_image/renderable/_types.py"], "used_names": ["Renderable"], "enclosing_function": "test_render_data", "extracted_code": "# Source: src/term_image/renderable/_renderable.py\nclass Renderable(metaclass=RenderableMeta, _base=True):\n \"\"\"A renderable.\n\n Args:\n frame_count: Number of frames. If it's a\n\n * positive integer, the number of frames is as given.\n * :py:class:`~term_image.renderable.FrameCount` enum member, see the\n member's description.\n\n If equal to 1 (one), the renderable is non-animated.\n Otherwise, it is animated.\n\n frame_duration: The duration of a frame. If it's a\n\n * positive integer, it implies a static duration (in **milliseconds**)\n i.e the same duration applies to every frame.\n * :py:class:`~term_image.renderable.FrameDuration` enum member, see the\n member's description.\n\n This argument is ignored if *frame_count* equals 1 (one)\n i.e the renderable is non-animated.\n\n Raises:\n ValueError: An argument has an invalid value.\n\n ATTENTION:\n This is an abstract base class. Hence, only **concrete** subclasses can be\n instantiated.\n\n .. seealso::\n\n :ref:`renderable-ext-api`\n :py:class:`Renderable`\\\\ 's Extension API\n \"\"\"\n\n # Class Attributes =========================================================\n\n # Initialized by `RenderableMeta` and may be updated by `ArgsNamespaceMeta`\n Args: ClassVar[type[ArgsNamespace] | None]\n \"\"\":term:`Render class`\\\\ -specific render arguments.\n\n This is either:\n\n - a render argument namespace class (subclass of :py:class:`ArgsNamespace`)\n associated [#an-ass]_ with the render class, or\n - :py:data:`None`, if the render class has no render arguments.\n\n If this is a class, an instance of it (or a subclass thereof) is contained within\n any :py:class:`RenderArgs` instance associated [#ra-ass]_ with the render class or\n any of its subclasses. Also, an instance of this class (or a subclass of it) is\n returned by :py:meth:`render_args[render_cls]\n `; where *render_args* is\n an instance of :py:class:`~term_image.renderable.RenderArgs` as previously\n described and *render_cls* is the render class with which this namespace class\n is associated [#an-ass]_.\n\n .. collapse:: Example\n\n >>> class Foo(Renderable):\n ... pass\n ...\n ... class FooArgs(ArgsNamespace, render_cls=Foo):\n ... foo: str | None = None\n ...\n >>> Foo.Args is FooArgs\n True\n >>>\n >>> # default\n >>> foo_args = Foo.Args()\n >>> foo_args\n FooArgs(foo=None)\n >>> foo_args.foo is None\n True\n >>>\n >>> render_args = RenderArgs(Foo)\n >>> render_args[Foo]\n FooArgs(foo=None)\n >>>\n >>> # non-default\n >>> foo_args = Foo.Args(\"FOO\")\n >>> foo_args\n FooArgs(foo='FOO')\n >>> foo_args.foo\n 'FOO'\n >>>\n >>> render_args = RenderArgs(Foo, foo_args.update(foo=\"bar\"))\n >>> render_args[Foo]\n FooArgs(foo='bar')\n\n On the other hand, if this is :py:data:`None`, it implies the render class has no\n render arguments.\n\n .. collapse:: Example\n\n >>> class Bar(Renderable):\n ... pass\n ...\n >>> Bar.Args is None\n True\n >>> render_args = RenderArgs(Bar)\n >>> render_args[Bar]\n Traceback (most recent call last):\n ...\n NoArgsNamespaceError: 'Bar' has no render arguments\n \"\"\"\n\n # Initialized by `RenderableMeta` and may be updated by `DataNamespaceMeta`\n _Data_: ClassVar[type[DataNamespace] | None]\n \"\"\":term:`Render class`\\\\ -specific render data.\n\n This is either:\n\n - a render data namespace class (subclass of :py:class:`DataNamespace`)\n associated [#dn-ass]_ with the render class, or\n - :py:data:`None`, if the render class has no render data.\n\n If this is a class, an instance of it (or a subclass thereof) is contained within\n any :py:class:`RenderData` instance associated [#rd-ass]_ with the render class or\n any of its subclasses. Also, an instance of this class (or a subclass of it) is\n returned by :py:meth:`render_data[render_cls]\n `; where *render_data* is\n an instance of :py:class:`~term_image.renderable.RenderData` as previously\n described and *render_cls* is the render class with which this namespace class\n is associated [#dn-ass]_.\n\n .. collapse:: Example\n\n >>> class Foo(Renderable):\n ... pass\n ...\n ... class _Data_(DataNamespace, render_cls=Foo):\n ... foo: str | None\n ...\n >>> Foo._Data_ is FooData\n True\n >>>\n >>> foo_data = Foo._Data_()\n >>> foo_data\n >\n >>> foo_data.foo\n Traceback (most recent call last):\n ...\n UninitializedDataFieldError: The render data field 'foo' of 'Foo' has not \\\nbeen initialized\n >>>\n >>> foo_data.foo = \"FOO\"\n >>> foo_data\n \n >>> foo_data.foo\n 'FOO'\n >>>\n >>> render_data = RenderData(Foo)\n >>> render_data[Foo]\n >\n >>>\n >>> render_data[Foo].foo = \"bar\"\n >>> render_data[Foo]\n \n\n On the other hand, if this is :py:data:`None`, it implies the render class has no\n render data.\n\n .. collapse:: Example\n\n >>> class Bar(Renderable):\n ... pass\n ...\n >>> Bar._Data_ is None\n True\n >>>\n >>> render_data = RenderData(Bar)\n >>> render_data[Bar]\n Traceback (most recent call last):\n ...\n NoDataNamespaceError: 'Bar' has no render data\n\n .. seealso::\n\n :py:class:`~term_image.renderable.RenderableData`\n Render data for :py:class:`~term_image.renderable.Renderable`.\n \"\"\"\n\n _EXPORTED_ATTRS_: ClassVar[tuple[str, ...]]\n \"\"\"Exported attributes.\n\n This specifies class attributes defined by the class (not a parent) on itself\n **but not** its subclasses which should be exported to definitions of the class\n in subprocesses.\n\n These attributes are typically assigned using ``__class__.*`` within methods.\n\n NOTE:\n * Defining this is optional.\n * The attributes are exported for a class if and only if they are defined\n on that class when starting a subprocess.\n * The attributes are exported only for subprocesses started via\n :py:class:`multiprocessing.Process`.\n\n TIP:\n This can be used to export \"private\" attributes of the class across\n subprocesses.\n \"\"\"\n\n _EXPORTED_DESCENDANT_ATTRS_: ClassVar[tuple[str, ...]]\n \"\"\"Exported :term:`descendant` attributes.\n\n This specifies class attributes defined by the class (not a parent) on itself\n **and** its subclasses (i.e :term:`descendant` attributes) which should be exported\n to definitions of the class and its subclasses in subprocesses.\n\n These attributes are typically assigned using ``cls.*`` within class methods.\n\n This extends the exported descendant attributes of parent classes i.e all\n exported descendant attributes of a class are also exported for its subclasses.\n\n NOTE:\n * Defining this is optional.\n * The attributes are exported for a class if and only if they are defined\n on that class when starting a subprocess.\n * The attributes are exported only for subprocesses started via\n :py:class:`multiprocessing.Process`.\n\n TIP:\n This can be used to export \"private\" :term:`descendant` attributes of the\n class across subprocesses.\n \"\"\"\n\n _ALL_DEFAULT_ARGS: ClassVar[MappingProxyType[type[Renderable], ArgsNamespace]]\n _RENDER_DATA_MRO: ClassVar[MappingProxyType[type[Renderable], type[DataNamespace]]]\n _ALL_EXPORTED_ATTRS: ClassVar[tuple[str, ...]]\n\n # Instance Attributes ======================================================\n\n animated: bool\n \"\"\"``True`` if the renderable is :term:`animated`. Otherwise, ``False``.\"\"\"\n\n _frame: int\n _frame_count: int | FrameCount\n _frame_duration: int | FrameDuration\n\n # Special Methods ==========================================================\n\n def __init__(\n self,\n frame_count: int | FrameCount,\n frame_duration: int | FrameDuration,\n ) -> None:\n if isinstance(frame_count, int) and frame_count < 1:\n raise arg_value_error_range(\"frame_count\", frame_count)\n\n if frame_count != 1:\n if isinstance(frame_duration, int) and frame_duration <= 0:\n raise arg_value_error_range(\"frame_duration\", frame_duration)\n self._frame_duration = frame_duration\n\n self.animated = frame_count != 1\n self._frame_count = frame_count\n self._frame = 0\n\n def __iter__(self) -> term_image.render.RenderIterator:\n \"\"\"Returns a render iterator.\n\n Returns:\n A render iterator (with frame caching disabled and all other optional\n arguments to :py:class:`~term_image.render.RenderIterator` being the\n default values).\n\n Raises:\n NonAnimatedRenderableError: The renderable is non-animated.\n\n :term:`Animated` renderables are iterable i.e they can be used with various\n means of iteration such as the ``for`` statement and iterable unpacking.\n \"\"\"\n from term_image.render import RenderIterator\n\n try:\n return RenderIterator(self, cache=False)\n except ValueError:\n raise NonAnimatedRenderableError(\n \"Non-animated renderables are not iterable\"\n ) from None\n\n def __repr__(self) -> str:\n return f\"<{type(self).__name__}: frame_count={self._frame_count}>\"\n\n def __str__(self) -> str:\n \"\"\":term:`Renders` the current frame with default arguments and no padding.\n\n Returns:\n The frame :term:`render output`.\n\n Raises:\n RenderError: An error occurred during :term:`rendering`.\n \"\"\"\n return self._init_render_(self._render_)[0].render_output\n\n # Properties ===============================================================\n\n @property\n def frame_count(self) -> int | Literal[FrameCount.INDEFINITE]:\n \"\"\"Frame count\n\n GET:\n Returns either\n\n * the number of frames the renderable has, or\n * :py:attr:`~term_image.renderable.FrameCount.INDEFINITE`.\n \"\"\"\n if self._frame_count is FrameCount.POSTPONED:\n self._frame_count = self._get_frame_count_()\n\n return self._frame_count\n\n @property\n def frame_duration(self) -> int | FrameDuration:\n \"\"\"Frame duration\n\n GET:\n Returns\n\n * a positive integer, a static duration (in **milliseconds**) i.e the\n same duration applies to every frame; or\n * :py:attr:`~term_image.renderable.FrameDuration.DYNAMIC`.\n\n SET:\n If the value is\n\n * a positive integer, it implies a static duration (in **milliseconds**)\n i.e the same duration applies to every frame.\n * :py:attr:`~term_image.renderable.FrameDuration.DYNAMIC`, see the\n enum member's description.\n\n Raises:\n NonAnimatedRenderableError: The renderable is non-animated.\n \"\"\"\n try:\n return self._frame_duration\n except AttributeError:\n if not self.animated:\n raise NonAnimatedRenderableError(\n \"Non-animated renderables have no frame duration\"\n ) from None\n raise\n\n @frame_duration.setter\n def frame_duration(self, duration: int | FrameDuration) -> None:\n if not self.animated:\n raise NonAnimatedRenderableError(\n \"Cannot set frame duration for a non-animated renderable\"\n )\n\n if isinstance(duration, int) and duration <= 0:\n raise arg_value_error_range(\"frame_duration\", duration)\n\n self._frame_duration = duration\n\n @property\n def render_size(self) -> geometry.Size:\n \"\"\":term:`Render size`\n\n GET:\n Returns the size of the renderable's :term:`render output`.\n \"\"\"\n return self._get_render_size_()\n\n # Public Methods ===========================================================\n\n def draw(\n self,\n render_args: RenderArgs | None = None,\n padding: Padding = AlignedPadding(0, -2),\n *,\n animate: bool = True,\n loops: int = -1,\n cache: bool | int = 100,\n check_size: bool = True,\n allow_scroll: bool = False,\n hide_cursor: bool = True,\n echo_input: bool = False,\n ) -> None:\n \"\"\"Draws the current frame or an animation to standard output.\n\n Args:\n render_args: Render arguments.\n padding: :term:`Render output` padding.\n animate: Whether to enable animation for :term:`animated` renderables.\n If disabled, only the current frame is drawn.\n loops: See :py:class:`~term_image.render.RenderIterator`\n (applies to **animations only**).\n cache: See :py:class:`~term_image.render.RenderIterator`.\n (applies to **animations only**).\n check_size: Whether to validate the padded :term:`render size` of\n **non-animations**.\n allow_scroll: Whether to validate the padded :term:`render height` of\n **non-animations**. Ignored if *check_size* is ``False``.\n hide_cursor: Whether to hide the cursor **while drawing**.\n echo_input: Whether to display input **while drawing** (applies on **Unix\n only**).\n\n .. note::\n * If disabled (default), input is not read/consumed, it's just not\n displayed.\n * If enabled, echoed input may affect cursor positioning and\n therefore, the output (especially for animations).\n\n Raises:\n RenderSizeOutofRangeError: The padded :term:`render size` can not fit into\n the :term:`terminal size`.\n IncompatibleRenderArgsError: Incompatible render arguments.\n RenderError: An error occurred during :term:`rendering`.\n\n If *check_size* is ``True`` (or it's an animation),\n\n * the padded :term:`render width` must not be greater than the\n :term:`terminal width`.\n * and *allow_scroll* is ``False`` (or it's an animation), the padded\n :term:`render height` must not be greater than the :term:`terminal height`.\n\n NOTE:\n * *hide_cursor* and *echo_input* apply if and only if the output stream\n is connected to a terminal.\n * For animations (i.e animated renderables with *animate* = ``True``),\n the padded :term:`render size` is always validated.\n * Animations with **definite** frame count, **by default**, are infinitely\n looped but can be terminated with :py:data:`~signal.SIGINT`\n (``CTRL + C``), **without** raising :py:class:`KeyboardInterrupt`.\n \"\"\"\n animation = self.animated and animate\n output = sys.stdout\n not_echo_input = OS_IS_UNIX and not echo_input and output.isatty()\n hide_cursor = hide_cursor and output.isatty()\n\n # Validate size and get render data and args\n render_data: RenderData\n real_render_args: RenderArgs\n (render_data, real_render_args), padding = self._init_render_(\n lambda *args: args,\n render_args,\n padding,\n iteration=animation,\n finalize=False,\n check_size=animation or check_size,\n allow_scroll=not animation and allow_scroll,\n )\n\n if not_echo_input:\n output_fd = output.fileno()\n old_attr = termios.tcgetattr(output_fd)\n new_attr = termios.tcgetattr(output_fd)\n new_attr[3] &= ~termios.ECHO\n try:\n if hide_cursor:\n output.write(HIDE_CURSOR)\n if not_echo_input:\n termios.tcsetattr(output_fd, termios.TCSAFLUSH, new_attr)\n\n if animation:\n self._animate_(\n render_data, real_render_args, padding, loops, cache, output\n )\n else:\n frame = self._render_(render_data, real_render_args)\n padded_size = padding.get_padded_size(frame.render_size)\n render = (\n frame.render_output\n if frame.render_size == padded_size\n else padding.pad(frame.render_output, frame.render_size)\n )\n try:\n output.write(render)\n output.flush()\n except KeyboardInterrupt:\n self._handle_interrupted_draw_(\n render_data, real_render_args, output\n )\n raise\n finally:\n output.write(\"\\n\")\n if hide_cursor:\n output.write(SHOW_CURSOR)\n output.flush()\n if not_echo_input:\n termios.tcsetattr(output_fd, termios.TCSANOW, old_attr)\n render_data.finalize()\n\n def render(\n self,\n render_args: RenderArgs | None = None,\n padding: Padding = NO_PADDING,\n ) -> Frame:\n \"\"\":term:`Renders` the current frame.\n\n Args:\n render_args: Render arguments.\n padding: :term:`Render output` padding.\n\n Returns:\n The rendered frame.\n\n Raises:\n IncompatibleRenderArgsError: Incompatible render arguments.\n RenderError: An error occurred during :term:`rendering`.\n \"\"\"\n frame, padding = self._init_render_(self._render_, render_args, padding)\n padded_size = padding.get_padded_size(frame.render_size)\n\n return (\n frame\n if frame.render_size == padded_size\n else Frame(\n frame.number,\n frame.duration,\n padded_size,\n padding.pad(frame.render_output, frame.render_size),\n )\n )\n\n def seek(self, offset: int, whence: Seek = Seek.START) -> int:\n \"\"\"Sets the current frame number.\n\n Args:\n offset: Frame offset (relative to *whence*).\n whence: Reference position for *offset*.\n\n Returns:\n The new current frame number.\n\n Raises:\n IndefiniteSeekError: The renderable has\n :py:attr:`~term_image.renderable.FrameCount.INDEFINITE` frame count.\n ValueError: *offset* is out of range.\n\n The value range for *offset* depends on *whence*:\n\n .. list-table::\n :align: left\n :header-rows: 1\n :widths: auto\n\n * - *whence*\n - Valid value range for *offset*\n\n * - :py:attr:`~term_image.renderable.Seek.START`\n - ``0`` <= *offset* < :py:attr:`frame_count`\n * - :py:attr:`~term_image.renderable.Seek.CURRENT`\n - -:py:meth:`tell` <= *offset* < :py:attr:`frame_count` - :py:meth:`tell`\n * - :py:attr:`~term_image.renderable.Seek.END`\n - -:py:attr:`frame_count` < *offset* <= ``0``\n \"\"\"\n frame_count = self.frame_count\n\n if frame_count is FrameCount.INDEFINITE:\n raise IndefiniteSeekError(\n \"Cannot seek a renderable with INDEFINITE frame count\"\n )\n\n frame = (\n offset\n if whence is Seek.START\n else (\n self._frame + offset\n if whence is Seek.CURRENT\n else frame_count + offset - 1\n )\n )\n if not 0 <= frame < frame_count:\n raise arg_value_error_range(\n \"offset\",\n offset,\n (\n f\"whence={whence.name}, frame_count={frame_count}\"\n + (f\", current={self._frame}\" if whence is Seek.CURRENT else \"\")\n ),\n )\n self._frame = frame\n\n return frame\n\n def tell(self) -> int:\n \"\"\"Returns the current frame number.\n\n Returns:\n Zero, if the renderable is non-animated or has\n :py:attr:`~term_image.renderable.FrameCount.INDEFINITE` frame count.\n Otherwise, the current frame number.\n \"\"\"\n return self._frame\n\n # Extension methods ========================================================\n\n def _animate_(\n self,\n render_data: RenderData,\n render_args: RenderArgs,\n padding: Padding,\n loops: int,\n cache: bool | int,\n output: TextIO,\n ) -> None:\n \"\"\"Animates frames of a renderable.\n\n Args:\n render_data: Render data.\n render_args: Render arguments associated with the renderable's class.\n output: The text I/O stream to which rendered frames will be written.\n\n All other parameters are the same as for :py:meth:`draw`, except that\n *padding* must have **absolute** dimensions if it's an instance of\n :py:class:`~term_image.padding.AlignedPadding`.\n\n This is called by :py:meth:`draw` for animations.\n\n NOTE:\n * The base implementation does not finalize *render_data*.\n * :term:`Render size` validation is expected to have been performed by\n the caller.\n * When called by :py:meth:`draw` (at least, the base implementation),\n *loops* and *cache* wouldn't have been validated.\n \"\"\"\n from term_image.render import RenderIterator\n\n render_size: Size = render_data[Renderable].size\n height = render_size.height\n pad_left, _, _, pad_bottom = padding._get_exact_dimensions_(render_size)\n render_iter = RenderIterator._from_render_data_(\n self,\n render_data,\n render_args,\n padding,\n loops,\n False if loops == 1 else cache,\n finalize=False,\n )\n cursor_to_next_render_line = f\"\\n{cursor_forward(pad_left)}\"\n cursor_to_render_top_left = (\n f\"\\r{cursor_up(height - 1)}{cursor_forward(pad_left)}\"\n )\n write = output.write\n flush = output.flush\n first_frame_written = False\n\n try:\n # first frame\n try:\n frame = next(render_iter)\n except StopIteration: # `INDEFINITE` frame count\n return\n\n try:\n write(frame.render_output)\n flush()\n except KeyboardInterrupt:\n self._handle_interrupted_draw_(render_data, render_args, output)\n return\n else:\n # Move the cursor to the top-left cell of the region occupied by the\n # render output\n write(\n f\"\\r{cursor_up(height + pad_bottom - 1)}{cursor_forward(pad_left)}\"\n )\n flush()\n\n first_frame_written = True\n\n # Padding has been drawn with the first frame, only the actual render is\n # needed henceforth.\n render_iter.set_padding(NO_PADDING)\n\n # render next frame during previous frame's duration\n duration_ms = frame.duration\n start_ns = perf_counter_ns()\n\n for frame in render_iter: # Render next frame\n # left-over of previous frame's duration\n sleep(\n max(0, duration_ms * 10**6 - (perf_counter_ns() - start_ns)) / 10**9\n )\n\n # clear previous frame, if necessary\n self._clear_frame_(render_data, render_args, pad_left + 1, output)\n\n # draw next frame\n try:\n write(frame.render_output.replace(\"\\n\", cursor_to_next_render_line))\n flush()\n except KeyboardInterrupt:\n self._handle_interrupted_draw_(render_data, render_args, output)\n return\n\n write(cursor_to_render_top_left)\n flush()\n\n # render next frame during previous frame's duration\n start_ns = perf_counter_ns()\n duration_ms = frame.duration\n\n # left-over of last frame's duration\n sleep(max(0, duration_ms * 10**6 - (perf_counter_ns() - start_ns)) / 10**9)\n except KeyboardInterrupt:\n pass\n finally:\n render_iter.close()\n if first_frame_written:\n # Move the cursor to the last line to prevent \"overlaid\" output\n write(cursor_down(height + pad_bottom - 1))\n flush()\n\n def _clear_frame_(\n self,\n render_data: RenderData,\n render_args: RenderArgs,\n cursor_x: int,\n output: TextIO,\n ) -> None:\n \"\"\"Clears the previous frame of an animation, if necessary.\n\n Args:\n render_data: Render data.\n render_args: Render arguments.\n cursor_x: Column/horizontal position of the cursor at the point of calling\n this method.\n\n .. note:: The position is **1-based** i.e the leftmost column on the\n screen is at position 1 (one).\n\n output: The text I/O stream to which frames of the animation are being\n written.\n\n Called by the base implementation of :py:meth:`_animate_` just before drawing\n the next frame of an animation.\n\n Upon calling this method, the cursor should be positioned at the top-left-most\n cell of the region occupied by the frame render output on the terminal screen.\n\n Upon return, ensure the cursor is at the same position it was at the point of\n calling this method (at least logically, since *output* shouldn't be flushed\n yet).\n\n The base implementation does nothing.\n\n NOTE:\n * This is required only if drawing the next frame doesn't inherently\n overwrite the previous frame.\n * This is only meant (and should only be used) as a last resort since\n clearing the previous frame before drawing the next may result in\n visible flicker.\n * Ensure whatever this method does doesn't result in the screen being\n scrolled.\n\n TIP:\n To reduce flicker, it's advisable to **not** flush *output*. It will be\n flushed after writing the next frame.\n \"\"\"\n\n @classmethod\n def _finalize_render_data_(cls, render_data: RenderData) -> None:\n \"\"\"Finalizes render data.\n\n Args:\n render_data: Render data.\n\n Typically, an overriding method should\n\n * finalize the data generated by :py:meth:`_get_render_data_` of the\n **same class**, if necessary,\n * call the overridden method, passing on *render_data*.\n\n NOTE:\n * It's recommended to call :py:meth:`RenderData.finalize()\n `\n instead as that assures a single invocation of this method.\n * Any definition of this method should be safe for multiple invocations on\n the same :py:class:`~term_image.renderable.RenderData` instance, just in\n case.\n\n .. seealso::\n :py:meth:`_get_render_data_`,\n :py:meth:`RenderData.finalize()\n `,\n the *finalize* parameter of :py:meth:`_init_render_`.\n \"\"\"\n\n def _get_frame_count_(self) -> int | Literal[FrameCount.INDEFINITE]:\n \"\"\"Implements :py:attr:`~term_image.renderable.FrameCount.POSTPONED` frame\n count evaluation.\n\n Returns:\n The frame count of the renderable. See :py:attr:`frame_count`.\n\n .. note::\n Returning :py:attr:`~term_image.renderable.FrameCount.POSTPONED` or\n ``1`` (one) is invalid and may result in unexpected/undefined behaviour\n across various interfaces defined by this library (and those derived\n from them), since re-postponing evaluation is unsupported and the\n renderable would have been taken to be animated.\n\n The base implementation raises :py:class:`NotImplementedError`.\n \"\"\"\n raise NotImplementedError(\"POSTPONED frame count evaluation isn't implemented\")\n\n def _get_render_data_(self, *, iteration: bool) -> RenderData:\n \"\"\"Generates data required for rendering that's based on internal or\n external state.\n\n Args:\n iteration: Whether the render operation requiring the data involves a\n sequence of :term:`renders` (most likely of different frames), or it's\n a one-off render.\n\n Returns:\n The generated render data.\n\n The render data should include **copies** of any **variable/mutable**\n internal/external state required for rendering and other data generated from\n constant state but which should **persist** throughout a render operation\n (which may involve consecutive/repeated renders of one or more frames).\n\n May also be used to \"allocate\" and initialize storage for mutable/variable\n data specific to a render operation.\n\n Typically, an overriding method should\n\n * call the overridden method,\n * update the namespace for its defining class (i.e\n :py:meth:`render_data[__class__]\n `) within the\n :py:class:`~term_image.renderable.RenderData` instance returned by the\n overridden method,\n * return the same :py:class:`~term_image.renderable.RenderData` instance.\n\n IMPORTANT:\n The :py:class:`~term_image.renderable.RenderData` instance returned must be\n associated [#rd-ass]_ with the type of the renderable on which this method\n is called i.e ``type(self)``. This is always the case for the base\n implementation of this method.\n\n NOTE:\n This method being called doesn't mean the data generated will be used\n immediately.\n\n .. seealso::\n :py:class:`~term_image.renderable.RenderData`,\n :py:meth:`_finalize_render_data_`,\n :py:meth:`~term_image.renderable.Renderable._init_render_`.\n \"\"\"\n render_data = RenderData(type(self))\n renderable_data: RenderableData = render_data[Renderable]\n renderable_data.update(\n size=self._get_render_size_(),\n frame_offset=self._frame,\n seek_whence=Seek.START,\n iteration=iteration,\n )\n if self.animated:\n renderable_data.duration = self._frame_duration\n\n return render_data\n\n @abstractmethod\n def _get_render_size_(self) -> geometry.Size:\n \"\"\"Returns the renderable's :term:`render size`.\n\n Returns:\n The size of the renderable's :term:`render output`.\n\n The base implementation raises :py:class:`NotImplementedError`.\n\n NOTE:\n Both dimensions are expected to be positive.\n\n .. seealso:: :py:attr:`render_size`\n \"\"\"\n raise NotImplementedError\n\n def _handle_interrupted_draw_(\n self, render_data: RenderData, render_args: RenderArgs, output: TextIO\n ) -> None:\n \"\"\"Performs any special handling necessary when an interruption occurs while\n writing a :term:`render output` to a stream.\n\n Args:\n render_data: Render data.\n render_args: Render arguments.\n output: The text I/O stream to which the render output was being written.\n\n Called by the base implementations of :py:meth:`draw` (for non-animations)\n and :py:meth:`_animate_` when :py:class:`KeyboardInterrupt` is raised while\n writing a render output.\n\n The base implementation does nothing.\n\n NOTE:\n *output* should be flushed by this method.\n\n HINT:\n For a renderable that uses SGR sequences in its render output, this method\n may write ``CSI 0 m`` to *output*.\n \"\"\"\n\n # *render_args*, no *padding*; or neither\n @overload\n def _init_render_(\n self,\n renderer: Callable[[RenderData, RenderArgs], T],\n render_args: RenderArgs | None = None,\n *,\n iteration: bool = False,\n finalize: bool = True,\n check_size: bool = False,\n allow_scroll: bool = False,\n ) -> tuple[T, None]: ...\n\n # both *render_args* and *padding*\n @overload\n def _init_render_(\n self,\n renderer: Callable[[RenderData, RenderArgs], T],\n render_args: RenderArgs | None,\n padding: OptionalPaddingT,\n *,\n iteration: bool = False,\n finalize: bool = True,\n check_size: bool = False,\n allow_scroll: bool = False,\n ) -> tuple[T, OptionalPaddingT]: ...\n\n # *padding*, no *render_args*\n @overload\n def _init_render_(\n self,\n renderer: Callable[[RenderData, RenderArgs], T],\n *,\n padding: OptionalPaddingT,\n iteration: bool = False,\n finalize: bool = True,\n check_size: bool = False,\n allow_scroll: bool = False,\n ) -> tuple[T, OptionalPaddingT]: ...\n\n def _init_render_(\n self,\n renderer: Callable[[RenderData, RenderArgs], T],\n render_args: RenderArgs | None = None,\n padding: Padding | None = None,\n *,\n iteration: bool = False,\n finalize: bool = True,\n check_size: bool = False,\n allow_scroll: bool = False,\n ) -> tuple[T, Padding | None]:\n \"\"\"Initiates a render operation.\n\n Args:\n renderer: Performs a render operation or extracts render data and arguments\n for a render operation to be performed later on.\n render_args: Render arguments.\n padding (:py:data:`OptionalPaddingT`): :term:`Render output` padding.\n iteration: Whether the render operation involves a sequence of renders\n (most likely of different frames), or it's a one-off render.\n finalize: Whether to finalize the render data passed to *renderer*\n immediately *renderer* returns.\n check_size: Whether to validate the [padded] :term:`render size` of\n **non-animations**.\n allow_scroll: Whether to validate the [padded] :term:`render height` of\n **non-animations**. Ignored if *check_size* is ``False``.\n\n Returns:\n A tuple containing\n\n * The return value of *renderer*.\n * *padding* (with equivalent **absolute** dimensions if it's an instance of\n :py:class:`~term_image.padding.AlignedPadding`).\n\n Raises:\n IncompatibleRenderArgsError: Incompatible render arguments.\n RenderSizeOutofRangeError: *check_size* is ``True`` and the [padded]\n :term:`render size` cannot fit into the :term:`terminal size`.\n\n :rtype: tuple[T, :py:data:`OptionalPaddingT`]\n\n After preparing render data and processing arguments, *renderer* is called with\n the following positional arguments:\n\n 1. Render data associated with **the renderable's class**\n 2. Render arguments associated with **the renderable's class** and initialized\n with *render_args*\n\n Any exception raised by *renderer* is propagated.\n\n IMPORTANT:\n Beyond this method (i.e any context from *renderer* onwards), use of any\n variable state (internal or external) should be avoided if possible.\n Any variable state (internal or external) required for rendering should\n be provided via :py:meth:`_get_render_data_`.\n\n If at all any variable state has to be used and is not\n reasonable/practicable to be provided via :py:meth:`_get_render_data_`,\n it should be read only once during a single render and passed to any\n nested/subsequent calls that require the value of that state during the\n same render.\n\n This is to prevent inconsistency in data used for the same render which may\n result in unexpected output.\n \"\"\"\n if not (render_args and render_args.render_cls is type(self)):\n # Validate compatibility (and convert, if compatible)\n render_args = RenderArgs(type(self), render_args)\n terminal_size = get_terminal_size()\n render_data = self._get_render_data_(iteration=iteration)\n try:\n if padding and isinstance(padding, AlignedPadding) and padding.relative:\n padding = padding.resolve(terminal_size)\n\n if check_size:\n render_size: Size = render_data[Renderable].size\n width, height = (\n padding.get_padded_size(render_size) if padding else render_size\n )\n terminal_width, terminal_height = terminal_size\n\n if width > terminal_width:\n raise RenderSizeOutofRangeError(\n f\"{'Padded render' if padding else 'Render'} width out of \"\n f\"range (got: {width}; terminal_width={terminal_width})\"\n )\n if not allow_scroll and height > terminal_height:\n raise RenderSizeOutofRangeError(\n f\"{'Padded render' if padding else 'Render'} height out of \"\n f\"range (got: {height}; terminal_height={terminal_height})\"\n )\n\n return renderer(render_data, render_args), padding\n finally:\n if finalize:\n render_data.finalize()\n\n @abstractmethod\n def _render_(self, render_data: RenderData, render_args: RenderArgs) -> Frame:\n \"\"\":term:`Renders` a frame.\n\n Args:\n render_data: Render data.\n render_args: Render arguments.\n\n Returns:\n The rendered frame.\n\n * The :py:attr:`~term_image.renderable.Frame.render_size` field =\n :py:attr:`render_data[Renderable].size\n `.\n * The :py:attr:`~term_image.renderable.Frame.render_output` field holds the\n :term:`render output`. This string should:\n\n * contain as many lines as ``render_size.height`` i.e exactly\n ``render_size.height - 1`` occurrences of ``\\\\n`` (the newline\n sequence).\n * occupy exactly ``render_size.height`` lines and ``render_size.width``\n columns on each line when drawn onto a terminal screen, **at least**\n when the render **size** it not greater than the terminal size on\n either axis.\n\n .. tip::\n If for any reason, the output behaves differently when the render\n **height** is greater than the terminal height, the behaviour, along\n with any possible alternatives or workarounds, should be duely noted.\n This doesn't apply to the **width**.\n\n * **not** end with ``\\\\n`` (the newline sequence).\n\n * As for the :py:attr:`~term_image.renderable.Frame.duration` field, if\n the renderable is:\n\n * **animated**; the value should be determined from the frame data\n source (or a default/fallback value, if undeterminable), if\n :py:attr:`render_data[Renderable].duration\n ` is\n :py:attr:`~term_image.renderable.FrameDuration.DYNAMIC`.\n Otherwise, it should be equal to\n :py:attr:`render_data[Renderable].duration\n `.\n * **non-animated**; the value range is unspecified i.e it may be given\n any value.\n\n Raises:\n StopIteration: End of iteration for an animated renderable with\n :py:attr:`~term_image.renderable.FrameCount.INDEFINITE` frame count.\n RenderError: An error occurred while rendering.\n\n NOTE:\n :py:class:`StopIteration` may be raised if and only if\n :py:attr:`render_data[Renderable].iteration\n ` is ``True``.\n Otherwise, it would be out of place.\n\n .. seealso:: :py:class:`~term_image.renderable.RenderableData`.\n \"\"\"\n raise NotImplementedError", "n_imports_parsed": 14, "n_files_resolved": 7, "n_chars_extracted": 41124}, "tests/renderable/test_renderable.py::1015": {"resolved_imports": ["src/term_image/_ctlseqs.py", "src/term_image/geometry.py", "src/term_image/padding.py", "src/term_image/renderable/_enum.py", "src/term_image/renderable/_exceptions.py", "src/term_image/renderable/_renderable.py", "src/term_image/renderable/_types.py"], "used_names": ["AlignedPadding", "RenderArgs", "sys"], "enclosing_function": "test_default", "extracted_code": "# Source: src/term_image/padding.py\nclass AlignedPadding(Padding):\n \"\"\"Aligned :term:`render output` padding.\n\n Args:\n width: Minimum :term:`render width`.\n height: Minimum :term:`render height`.\n h_align: Horizontal alignment.\n v_align: Vertical alignment.\n\n If *width* or *height* is:\n\n * positive, it is **absolute** and used as-is.\n * non-positive, it is **relative** to the corresponding terminal dimension\n (**at the point of resolution**) and equivalent to the absolute dimension\n ``max(terminal_dimension + relative_dimension, 1)``.\n\n The *padded render dimension* (i.e the dimension of a :term:`render output` after\n it's padded) on each axis is given by::\n\n padded_dimension = max(render_dimension, absolute_minimum_dimension)\n\n In words... If the **absolute** *minimum render dimension* on an axis is less than\n or equal to the corresponding *render dimension*, there is no padding on that axis\n and the *padded render dimension* on that axis is equal to the *render dimension*.\n Otherwise, the render output will be padded along that axis and the *padded render\n dimension* on that axis is equal to the *minimum render dimension*.\n\n The amount of padding to each side depends on the alignment, defined by *h_align*\n and *v_align*.\n\n IMPORTANT:\n :py:class:`RelativePaddingDimensionError` is raised if any padding-related\n computation/operation (basically, calling any method other than\n :py:meth:`resolve`) is performed on an instance with **relative** *minimum\n render dimension(s)* i.e if :py:attr:`relative` is ``True``.\n\n NOTE:\n Any interface receiving an instance with **relative** dimension(s) should\n typically resolve it/them upon reception.\n\n TIP:\n * Instances are immutable and hashable.\n * Instances with equal fields compare equal.\n \"\"\"\n\n # Class Attributes =========================================================\n\n __slots__ = (\"width\", \"height\", \"h_align\", \"v_align\", \"relative\")\n\n # Instance Attributes ======================================================\n\n width: int\n \"\"\"Minimum :term:`render width`\"\"\"\n\n height: int\n \"\"\"Minimum :term:`render height`\"\"\"\n\n h_align: HAlign\n \"\"\"Horizontal alignment\"\"\"\n\n v_align: VAlign\n \"\"\"Vertical alignment\"\"\"\n\n fill: str\n\n relative: bool\n \"\"\"``True`` if either or both *minimum render dimension(s)* is/are relative i.e\n non-positive. Otherwise, ``False``.\n \"\"\"\n\n # Special Methods ==========================================================\n\n def __init__(\n self,\n width: int,\n height: int,\n h_align: HAlign = HAlign.CENTER,\n v_align: VAlign = VAlign.MIDDLE,\n fill: str = \" \",\n ):\n super().__init__(fill)\n\n _setattr = super().__setattr__\n _setattr(\"width\", width)\n _setattr(\"height\", height)\n _setattr(\"h_align\", h_align)\n _setattr(\"v_align\", v_align)\n _setattr(\"relative\", not width > 0 < height)\n\n def __repr__(self) -> str:\n return \"{}(width={}, height={}, h_align={}, v_align={}, fill={!r})\".format(\n type(self).__name__,\n self.width,\n self.height,\n self.h_align.name,\n self.v_align.name,\n self.fill,\n )\n\n # Properties ===============================================================\n\n @property\n def size(self) -> RawSize:\n \"\"\"Minimum :term:`render size`\n\n GET:\n Returns the *minimum render dimensions*.\n \"\"\"\n return _RawSize(self.width, self.height)\n\n # Public Methods ===========================================================\n\n @override\n def get_padded_size(self, render_size: Size) -> Size:\n \"\"\"Computes an expected padded :term:`render size`.\n\n See :py:meth:`Padding.get_padded_size`.\n\n Raises:\n RelativePaddingDimensionError: Relative *minimum render dimension(s)*.\n \"\"\"\n if self.relative:\n raise RelativePaddingDimensionError(\"Relative minimum render dimension(s)\")\n\n return _Size(max(self.width, render_size[0]), max(self.height, render_size[1]))\n\n def resolve(self, terminal_size: os.terminal_size) -> AlignedPadding:\n \"\"\"Resolves **relative** *minimum render dimensions*.\n\n Args:\n terminal_size: The terminal size against which to resolve relative\n dimensions.\n\n Returns:\n An instance with equivalent **absolute** dimensions.\n \"\"\"\n if not self.relative:\n return self\n\n width, height, *args, _ = astuple(self)\n terminal_width, terminal_height = terminal_size\n if width <= 0:\n width = max(terminal_width + width, 1)\n if height <= 0:\n height = max(terminal_height + height, 1)\n\n return type(self)(width, height, *args)\n\n # Extension methods ========================================================\n\n @override\n def _get_exact_dimensions_(self, render_size: Size) -> tuple[int, int, int, int]:\n if self.relative:\n raise RelativePaddingDimensionError(\"Relative minimum render dimension(s)\")\n\n width, height, h_align, v_align = astuple(self)[:4]\n render_width, render_height = render_size\n\n if width > render_width:\n padding_width = width - render_width\n numerator, denominator = _ALIGN_RATIOS[h_align]\n left = padding_width * numerator // denominator\n right = padding_width - left\n else:\n left = right = 0\n\n if height > render_height:\n padding_height = height - render_height\n numerator, denominator = _ALIGN_RATIOS[v_align]\n top = padding_height * numerator // denominator\n bottom = padding_height - top\n else:\n top = bottom = 0\n\n return left, top, right, bottom\n\n\n# Source: src/term_image/renderable/_types.py\nclass RenderArgs(RenderArgsData):\n \"\"\"RenderArgs(render_cls, /, *namespaces)\n RenderArgs(render_cls, init_render_args, /, *namespaces)\n\n Render arguments.\n\n Args:\n render_cls: A :term:`render class`.\n init_render_args (RenderArgs | None): A set of render arguments.\n If not ``None``,\n\n * it must be compatible [#ra-com]_ with *render_cls*,\n * it'll be used to initialize the render arguments.\n\n namespaces: Render argument namespaces compatible [#an-com]_ with *render_cls*.\n\n .. note:: If multiple namespaces associated with the same :term:`render\n class` are given, the last of them takes precedence.\n\n Raises:\n IncompatibleRenderArgsError: *init_render_args* is incompatible [#ra-com]_ with\n *render_cls*.\n IncompatibleArgsNamespaceError: Incompatible [#an-com]_ render argument\n namespace.\n\n A set of render arguments (an instance of this class) is basically a container of\n render argument namespaces (instances of\n :py:class:`~term_image.renderable.ArgsNamespace`); one for\n each :term:`render class`, which has render arguments, in the Method Resolution\n Order of its associated [#ra-ass]_ render class.\n\n The namespace for each render class is derived from the following sources, in\n [descending] order of precedence:\n\n * *namespaces*\n * *init_render_args*\n * default render argument namespaces\n\n NOTE:\n Instances are immutable but updated copies can be created via :py:meth:`update`.\n\n .. seealso::\n\n :py:attr:`~term_image.renderable.Renderable.Args`\n Render class-specific render arguments.\n\n .. Completed in /docs/source/api/renderable.rst\n \"\"\"\n\n # Class Attributes =========================================================\n\n __slots__ = ()\n\n _interned: ClassVar[dict[type[Renderable], Self]] = {}\n _namespaces: MappingProxyType[type[Renderable], ArgsNamespace]\n\n # Instance Attributes ======================================================\n\n render_cls: type[Renderable]\n \"\"\"The associated :term:`render class`\"\"\"\n\n # Special Methods ==========================================================\n\n def __new__(\n cls,\n render_cls: type[Renderable],\n init_or_namespace: RenderArgs | ArgsNamespace | None = None,\n *namespaces: ArgsNamespace,\n ) -> Self:\n if init_or_namespace is None:\n init_render_args = None\n elif isinstance(init_or_namespace, RenderArgs):\n init_render_args = init_or_namespace\n else:\n init_render_args = None\n namespaces = (init_or_namespace, *namespaces)\n\n if init_render_args and not issubclass(render_cls, init_render_args.render_cls):\n raise IncompatibleRenderArgsError(\n f\"'init_render_args' (associated with \"\n f\"{init_render_args.render_cls.__name__!r}) is incompatible with \"\n f\"{render_cls.__name__!r} \"\n )\n\n if not namespaces:\n # has default namespaces only\n if (\n not init_render_args\n or init_render_args is BASE_RENDER_ARGS\n or cls._interned.get(init_render_args.render_cls) is init_render_args\n ):\n try:\n return cls._interned[render_cls]\n except KeyError:\n pass\n\n if (\n init_render_args\n and type(init_render_args) is cls\n and init_render_args.render_cls is render_cls\n ):\n return init_render_args\n\n return super().__new__(cls)\n\n def __init__(\n self,\n render_cls: type[Renderable],\n init_or_namespace: RenderArgs | ArgsNamespace | None = None,\n *namespaces: ArgsNamespace,\n ) -> None:\n if init_or_namespace is None:\n init_render_args = None\n elif isinstance(init_or_namespace, RenderArgs):\n init_render_args = init_or_namespace\n else:\n init_render_args = None\n namespaces = (init_or_namespace, *namespaces)\n\n # has default namespaces only\n if not namespaces and (\n not init_render_args\n or init_render_args is BASE_RENDER_ARGS\n or (\n type(self)._interned.get(init_render_args.render_cls)\n is init_render_args\n )\n ):\n if render_cls in type(self)._interned: # has been initialized\n return\n intern = True\n else:\n intern = False\n\n if init_render_args is self:\n return\n\n namespaces_dict = render_cls._ALL_DEFAULT_ARGS.copy()\n\n # if `init_render_args` is non-default\n if init_render_args and BASE_RENDER_ARGS is not init_render_args is not (\n type(self)._interned.get(init_render_args.render_cls)\n ):\n namespaces_dict.update(init_render_args._namespaces)\n\n for index, namespace in enumerate(namespaces):\n if namespace._RENDER_CLS not in namespaces_dict:\n raise IncompatibleArgsNamespaceError(\n f\"'namespaces[{index}]' (associated with \"\n f\"{namespace._RENDER_CLS.__name__!r}) is incompatible with \"\n f\"{render_cls.__name__!r} \"\n )\n namespaces_dict[namespace._RENDER_CLS] = namespace\n\n super().__init__(render_cls, namespaces_dict)\n\n if intern:\n type(self)._interned[render_cls] = self\n\n def __init_subclass__(cls, **kwargs: Any) -> None:\n cls._interned = {}\n super().__init_subclass__(**kwargs)\n\n def __contains__(self, namespace: ArgsNamespace) -> bool:\n \"\"\"Checks if a render argument namespace is contained in this set of render\n arguments.\n\n Args:\n namespace: A render argument namespace.\n\n Returns:\n ``True`` if the given namespace is equal to any of the namespaces\n contained in this set of render arguments. Otherwise, ``False``.\n \"\"\"\n return None is not self._namespaces.get(namespace._RENDER_CLS) == namespace\n\n def __eq__(self, other: object) -> bool:\n \"\"\"Compares this set of render arguments with another.\n\n Args:\n other: Another set of render arguments.\n\n Returns:\n ``True`` if both are associated with the same :term:`render class`\n and have equal argument values. Otherwise, ``False``.\n \"\"\"\n if isinstance(other, RenderArgs):\n return (\n self is other\n or self.render_cls is other.render_cls\n and self._namespaces == other._namespaces\n )\n\n return NotImplemented\n\n def __getitem__(self, render_cls: type[Renderable]) -> Any:\n \"\"\"Returns a constituent namespace.\n\n Args:\n render_cls: A :term:`render class` of which :py:attr:`render_cls` is a\n subclass (which may be :py:attr:`render_cls` itself) and which has\n render arguments.\n\n Returns:\n The constituent namespace associated with *render_cls*.\n\n Raises:\n TypeError: *render_cls* is not a render class.\n ValueError: :py:attr:`render_cls` is not a subclass of *render_cls*.\n NoArgsNamespaceError: *render_cls* has no render arguments.\n\n NOTE:\n The return type hint is :py:class:`~typing.Any` only for compatibility\n with static type checking, as this aspect of the interface seems too\n dynamic to be correctly expressed with the exisiting type system.\n\n Regardless, the return value is guaranteed to always be an instance\n of a render argument namespace class associated with *render_cls*.\n For instance, the following would always be valid for\n :py:class:`~term_image.renderable.Renderable`::\n\n renderable_args: RenderableArgs = render_args[Renderable]\n\n and similar idioms are encouraged to be used for other render classes.\n \"\"\"\n try:\n return self._namespaces[render_cls]\n except TypeError:\n raise arg_type_error(\"render_cls\", render_cls) from None\n except KeyError:\n if not isinstance(render_cls, RenderableMeta):\n raise arg_type_error(\"render_cls\", render_cls) from None\n\n if issubclass(self.render_cls, render_cls):\n raise NoArgsNamespaceError(\n f\"{render_cls.__name__!r} has no render arguments\"\n ) from None\n\n raise ValueError(\n f\"{self.render_cls.__name__!r} is not a subclass of \"\n f\"{render_cls.__name__!r}\"\n ) from None\n\n def __hash__(self) -> int:\n \"\"\"Computes the hash of the render arguments.\n\n Returns:\n The computed hash.\n\n IMPORTANT:\n Like tuples, an instance is hashable if and only if the constituent\n namespaces are hashable.\n \"\"\"\n # Namespaces are always in the same order, wrt their respective associated\n # render classes, for all instances associated with the same render class.\n return hash((self.render_cls, tuple(self._namespaces.values())))\n\n def __iter__(self) -> Iterator[ArgsNamespace]:\n \"\"\"Returns an iterator that yields the constituent namespaces.\n\n Returns:\n An iterator that yields the constituent namespaces.\n\n WARNING:\n The number and order of namespaces is guaranteed to be the same across all\n instances associated [#ra-ass]_ with the same :term:`render class` but\n beyond this, should not be relied upon as the details (such as the\n specific number or order) may change without notice.\n\n The order is an implementation detail of the Renderable API and the number\n should be considered alike with respect to the associated render class.\n \"\"\"\n return iter(self._namespaces.values())\n\n def __repr__(self) -> str:\n return \"\".join(\n (\n f\"{type(self).__name__}({self.render_cls.__name__}\",\n \", \" if self._namespaces else \"\",\n \", \".join(map(repr, self._namespaces.values())),\n \")\",\n )\n )\n\n # Public Methods ===========================================================\n\n def convert(self, render_cls: type[Renderable]) -> RenderArgs:\n \"\"\"Converts the set of render arguments to one for a related render class.\n\n Args:\n render_cls: A :term:`render class` of which :py:attr:`render_cls` is a\n parent or child (which may be :py:attr:`render_cls` itself).\n\n Returns:\n A set of render arguments associated [#ra-ass]_ with *render_cls* and\n initialized with all constituent namespaces (of this set of render\n arguments, *self*) that are compatible [#an-com]_ with *render_cls*.\n\n Raises:\n ValueError: *render_cls* is not a parent or child of :py:attr:`render_cls`.\n \"\"\"\n if render_cls is self.render_cls:\n return self\n\n if issubclass(render_cls, self.render_cls):\n return RenderArgs(render_cls, self)\n\n if issubclass(self.render_cls, render_cls):\n render_cls_args_mro = render_cls._ALL_DEFAULT_ARGS\n return RenderArgs(\n render_cls,\n *[\n namespace\n for cls, namespace in self._namespaces.items()\n if cls in render_cls_args_mro\n ],\n )\n\n raise ValueError(\n f\"{render_cls.__name__!r} is not a parent or child of \"\n f\"{self.render_cls.__name__!r}\"\n )\n\n @overload\n def update(\n self,\n namespace: ArgsNamespace,\n /,\n *namespaces: ArgsNamespace,\n ) -> RenderArgs: ...\n\n @overload\n def update(\n self,\n render_cls: type[Renderable],\n /,\n **fields: Any,\n ) -> RenderArgs: ...\n\n def update(\n self,\n render_cls_or_namespace: type[Renderable] | ArgsNamespace,\n /,\n *namespaces: ArgsNamespace,\n **fields: Any,\n ) -> RenderArgs:\n \"\"\"update(namespace, /, *namespaces) -> RenderArgs\n update(render_cls, /, **fields) -> RenderArgs\n\n Replaces or updates render argument namespaces.\n\n Args:\n namespace (ArgsNamespace): Prepended to *namespaces*.\n namespaces: Render argument namespaces compatible [#an-com]_ with\n :py:attr:`render_cls`.\n\n .. note:: If multiple namespaces associated with the same :term:`render\n class` are given, the last of them takes precedence.\n\n render_cls (type[Renderable]): A :term:`render class` of which\n :py:attr:`render_cls` is a subclass (which may be :py:attr:`render_cls`\n itself) and which has render arguments.\n fields: Render argument fields.\n\n The keywords must be names of render argument fields for *render_cls*.\n\n Returns:\n For the **first** form, an instance with the namespaces for the respective\n associated :term:`render classes` of the given namespaces replaced.\n\n For the **second** form, an instance with the given render argument fields\n for *render_cls* updated, if any.\n\n Raises:\n TypeError: The arguments given do not conform to any of the expected forms.\n\n Propagates exceptions raised by:\n\n * the class constructor, for the **first** form.\n * :py:meth:`__getitem__` and :py:meth:`ArgsNamespace.update()\n `, for the **second** form.\n \"\"\"\n if isinstance(render_cls_or_namespace, RenderableMeta):\n if namespaces:\n raise TypeError(\n \"No other positional argument is expected when the first argument \"\n \"is a render class\"\n )\n render_cls = render_cls_or_namespace\n else:\n if fields:\n raise TypeError(\n \"No keyword argument is expected when the first argument is \"\n \"a render argument namespace\"\n )\n render_cls = None\n namespaces = (render_cls_or_namespace, *namespaces)\n\n return RenderArgs(\n self.render_cls,\n self,\n *((self[render_cls].update(**fields),) if render_cls else namespaces),\n )", "n_imports_parsed": 14, "n_files_resolved": 7, "n_chars_extracted": 20781}, "tests/test_image/test_kitty.py::178": {"resolved_imports": ["src/term_image/__init__.py", "src/term_image/_ctlseqs.py", "src/term_image/exceptions.py", "src/term_image/image/__init__.py", "src/term_image/image/kitty.py"], "used_names": ["decompress", "io", "standard_b64decode"], "enclosing_function": "decode_image", "extracted_code": "", "n_imports_parsed": 12, "n_files_resolved": 5, "n_chars_extracted": 0}, "tests/widget/urwid/test_main.py::68": {"resolved_imports": ["src/term_image/__init__.py", "src/term_image/_ctlseqs.py", "src/term_image/exceptions.py", "src/term_image/image/block.py", "src/term_image/image/common.py", "src/term_image/image/iterm2.py", "src/term_image/image/kitty.py", "src/term_image/widget/_urwid.py"], "used_names": ["BlockImage", "Image", "RenderError", "UrwidImage", "pytest", "urwid"], "enclosing_function": "test_error_placeholder", "extracted_code": "# Source: src/term_image/exceptions.py\nclass RenderError(TermImageError):\n \"\"\"...\"\"\"\n\n\n# Source: src/term_image/image/block.py\nclass BlockImage(TextImage):\n \"\"\"A render style using unicode half blocks and direct-color colour escape\n sequences.\n\n See :py:class:`TextImage` for the description of the constructor.\n \"\"\"\n\n @classmethod\n def is_supported(cls):\n if cls._supported is None:\n COLORTERM = os.environ.get(\"COLORTERM\") or \"\"\n TERM = os.environ.get(\"TERM\") or \"\"\n cls._supported = (\n \"truecolor\" in COLORTERM or \"24bit\" in COLORTERM or \"256color\" in TERM\n )\n\n return cls._supported\n\n def _get_render_size(self) -> Tuple[int, int]:\n return tuple(map(mul, self.rendered_size, (1, 2)))\n\n @staticmethod\n def _pixels_cols(\n *, pixels: Optional[int] = None, cols: Optional[int] = None\n ) -> int:\n return pixels if pixels is not None else cols\n\n @staticmethod\n def _pixels_lines(\n *, pixels: Optional[int] = None, lines: Optional[int] = None\n ) -> int:\n return ceil(pixels / 2) if pixels is not None else lines * 2\n\n def _render_image(\n self,\n img: PIL.Image.Image,\n alpha: Union[None, float, str],\n *,\n frame: bool = False,\n split_cells: bool = False,\n ) -> str:\n # NOTE:\n # It's more efficient to write separate strings to the buffer separately\n # than concatenate and write together.\n\n def update_buffer():\n if alpha:\n no_alpha = False\n if a_cluster1 == 0 == a_cluster2:\n buf_write(SGR_DEFAULT)\n buf_write(blank * n)\n elif a_cluster1 == 0: # up is transparent\n buf_write(SGR_DEFAULT)\n buf_write(SGR_FG_DIRECT % cluster2)\n buf_write(lower_pixel * n)\n elif a_cluster2 == 0: # down is transparent\n buf_write(SGR_DEFAULT)\n buf_write(SGR_FG_DIRECT % cluster1)\n buf_write(upper_pixel * n)\n else:\n no_alpha = True\n\n if not alpha or no_alpha:\n r, g, b = cluster2\n # Kitty does not render BG colors equal to the default BG color\n if is_on_kitty and cluster2 == bg_color:\n r += r < 255 or -1\n buf_write(SGR_BG_DIRECT % (r, g, b))\n if cluster1 == cluster2:\n buf_write(blank * n)\n else:\n buf_write(SGR_FG_DIRECT % cluster1)\n buf_write(upper_pixel * n)\n\n buffer = io.StringIO()\n buf_write = buffer.write # Eliminate attribute resolution cost\n\n bg_color = get_fg_bg_colors()[1]\n is_on_kitty = self._is_on_kitty()\n if split_cells:\n blank = \" \\0\"\n lower_pixel = LOWER_PIXEL + \"\\0\"\n upper_pixel = UPPER_PIXEL + \"\\0\"\n else:\n blank = \" \"\n lower_pixel = LOWER_PIXEL\n upper_pixel = UPPER_PIXEL\n end_of_line = SGR_DEFAULT + \"\\n\"\n\n width, height = self._get_render_size()\n frame_img = img if frame else None\n img, rgb, a = self._get_render_data(img, alpha, round_alpha=True, frame=frame)\n alpha = img.mode == \"RGBA\"\n\n # clean up (ImageIterator uses one PIL image throughout)\n if frame_img is not img:\n self._close_image(img)\n\n rgb_pairs = (\n (\n zip(rgb[x : x + width], rgb[x + width : x + width * 2]),\n (rgb[x], rgb[x + width]),\n )\n for x in range(0, len(rgb), width * 2)\n )\n a_pairs = (\n (\n zip(a[x : x + width], a[x + width : x + width * 2]),\n (a[x], a[x + width]),\n )\n for x in range(0, len(a), width * 2)\n )\n\n row_no = 0\n # Two rows of pixels per line\n for (rgb_pair, (cluster1, cluster2)), (a_pair, (a_cluster1, a_cluster2)) in zip(\n rgb_pairs, a_pairs\n ):\n row_no += 2\n n = 0\n for (px1, px2), (a1, a2) in zip(rgb_pair, a_pair):\n # Color-code characters and write to buffer\n # when upper and/or lower pixel color/alpha-level changes\n if not (alpha and a1 == a_cluster1 == 0 == a_cluster2 == a2) and (\n px1 != cluster1\n or px2 != cluster2\n or alpha\n and (\n # From non-transparent to transparent\n a_cluster1 != a1 == 0\n or a_cluster2 != a2 == 0\n # From transparent to non-transparent\n or 0 == a_cluster1 != a1\n or 0 == a_cluster2 != a2\n )\n ):\n update_buffer()\n cluster1 = px1\n cluster2 = px2\n if alpha:\n a_cluster1 = a1\n a_cluster2 = a2\n n = 0\n n += 1\n\n update_buffer() # Rest of the line\n if split_cells:\n # Set the last \"\\0\" to be overwritten by the next byte\n buffer.seek(buffer.tell() - 1)\n if row_no < height: # last line not yet rendered\n buf_write(end_of_line)\n\n buf_write(SGR_DEFAULT) # Reset color after last line\n\n with buffer:\n return buffer.getvalue()\n\n\n# Source: src/term_image/widget/_urwid.py\nclass UrwidImage(urwid.Widget):\n \"\"\"Image widget (box/flow) for the urwid TUI framework.\n\n Args:\n image: The image to be rendered by the widget.\n format_spec: :ref:`Render format specifier `. Padding width and\n height are ignored.\n upscale: If ``True``, the image will be upscaled to fit maximally within the\n available size, if necessary, while still preserving the aspect ratio.\n Otherwise, the image is never upscaled.\n\n Raises:\n TypeError: An argument is of an inappropriate type.\n ValueError: An argument is of an appropriate type but has an\n unexpected/invalid value.\n term_image.exceptions.StyleError: Invalid style-specific format specifier.\n term_image.exceptions.UrwidImageError: Too many image widgets rendering images\n with the *kitty* render style.\n\n | Any ample space in the widget's render size is filled with spaces.\n | For animated images, the current frame (at render-time) is rendered.\n\n TIP:\n If *image* is of a :ref:`graphics-based ` render style and the\n widget is being used as or within a **flow** widget, with overlays or in any\n other case where the canvas will require vertical trimming, make sure to use a\n render method that splits images across lines such as the **LINES** render\n method for *kitty* and *iterm2* render styles.\n\n NOTE:\n * The `z-index` style-specific format spec field for\n :py:class:`~term_image.image.KittyImage` is ignored as this is used\n internally.\n * A **maximum** of ``2**32 - 2`` instances initialized with\n :py:class:`~term_image.image.KittyImage` instances may exist at the same time.\n\n IMPORTANT:\n This is defined if and only if the ``urwid`` package is available.\n \"\"\"\n\n _sizing = frozenset((urwid.BOX, urwid.FLOW))\n ignore_focus = True\n\n _ti_error_placeholder = None\n\n # For kitty images\n _ti_disguise_state = 0\n _ti_free_z_indexes = set()\n\n # Progresses thus: 1, -1, 2, -2, 3, ..., 2**31 - 1, -(2**31 - 1)\n # This sequence results in shorter image escape sequences compared to starting\n # from -(2**31)\n _ti_next_z_index = 1\n\n def __init__(\n self, image: BaseImage, format_spec: str = \"\", *, upscale: bool = False\n ) -> None:\n if not isinstance(image, BaseImage):\n raise arg_type_error(\"image\", image)\n\n if not isinstance(format_spec, str):\n raise arg_type_error(\"format_spec\", format_spec)\n *fmt, alpha, style_args = image._check_format_spec(format_spec)\n\n if not isinstance(upscale, bool):\n raise arg_type_error(\"upscale\", upscale)\n\n super().__init__()\n self._ti_image = image\n self._ti_h_align, _, self._ti_v_align, _ = fmt\n self._ti_alpha = alpha\n self._ti_style_args = style_args\n self._ti_sizing = Size.FIT if upscale else Size.AUTO\n\n if isinstance(image, TextImage):\n style_args[\"split_cells\"] = True\n elif isinstance(image, KittyImage):\n style_args[\"z_index\"] = self._ti_z_index = self._ti_get_z_index()\n\n # Since Konsole doesn't blend images placed at the same location and\n # z-index, unlike Kitty (and potentially others), `blend=True` is\n # better on Konsole as it reduces/eliminates flicker.\n if get_terminal_name_version()[0] != \"konsole\":\n # To clear directly overlapped images when urwid redraws a line without\n # a change in image position\n style_args[\"blend\"] = False\n\n def __del__(self) -> None:\n if hasattr(self, \"_ti_z_index\"):\n __class__._ti_free_z_indexes.add(self._ti_z_index)\n\n image = property(\n lambda self: self._ti_image,\n doc=\"\"\"\n The image rendered by the widget\n\n :type: BaseImage\n\n GET:\n Returns the image instance rendered by the widget.\n \"\"\",\n )\n\n def render(self, size: Tuple[int, int], focus: bool = False) -> urwid.Canvas:\n image = self._ti_image\n\n if len(size) == 2: # box\n image.set_size(self._ti_sizing, frame_size=size)\n elif len(size) == 1: # flow\n if self._ti_sizing is Size.FIT:\n image.set_size(size[0])\n else:\n fit_size = self._ti_image._valid_size(size[0])\n ori_size = self._ti_image._valid_size(Size.ORIGINAL)\n image._size = (\n ori_size\n if ori_size[0] <= fit_size[0] and ori_size[1] <= fit_size[1]\n else fit_size\n )\n size = (size[0], image._size[1])\n else: # fixed\n raise UrwidImageError(\"Not a fixed widget\")\n\n try:\n render = image._format_render(\n image._renderer(\n image._render_image, self._ti_alpha, **self._ti_style_args\n ),\n self._ti_h_align,\n size[0],\n self._ti_v_align,\n size[1],\n )\n except Exception:\n if type(self)._ti_error_placeholder is None:\n raise\n canv = type(self)._ti_error_placeholder.render(size, focus)\n else:\n canv = UrwidImageCanvas(render, size, image._size)\n\n return canv\n\n def rows(self, size: Tuple[int], focus: bool = False) -> int:\n fit_size = self._ti_image._valid_size(size[0])\n if self._ti_sizing is Size.FIT:\n n_rows = fit_size[1]\n else:\n ori_size = self._ti_image._valid_size(Size.ORIGINAL)\n n_rows = (\n ori_size[1]\n if ori_size[0] <= fit_size[0] and ori_size[1] <= fit_size[1]\n else fit_size[1]\n )\n\n return n_rows\n\n @classmethod\n def set_error_placeholder(cls, widget: Optional[urwid.Widget]) -> None:\n \"\"\"Sets the widget to be rendered in place of an image when rendering fails.\n\n Args:\n widget: The placeholder widget or ``None`` to remove the placeholder.\n\n Raises:\n TypeError: *widget* is not an urwid widget.\n\n If set, any exception raised during rendering is **suppressed** and the\n placeholder is rendered in place of the image.\n \"\"\"\n if not isinstance(widget, urwid.Widget):\n raise arg_type_error(\"widget\", widget)\n\n cls._ti_error_placeholder = widget\n\n @staticmethod\n def _ti_get_z_index() -> int:\n if __class__._ti_free_z_indexes:\n return __class__._ti_free_z_indexes.pop()\n\n z_index = __class__._ti_next_z_index\n if z_index == 2**31:\n raise UrwidImageError(\"Too many image widgets with the kitty render style\")\n __class__._ti_next_z_index = -z_index if z_index > 0 else -z_index + 1\n\n return z_index\n\n def _ti_change_disguise(self) -> None:\n \"\"\"See :py:meth`UrwidImageCanvas._ti_change_disguise`.\"\"\"\n self._ti_disguise_state = (self._ti_disguise_state + 1) % 3", "n_imports_parsed": 10, "n_files_resolved": 8, "n_chars_extracted": 12826}, "tests/test_iterator.py::108": {"resolved_imports": ["src/term_image/_ctlseqs.py", "src/term_image/exceptions.py", "src/term_image/image/block.py", "src/term_image/image/common.py"], "used_names": ["ImageIterator", "pytest"], "enclosing_function": "test_next", "extracted_code": "# Source: src/term_image/image/common.py\nclass ImageIterator:\n \"\"\"Efficiently iterate over :term:`rendered` frames of an :term:`animated` image\n\n Args:\n image: Animated image.\n repeat: The number of times to go over the entire image. A negative value\n implies infinite repetition.\n format_spec: The :ref:`format specifier ` for the rendered\n frames (default: auto).\n cached: Determines if the :term:`rendered` frames will be cached (for speed up\n of subsequent renders) or not. If it is\n\n * a boolean, caching is enabled if ``True``. Otherwise, caching is disabled.\n * a positive integer, caching is enabled only if the framecount of the image\n is less than or equal to the given number.\n\n Raises:\n TypeError: An argument is of an inappropriate type.\n ValueError: An argument is of an appropriate type but has an\n unexpected/invalid value.\n term_image.exceptions.StyleError: Invalid style-specific format specifier.\n\n * If *repeat* equals ``1``, caching is disabled.\n * The iterator has immediate response to changes in the image size.\n * If the image size is :term:`dynamic `, it's computed per frame.\n * The number of the last yielded frame is set as the image's seek position.\n * Directly adjusting the seek position of the image doesn't affect iteration.\n Use :py:meth:`ImageIterator.seek` instead.\n * After the iterator is exhausted, the underlying image is set to frame ``0``.\n \"\"\"\n\n def __init__(\n self,\n image: BaseImage,\n repeat: int = -1,\n format_spec: str = \"\",\n cached: Union[bool, int] = 100,\n ) -> None:\n if not isinstance(image, BaseImage):\n raise arg_type_error(\"image\", image)\n if not image._is_animated:\n raise ValueError(\"'image' is not animated\")\n\n if not isinstance(repeat, int):\n raise arg_type_error(\"repeat\", repeat)\n if not repeat:\n raise arg_value_error(\"repeat\", repeat)\n\n if not isinstance(format_spec, str):\n raise arg_type_error(\"format_spec\", format_spec)\n *fmt, alpha, style_args = image._check_format_spec(format_spec)\n\n if not isinstance(cached, int): # `bool` is a subclass of `int`\n raise arg_type_error(\"cached\", cached)\n if False is not cached <= 0:\n raise arg_value_error_range(\"cached\", cached)\n\n self._image = image\n self._repeat = repeat\n self._format = format_spec\n self._cached = repeat != 1 and (\n cached if isinstance(cached, bool) else image.n_frames <= cached\n )\n self._loop_no = None\n self._animator = image._renderer(\n self._animate, alpha, fmt, style_args, check_size=False\n )\n\n def __del__(self) -> None:\n self.close()\n\n def __iter__(self) -> ImageIterator:\n return self\n\n def __next__(self) -> str:\n try:\n return next(self._animator)\n except StopIteration:\n self.close()\n raise StopIteration(\n \"Iteration has reached the given repeat count\"\n ) from None\n except AttributeError as e:\n if str(e).endswith(\"'_animator'\"):\n raise StopIteration(\"Iterator exhausted or closed\") from None\n else:\n self.close()\n raise\n except Exception:\n self.close()\n raise\n\n def __repr__(self) -> str:\n return (\n \"{}(image={!r}, repeat={}, format_spec={!r}, cached={}, loop_no={})\".format(\n type(self).__name__,\n *self.__dict__.values(),\n )\n )\n\n loop_no = property(\n lambda self: self._loop_no,\n doc=\"\"\"Iteration repeat countdown\n\n :type: Optional[int]\n\n GET:\n Returns:\n\n * ``None``, if iteration hasn't started.\n * Otherwise, the current iteration repeat countdown value.\n\n Changes on the first iteration of each loop, except for infinite iteration\n where it's always ``-1``. When iteration has ended, the value is zero.\n \"\"\",\n )\n\n def close(self) -> None:\n \"\"\"Closes the iterator and releases resources used.\n\n Does not reset the frame number of the underlying image.\n\n NOTE:\n This method is automatically called when the iterator is exhausted or\n garbage-collected.\n \"\"\"\n try:\n self._animator.close()\n del self._animator\n self._image._close_image(self._img)\n del self._img\n except AttributeError:\n pass\n\n def seek(self, pos: int) -> None:\n \"\"\"Sets the frame number to be yielded on the next iteration without affecting\n the repeat count.\n\n Args:\n pos: Next frame number.\n\n Raises:\n TypeError: An argument is of an inappropriate type.\n ValueError: An argument is of an appropriate type but has an\n unexpected/invalid value.\n term_image.exceptions.TermImageError: Iteration has not yet started or the\n iterator is exhausted/closed.\n\n Frame numbers start from ``0`` (zero).\n \"\"\"\n if not isinstance(pos, int):\n raise arg_type_error(\"pos\", pos)\n if not 0 <= pos < self._image.n_frames:\n raise arg_value_error_range(\"pos\", pos, f\"n_frames={self._image.n_frames}\")\n\n try:\n self._animator.send(pos)\n except TypeError:\n raise TermImageError(\"Iteration has not yet started\") from None\n except AttributeError:\n raise TermImageError(\"Iterator exhausted or closed\") from None\n\n def _animate(\n self,\n img: PIL.Image.Image,\n alpha: Union[None, float, str],\n fmt: Tuple[Union[None, str, int]],\n style_args: Dict[str, Any],\n ) -> Generator[str, int, None]:\n \"\"\"Returns a generator that yields rendered and formatted frames of the\n underlying image.\n \"\"\"\n self._img = img # For cleanup\n image = self._image\n cached = self._cached\n self._loop_no = repeat = self._repeat\n if cached:\n cache = [(None,) * 2] * image.n_frames\n\n sent = None\n n = 0\n while repeat:\n if sent is None:\n image._seek_position = n\n try:\n frame = image._format_render(\n image._render_image(img, alpha, frame=True, **style_args), *fmt\n )\n except EOFError:\n image._seek_position = n = 0\n if repeat > 0: # Avoid infinitely large negative numbers\n self._loop_no = repeat = repeat - 1\n if cached:\n break\n continue\n else:\n if cached:\n cache[n] = (frame, hash(image.rendered_size))\n\n sent = yield frame\n n = n + 1 if sent is None else sent - 1\n\n if cached:\n n_frames = len(cache)\n while repeat:\n while n < n_frames:\n if sent is None:\n image._seek_position = n\n frame, size_hash = cache[n]\n if hash(image.rendered_size) != size_hash:\n frame = image._format_render(\n image._render_image(img, alpha, frame=True, **style_args),\n *fmt,\n )\n cache[n] = (frame, hash(image.rendered_size))\n\n sent = yield frame\n n = n + 1 if sent is None else sent - 1\n\n image._seek_position = n = 0\n if repeat > 0: # Avoid infinitely large negative numbers\n self._loop_no = repeat = repeat - 1\n\n # For consistency in behaviour\n if img is image._source:\n img.seek(0)", "n_imports_parsed": 7, "n_files_resolved": 4, "n_chars_extracted": 8102}, "tests/test_image/test_block.py::39": {"resolved_imports": ["src/term_image/_ctlseqs.py", "src/term_image/image/block.py", "src/term_image/image/common.py"], "used_names": ["SGR_BG_DIRECT", "SGR_DEFAULT", "_ALPHA_THRESHOLD"], "enclosing_function": "test_transparency", "extracted_code": "# Source: src/term_image/_ctlseqs.py\nSGR_BG_DIRECT = SGR % f\"48;2;{Pm(3)}\"\n\nSGR_DEFAULT = SGR % \"\"\n\n\n# Source: src/term_image/image/common.py\n_ALPHA_THRESHOLD = 40 / 255", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 169}, "tests/test_image/test_kitty.py::36": {"resolved_imports": ["src/term_image/__init__.py", "src/term_image/_ctlseqs.py", "src/term_image/exceptions.py", "src/term_image/image/__init__.py", "src/term_image/image/kitty.py"], "used_names": ["KittyImage", "LINES", "WHOLE", "python_img"], "enclosing_function": "test_set_render_method", "extracted_code": "", "n_imports_parsed": 12, "n_files_resolved": 5, "n_chars_extracted": 0}, "tests/widget/urwid/test_main.py::277": {"resolved_imports": ["src/term_image/__init__.py", "src/term_image/_ctlseqs.py", "src/term_image/exceptions.py", "src/term_image/image/block.py", "src/term_image/image/common.py", "src/term_image/image/iterm2.py", "src/term_image/image/kitty.py", "src/term_image/widget/_urwid.py"], "used_names": ["Size", "UrwidImage", "_ALPHA_THRESHOLD"], "enclosing_function": "test_ignore_padding", "extracted_code": "# Source: src/term_image/image/common.py\nclass Size(Enum):\n \"\"\"Enumeration for :term:`automatic sizing`.\"\"\"\n\n #: Equivalent to :py:attr:`ORIGINAL` if it will fit into the\n #: :term:`frame size`, else :py:attr:`FIT`.\n #:\n #: :meta hide-value:\n AUTO = Hidden()\n\n #: The image size is set to fit optimally **within** the :term:`frame size`.\n #:\n #: :meta hide-value:\n FIT = Hidden()\n\n #: The size is set such that the width is exactly the :term:`frame width`,\n #: regardless of the :term:`cell ratio`.\n #:\n #: :meta hide-value:\n FIT_TO_WIDTH = Hidden()\n\n #: The image size is set such that the image is rendered with as many pixels as the\n #: the original image consists of.\n #:\n #: :meta hide-value:\n ORIGINAL = Hidden()\n\n\n# Source: src/term_image/widget/_urwid.py\nclass UrwidImage(urwid.Widget):\n \"\"\"Image widget (box/flow) for the urwid TUI framework.\n\n Args:\n image: The image to be rendered by the widget.\n format_spec: :ref:`Render format specifier `. Padding width and\n height are ignored.\n upscale: If ``True``, the image will be upscaled to fit maximally within the\n available size, if necessary, while still preserving the aspect ratio.\n Otherwise, the image is never upscaled.\n\n Raises:\n TypeError: An argument is of an inappropriate type.\n ValueError: An argument is of an appropriate type but has an\n unexpected/invalid value.\n term_image.exceptions.StyleError: Invalid style-specific format specifier.\n term_image.exceptions.UrwidImageError: Too many image widgets rendering images\n with the *kitty* render style.\n\n | Any ample space in the widget's render size is filled with spaces.\n | For animated images, the current frame (at render-time) is rendered.\n\n TIP:\n If *image* is of a :ref:`graphics-based ` render style and the\n widget is being used as or within a **flow** widget, with overlays or in any\n other case where the canvas will require vertical trimming, make sure to use a\n render method that splits images across lines such as the **LINES** render\n method for *kitty* and *iterm2* render styles.\n\n NOTE:\n * The `z-index` style-specific format spec field for\n :py:class:`~term_image.image.KittyImage` is ignored as this is used\n internally.\n * A **maximum** of ``2**32 - 2`` instances initialized with\n :py:class:`~term_image.image.KittyImage` instances may exist at the same time.\n\n IMPORTANT:\n This is defined if and only if the ``urwid`` package is available.\n \"\"\"\n\n _sizing = frozenset((urwid.BOX, urwid.FLOW))\n ignore_focus = True\n\n _ti_error_placeholder = None\n\n # For kitty images\n _ti_disguise_state = 0\n _ti_free_z_indexes = set()\n\n # Progresses thus: 1, -1, 2, -2, 3, ..., 2**31 - 1, -(2**31 - 1)\n # This sequence results in shorter image escape sequences compared to starting\n # from -(2**31)\n _ti_next_z_index = 1\n\n def __init__(\n self, image: BaseImage, format_spec: str = \"\", *, upscale: bool = False\n ) -> None:\n if not isinstance(image, BaseImage):\n raise arg_type_error(\"image\", image)\n\n if not isinstance(format_spec, str):\n raise arg_type_error(\"format_spec\", format_spec)\n *fmt, alpha, style_args = image._check_format_spec(format_spec)\n\n if not isinstance(upscale, bool):\n raise arg_type_error(\"upscale\", upscale)\n\n super().__init__()\n self._ti_image = image\n self._ti_h_align, _, self._ti_v_align, _ = fmt\n self._ti_alpha = alpha\n self._ti_style_args = style_args\n self._ti_sizing = Size.FIT if upscale else Size.AUTO\n\n if isinstance(image, TextImage):\n style_args[\"split_cells\"] = True\n elif isinstance(image, KittyImage):\n style_args[\"z_index\"] = self._ti_z_index = self._ti_get_z_index()\n\n # Since Konsole doesn't blend images placed at the same location and\n # z-index, unlike Kitty (and potentially others), `blend=True` is\n # better on Konsole as it reduces/eliminates flicker.\n if get_terminal_name_version()[0] != \"konsole\":\n # To clear directly overlapped images when urwid redraws a line without\n # a change in image position\n style_args[\"blend\"] = False\n\n def __del__(self) -> None:\n if hasattr(self, \"_ti_z_index\"):\n __class__._ti_free_z_indexes.add(self._ti_z_index)\n\n image = property(\n lambda self: self._ti_image,\n doc=\"\"\"\n The image rendered by the widget\n\n :type: BaseImage\n\n GET:\n Returns the image instance rendered by the widget.\n \"\"\",\n )\n\n def render(self, size: Tuple[int, int], focus: bool = False) -> urwid.Canvas:\n image = self._ti_image\n\n if len(size) == 2: # box\n image.set_size(self._ti_sizing, frame_size=size)\n elif len(size) == 1: # flow\n if self._ti_sizing is Size.FIT:\n image.set_size(size[0])\n else:\n fit_size = self._ti_image._valid_size(size[0])\n ori_size = self._ti_image._valid_size(Size.ORIGINAL)\n image._size = (\n ori_size\n if ori_size[0] <= fit_size[0] and ori_size[1] <= fit_size[1]\n else fit_size\n )\n size = (size[0], image._size[1])\n else: # fixed\n raise UrwidImageError(\"Not a fixed widget\")\n\n try:\n render = image._format_render(\n image._renderer(\n image._render_image, self._ti_alpha, **self._ti_style_args\n ),\n self._ti_h_align,\n size[0],\n self._ti_v_align,\n size[1],\n )\n except Exception:\n if type(self)._ti_error_placeholder is None:\n raise\n canv = type(self)._ti_error_placeholder.render(size, focus)\n else:\n canv = UrwidImageCanvas(render, size, image._size)\n\n return canv\n\n def rows(self, size: Tuple[int], focus: bool = False) -> int:\n fit_size = self._ti_image._valid_size(size[0])\n if self._ti_sizing is Size.FIT:\n n_rows = fit_size[1]\n else:\n ori_size = self._ti_image._valid_size(Size.ORIGINAL)\n n_rows = (\n ori_size[1]\n if ori_size[0] <= fit_size[0] and ori_size[1] <= fit_size[1]\n else fit_size[1]\n )\n\n return n_rows\n\n @classmethod\n def set_error_placeholder(cls, widget: Optional[urwid.Widget]) -> None:\n \"\"\"Sets the widget to be rendered in place of an image when rendering fails.\n\n Args:\n widget: The placeholder widget or ``None`` to remove the placeholder.\n\n Raises:\n TypeError: *widget* is not an urwid widget.\n\n If set, any exception raised during rendering is **suppressed** and the\n placeholder is rendered in place of the image.\n \"\"\"\n if not isinstance(widget, urwid.Widget):\n raise arg_type_error(\"widget\", widget)\n\n cls._ti_error_placeholder = widget\n\n @staticmethod\n def _ti_get_z_index() -> int:\n if __class__._ti_free_z_indexes:\n return __class__._ti_free_z_indexes.pop()\n\n z_index = __class__._ti_next_z_index\n if z_index == 2**31:\n raise UrwidImageError(\"Too many image widgets with the kitty render style\")\n __class__._ti_next_z_index = -z_index if z_index > 0 else -z_index + 1\n\n return z_index\n\n def _ti_change_disguise(self) -> None:\n \"\"\"See :py:meth`UrwidImageCanvas._ti_change_disguise`.\"\"\"\n self._ti_disguise_state = (self._ti_disguise_state + 1) % 3", "n_imports_parsed": 10, "n_files_resolved": 8, "n_chars_extracted": 7948}, "tests/test_top_level.py::67": {"resolved_imports": ["src/term_image/__init__.py", "src/term_image/utils.py", "src/term_image/exceptions.py", "src/term_image/geometry.py"], "used_names": ["AutoCellRatio", "Size", "get_cell_ratio", "reset_cell_size_ratio", "set_cell_ratio", "set_cell_size"], "enclosing_function": "test_dynamic", "extracted_code": "# Source: src/term_image/__init__.py\nclass AutoCellRatio(Enum):\n \"\"\":ref:`auto-cell-ratio` enumeration and support status.\n\n .. seealso:: :py:func:`set_cell_ratio`.\n \"\"\"\n\n FIXED = auto()\n \"\"\"Fixed cell ratio.\n\n :meta hide-value:\n \"\"\"\n\n DYNAMIC = auto()\n \"\"\"Dynamic cell ratio.\n\n :meta hide-value:\n \"\"\"\n\n is_supported: ClassVar[bool | None]\n \"\"\"Auto cell ratio support status. Can be\n\n :meta hide-value:\n\n - ``None`` -> support status not yet determined\n - ``True`` -> supported\n - ``False`` -> not supported\n\n Can be explicitly set when using auto cell ratio but want to avoid the support\n check in a situation where the support status is foreknown. Can help to avoid\n being wrongly detected as unsupported on a :ref:`queried `\n terminal that doesn't respond on time.\n\n For instance, when using multiprocessing, if the support status has been\n determined in the main process, this value can simply be passed on to and set\n within the child processes.\n \"\"\"\n\ndef get_cell_ratio() -> float:\n \"\"\"Returns the global :term:`cell ratio`.\n\n .. seealso:: :py:func:`set_cell_ratio`.\n \"\"\"\n # `(1, 2)` is a fallback in case the terminal doesn't respond in time\n return _cell_ratio or truediv(*(get_cell_size() or (1, 2)))\n\ndef set_cell_ratio(ratio: float | AutoCellRatio) -> None:\n \"\"\"Sets the global :term:`cell ratio`.\n\n Args:\n ratio: Can be one of the following values.\n\n * A positive :py:class:`float` value.\n * :py:attr:`AutoCellRatio.FIXED`, the ratio is immediately determined from\n the :term:`active terminal`.\n * :py:attr:`AutoCellRatio.DYNAMIC`, the ratio is determined from the\n :term:`active terminal` whenever :py:func:`get_cell_ratio` is called,\n though with some caching involved, such that the ratio is re-determined\n only if the terminal size changes.\n\n Raises:\n ValueError: *ratio* is a non-positive :py:class:`float`.\n term_image.exceptions.TermImageError: Auto cell ratio is not supported\n in the :term:`active terminal` or on the current platform.\n\n This value is taken into consideration when setting image sizes for **text-based**\n render styles, in order to preserve the aspect ratio of images drawn to the\n terminal.\n\n NOTE:\n Changing the cell ratio does not automatically affect any image that has a\n :term:`fixed size`. For a change in cell ratio to take effect, the image's\n size has to be re-set.\n\n IMPORTANT:\n See :ref:`auto-cell-ratio` for details about the auto modes.\n \"\"\"\n global _cell_ratio\n\n if isinstance(ratio, AutoCellRatio):\n if AutoCellRatio.is_supported is None:\n AutoCellRatio.is_supported = get_cell_size() is not None\n\n if not AutoCellRatio.is_supported:\n raise TermImageError(\n \"Auto cell ratio is not supported in the active terminal or on the \"\n \"current platform\"\n )\n elif ratio is AutoCellRatio.FIXED:\n # `(1, 2)` is a fallback in case the terminal doesn't respond in time\n _cell_ratio = truediv(*(get_cell_size() or (1, 2)))\n else:\n _cell_ratio = None\n else:\n if ratio <= 0.0:\n raise arg_value_error_range(\"ratio\", ratio)\n _cell_ratio = ratio\n\n\n# Source: src/term_image/geometry.py\nclass Size(RawSize):\n \"\"\"The dimensions of a rectangular region.\n\n Raises:\n ValueError: Either dimension is non-positive.\n\n Same as :py:class:`RawSize`, except that both dimensions must be **positive**.\n\n IMPORTANT:\n In the case of multiple inheritance i.e if subclassing this class along with\n other classes, this class should appear last (i.e to the far right) in the\n base class list.\n \"\"\"\n\n __slots__ = ()\n\n def __new__(cls, width: int, height: int) -> Self:\n if width < 1:\n raise arg_value_error_range(\"width\", width)\n if height < 1:\n raise arg_value_error_range(\"height\", height)\n\n # Using `tuple` directly instead of `super()` for performance\n return tuple.__new__(cls, (width, height))", "n_imports_parsed": 6, "n_files_resolved": 4, "n_chars_extracted": 4235}, "tests/test_top_level.py::114": {"resolved_imports": ["src/term_image/__init__.py", "src/term_image/utils.py", "src/term_image/exceptions.py", "src/term_image/geometry.py"], "used_names": ["pytest", "set_query_timeout"], "enclosing_function": "test_invalid", "extracted_code": "# Source: src/term_image/__init__.py\ndef set_query_timeout(timeout: float) -> None:\n \"\"\"Sets the timeout for :ref:`terminal-queries`.\n\n Args:\n timeout: Time limit for awaiting a response from the terminal, in seconds.\n\n Raises:\n ValueError: *timeout* is less than or equal to zero.\n \"\"\"\n if timeout <= 0.0:\n raise arg_value_error_range(\"timeout\", timeout)\n\n utils._query_timeout = timeout", "n_imports_parsed": 6, "n_files_resolved": 4, "n_chars_extracted": 427}, "tests/test_image/test_url.py::30": {"resolved_imports": ["src/term_image/exceptions.py", "src/term_image/image/block.py", "src/term_image/image/common.py", "src/term_image/image/__init__.py"], "used_names": ["BlockImage", "ImageSource", "Size", "URLNotFoundError", "UnidentifiedImageError", "from_url", "os", "pytest"], "enclosing_function": "test_from_url", "extracted_code": "# Source: src/term_image/exceptions.py\nclass URLNotFoundError(TermImageError, FileNotFoundError):\n \"\"\"Raised for 404 errors.\"\"\"\n\n\n# Source: src/term_image/image/block.py\nclass BlockImage(TextImage):\n \"\"\"A render style using unicode half blocks and direct-color colour escape\n sequences.\n\n See :py:class:`TextImage` for the description of the constructor.\n \"\"\"\n\n @classmethod\n def is_supported(cls):\n if cls._supported is None:\n COLORTERM = os.environ.get(\"COLORTERM\") or \"\"\n TERM = os.environ.get(\"TERM\") or \"\"\n cls._supported = (\n \"truecolor\" in COLORTERM or \"24bit\" in COLORTERM or \"256color\" in TERM\n )\n\n return cls._supported\n\n def _get_render_size(self) -> Tuple[int, int]:\n return tuple(map(mul, self.rendered_size, (1, 2)))\n\n @staticmethod\n def _pixels_cols(\n *, pixels: Optional[int] = None, cols: Optional[int] = None\n ) -> int:\n return pixels if pixels is not None else cols\n\n @staticmethod\n def _pixels_lines(\n *, pixels: Optional[int] = None, lines: Optional[int] = None\n ) -> int:\n return ceil(pixels / 2) if pixels is not None else lines * 2\n\n def _render_image(\n self,\n img: PIL.Image.Image,\n alpha: Union[None, float, str],\n *,\n frame: bool = False,\n split_cells: bool = False,\n ) -> str:\n # NOTE:\n # It's more efficient to write separate strings to the buffer separately\n # than concatenate and write together.\n\n def update_buffer():\n if alpha:\n no_alpha = False\n if a_cluster1 == 0 == a_cluster2:\n buf_write(SGR_DEFAULT)\n buf_write(blank * n)\n elif a_cluster1 == 0: # up is transparent\n buf_write(SGR_DEFAULT)\n buf_write(SGR_FG_DIRECT % cluster2)\n buf_write(lower_pixel * n)\n elif a_cluster2 == 0: # down is transparent\n buf_write(SGR_DEFAULT)\n buf_write(SGR_FG_DIRECT % cluster1)\n buf_write(upper_pixel * n)\n else:\n no_alpha = True\n\n if not alpha or no_alpha:\n r, g, b = cluster2\n # Kitty does not render BG colors equal to the default BG color\n if is_on_kitty and cluster2 == bg_color:\n r += r < 255 or -1\n buf_write(SGR_BG_DIRECT % (r, g, b))\n if cluster1 == cluster2:\n buf_write(blank * n)\n else:\n buf_write(SGR_FG_DIRECT % cluster1)\n buf_write(upper_pixel * n)\n\n buffer = io.StringIO()\n buf_write = buffer.write # Eliminate attribute resolution cost\n\n bg_color = get_fg_bg_colors()[1]\n is_on_kitty = self._is_on_kitty()\n if split_cells:\n blank = \" \\0\"\n lower_pixel = LOWER_PIXEL + \"\\0\"\n upper_pixel = UPPER_PIXEL + \"\\0\"\n else:\n blank = \" \"\n lower_pixel = LOWER_PIXEL\n upper_pixel = UPPER_PIXEL\n end_of_line = SGR_DEFAULT + \"\\n\"\n\n width, height = self._get_render_size()\n frame_img = img if frame else None\n img, rgb, a = self._get_render_data(img, alpha, round_alpha=True, frame=frame)\n alpha = img.mode == \"RGBA\"\n\n # clean up (ImageIterator uses one PIL image throughout)\n if frame_img is not img:\n self._close_image(img)\n\n rgb_pairs = (\n (\n zip(rgb[x : x + width], rgb[x + width : x + width * 2]),\n (rgb[x], rgb[x + width]),\n )\n for x in range(0, len(rgb), width * 2)\n )\n a_pairs = (\n (\n zip(a[x : x + width], a[x + width : x + width * 2]),\n (a[x], a[x + width]),\n )\n for x in range(0, len(a), width * 2)\n )\n\n row_no = 0\n # Two rows of pixels per line\n for (rgb_pair, (cluster1, cluster2)), (a_pair, (a_cluster1, a_cluster2)) in zip(\n rgb_pairs, a_pairs\n ):\n row_no += 2\n n = 0\n for (px1, px2), (a1, a2) in zip(rgb_pair, a_pair):\n # Color-code characters and write to buffer\n # when upper and/or lower pixel color/alpha-level changes\n if not (alpha and a1 == a_cluster1 == 0 == a_cluster2 == a2) and (\n px1 != cluster1\n or px2 != cluster2\n or alpha\n and (\n # From non-transparent to transparent\n a_cluster1 != a1 == 0\n or a_cluster2 != a2 == 0\n # From transparent to non-transparent\n or 0 == a_cluster1 != a1\n or 0 == a_cluster2 != a2\n )\n ):\n update_buffer()\n cluster1 = px1\n cluster2 = px2\n if alpha:\n a_cluster1 = a1\n a_cluster2 = a2\n n = 0\n n += 1\n\n update_buffer() # Rest of the line\n if split_cells:\n # Set the last \"\\0\" to be overwritten by the next byte\n buffer.seek(buffer.tell() - 1)\n if row_no < height: # last line not yet rendered\n buf_write(end_of_line)\n\n buf_write(SGR_DEFAULT) # Reset color after last line\n\n with buffer:\n return buffer.getvalue()\n\n\n# Source: src/term_image/image/common.py\nclass ImageSource(Enum):\n \"\"\"Image source type.\"\"\"\n\n #: The instance was derived from a path to a local image file.\n #:\n #: :meta hide-value:\n FILE_PATH = SourceAttr(\"_source\")\n\n #: The instance was derived from a PIL image instance.\n #:\n #: :meta hide-value:\n PIL_IMAGE = SourceAttr(\"_source\")\n\n #: The instance was derived from an image URL.\n #:\n #: :meta hide-value:\n URL = SourceAttr(\"_url\")\n\nclass Size(Enum):\n \"\"\"Enumeration for :term:`automatic sizing`.\"\"\"\n\n #: Equivalent to :py:attr:`ORIGINAL` if it will fit into the\n #: :term:`frame size`, else :py:attr:`FIT`.\n #:\n #: :meta hide-value:\n AUTO = Hidden()\n\n #: The image size is set to fit optimally **within** the :term:`frame size`.\n #:\n #: :meta hide-value:\n FIT = Hidden()\n\n #: The size is set such that the width is exactly the :term:`frame width`,\n #: regardless of the :term:`cell ratio`.\n #:\n #: :meta hide-value:\n FIT_TO_WIDTH = Hidden()\n\n #: The image size is set such that the image is rendered with as many pixels as the\n #: the original image consists of.\n #:\n #: :meta hide-value:\n ORIGINAL = Hidden()\n\n\n# Source: src/term_image/image/__init__.py\ndef from_url(\n url: str,\n **kwargs: Union[None, int],\n) -> BaseImage:\n \"\"\"Creates an image instance from an image URL.\n\n Returns:\n An instance of the automatically selected image render style (as returned by\n :py:func:`auto_image_class`).\n\n Same arguments and raised exceptions as :py:meth:`BaseImage.from_url`.\n \"\"\"\n return auto_image_class().from_url(url, **kwargs)", "n_imports_parsed": 6, "n_files_resolved": 4, "n_chars_extracted": 7364}, "tests/test_image/test_url.py::24": {"resolved_imports": ["src/term_image/exceptions.py", "src/term_image/image/block.py", "src/term_image/image/common.py", "src/term_image/image/__init__.py"], "used_names": ["BlockImage", "ImageSource", "Size", "URLNotFoundError", "UnidentifiedImageError", "from_url", "os", "pytest"], "enclosing_function": "test_from_url", "extracted_code": "# Source: src/term_image/exceptions.py\nclass URLNotFoundError(TermImageError, FileNotFoundError):\n \"\"\"Raised for 404 errors.\"\"\"\n\n\n# Source: src/term_image/image/block.py\nclass BlockImage(TextImage):\n \"\"\"A render style using unicode half blocks and direct-color colour escape\n sequences.\n\n See :py:class:`TextImage` for the description of the constructor.\n \"\"\"\n\n @classmethod\n def is_supported(cls):\n if cls._supported is None:\n COLORTERM = os.environ.get(\"COLORTERM\") or \"\"\n TERM = os.environ.get(\"TERM\") or \"\"\n cls._supported = (\n \"truecolor\" in COLORTERM or \"24bit\" in COLORTERM or \"256color\" in TERM\n )\n\n return cls._supported\n\n def _get_render_size(self) -> Tuple[int, int]:\n return tuple(map(mul, self.rendered_size, (1, 2)))\n\n @staticmethod\n def _pixels_cols(\n *, pixels: Optional[int] = None, cols: Optional[int] = None\n ) -> int:\n return pixels if pixels is not None else cols\n\n @staticmethod\n def _pixels_lines(\n *, pixels: Optional[int] = None, lines: Optional[int] = None\n ) -> int:\n return ceil(pixels / 2) if pixels is not None else lines * 2\n\n def _render_image(\n self,\n img: PIL.Image.Image,\n alpha: Union[None, float, str],\n *,\n frame: bool = False,\n split_cells: bool = False,\n ) -> str:\n # NOTE:\n # It's more efficient to write separate strings to the buffer separately\n # than concatenate and write together.\n\n def update_buffer():\n if alpha:\n no_alpha = False\n if a_cluster1 == 0 == a_cluster2:\n buf_write(SGR_DEFAULT)\n buf_write(blank * n)\n elif a_cluster1 == 0: # up is transparent\n buf_write(SGR_DEFAULT)\n buf_write(SGR_FG_DIRECT % cluster2)\n buf_write(lower_pixel * n)\n elif a_cluster2 == 0: # down is transparent\n buf_write(SGR_DEFAULT)\n buf_write(SGR_FG_DIRECT % cluster1)\n buf_write(upper_pixel * n)\n else:\n no_alpha = True\n\n if not alpha or no_alpha:\n r, g, b = cluster2\n # Kitty does not render BG colors equal to the default BG color\n if is_on_kitty and cluster2 == bg_color:\n r += r < 255 or -1\n buf_write(SGR_BG_DIRECT % (r, g, b))\n if cluster1 == cluster2:\n buf_write(blank * n)\n else:\n buf_write(SGR_FG_DIRECT % cluster1)\n buf_write(upper_pixel * n)\n\n buffer = io.StringIO()\n buf_write = buffer.write # Eliminate attribute resolution cost\n\n bg_color = get_fg_bg_colors()[1]\n is_on_kitty = self._is_on_kitty()\n if split_cells:\n blank = \" \\0\"\n lower_pixel = LOWER_PIXEL + \"\\0\"\n upper_pixel = UPPER_PIXEL + \"\\0\"\n else:\n blank = \" \"\n lower_pixel = LOWER_PIXEL\n upper_pixel = UPPER_PIXEL\n end_of_line = SGR_DEFAULT + \"\\n\"\n\n width, height = self._get_render_size()\n frame_img = img if frame else None\n img, rgb, a = self._get_render_data(img, alpha, round_alpha=True, frame=frame)\n alpha = img.mode == \"RGBA\"\n\n # clean up (ImageIterator uses one PIL image throughout)\n if frame_img is not img:\n self._close_image(img)\n\n rgb_pairs = (\n (\n zip(rgb[x : x + width], rgb[x + width : x + width * 2]),\n (rgb[x], rgb[x + width]),\n )\n for x in range(0, len(rgb), width * 2)\n )\n a_pairs = (\n (\n zip(a[x : x + width], a[x + width : x + width * 2]),\n (a[x], a[x + width]),\n )\n for x in range(0, len(a), width * 2)\n )\n\n row_no = 0\n # Two rows of pixels per line\n for (rgb_pair, (cluster1, cluster2)), (a_pair, (a_cluster1, a_cluster2)) in zip(\n rgb_pairs, a_pairs\n ):\n row_no += 2\n n = 0\n for (px1, px2), (a1, a2) in zip(rgb_pair, a_pair):\n # Color-code characters and write to buffer\n # when upper and/or lower pixel color/alpha-level changes\n if not (alpha and a1 == a_cluster1 == 0 == a_cluster2 == a2) and (\n px1 != cluster1\n or px2 != cluster2\n or alpha\n and (\n # From non-transparent to transparent\n a_cluster1 != a1 == 0\n or a_cluster2 != a2 == 0\n # From transparent to non-transparent\n or 0 == a_cluster1 != a1\n or 0 == a_cluster2 != a2\n )\n ):\n update_buffer()\n cluster1 = px1\n cluster2 = px2\n if alpha:\n a_cluster1 = a1\n a_cluster2 = a2\n n = 0\n n += 1\n\n update_buffer() # Rest of the line\n if split_cells:\n # Set the last \"\\0\" to be overwritten by the next byte\n buffer.seek(buffer.tell() - 1)\n if row_no < height: # last line not yet rendered\n buf_write(end_of_line)\n\n buf_write(SGR_DEFAULT) # Reset color after last line\n\n with buffer:\n return buffer.getvalue()\n\n\n# Source: src/term_image/image/common.py\nclass ImageSource(Enum):\n \"\"\"Image source type.\"\"\"\n\n #: The instance was derived from a path to a local image file.\n #:\n #: :meta hide-value:\n FILE_PATH = SourceAttr(\"_source\")\n\n #: The instance was derived from a PIL image instance.\n #:\n #: :meta hide-value:\n PIL_IMAGE = SourceAttr(\"_source\")\n\n #: The instance was derived from an image URL.\n #:\n #: :meta hide-value:\n URL = SourceAttr(\"_url\")\n\nclass Size(Enum):\n \"\"\"Enumeration for :term:`automatic sizing`.\"\"\"\n\n #: Equivalent to :py:attr:`ORIGINAL` if it will fit into the\n #: :term:`frame size`, else :py:attr:`FIT`.\n #:\n #: :meta hide-value:\n AUTO = Hidden()\n\n #: The image size is set to fit optimally **within** the :term:`frame size`.\n #:\n #: :meta hide-value:\n FIT = Hidden()\n\n #: The size is set such that the width is exactly the :term:`frame width`,\n #: regardless of the :term:`cell ratio`.\n #:\n #: :meta hide-value:\n FIT_TO_WIDTH = Hidden()\n\n #: The image size is set such that the image is rendered with as many pixels as the\n #: the original image consists of.\n #:\n #: :meta hide-value:\n ORIGINAL = Hidden()\n\n\n# Source: src/term_image/image/__init__.py\ndef from_url(\n url: str,\n **kwargs: Union[None, int],\n) -> BaseImage:\n \"\"\"Creates an image instance from an image URL.\n\n Returns:\n An instance of the automatically selected image render style (as returned by\n :py:func:`auto_image_class`).\n\n Same arguments and raised exceptions as :py:meth:`BaseImage.from_url`.\n \"\"\"\n return auto_image_class().from_url(url, **kwargs)", "n_imports_parsed": 6, "n_files_resolved": 4, "n_chars_extracted": 7364}, "tests/widget/urwid/test_main.py::63": {"resolved_imports": ["src/term_image/__init__.py", "src/term_image/_ctlseqs.py", "src/term_image/exceptions.py", "src/term_image/image/block.py", "src/term_image/image/common.py", "src/term_image/image/iterm2.py", "src/term_image/image/kitty.py", "src/term_image/widget/_urwid.py"], "used_names": ["BlockImage", "Image", "RenderError", "UrwidImage", "pytest", "urwid"], "enclosing_function": "test_error_placeholder", "extracted_code": "# Source: src/term_image/exceptions.py\nclass RenderError(TermImageError):\n \"\"\"...\"\"\"\n\n\n# Source: src/term_image/image/block.py\nclass BlockImage(TextImage):\n \"\"\"A render style using unicode half blocks and direct-color colour escape\n sequences.\n\n See :py:class:`TextImage` for the description of the constructor.\n \"\"\"\n\n @classmethod\n def is_supported(cls):\n if cls._supported is None:\n COLORTERM = os.environ.get(\"COLORTERM\") or \"\"\n TERM = os.environ.get(\"TERM\") or \"\"\n cls._supported = (\n \"truecolor\" in COLORTERM or \"24bit\" in COLORTERM or \"256color\" in TERM\n )\n\n return cls._supported\n\n def _get_render_size(self) -> Tuple[int, int]:\n return tuple(map(mul, self.rendered_size, (1, 2)))\n\n @staticmethod\n def _pixels_cols(\n *, pixels: Optional[int] = None, cols: Optional[int] = None\n ) -> int:\n return pixels if pixels is not None else cols\n\n @staticmethod\n def _pixels_lines(\n *, pixels: Optional[int] = None, lines: Optional[int] = None\n ) -> int:\n return ceil(pixels / 2) if pixels is not None else lines * 2\n\n def _render_image(\n self,\n img: PIL.Image.Image,\n alpha: Union[None, float, str],\n *,\n frame: bool = False,\n split_cells: bool = False,\n ) -> str:\n # NOTE:\n # It's more efficient to write separate strings to the buffer separately\n # than concatenate and write together.\n\n def update_buffer():\n if alpha:\n no_alpha = False\n if a_cluster1 == 0 == a_cluster2:\n buf_write(SGR_DEFAULT)\n buf_write(blank * n)\n elif a_cluster1 == 0: # up is transparent\n buf_write(SGR_DEFAULT)\n buf_write(SGR_FG_DIRECT % cluster2)\n buf_write(lower_pixel * n)\n elif a_cluster2 == 0: # down is transparent\n buf_write(SGR_DEFAULT)\n buf_write(SGR_FG_DIRECT % cluster1)\n buf_write(upper_pixel * n)\n else:\n no_alpha = True\n\n if not alpha or no_alpha:\n r, g, b = cluster2\n # Kitty does not render BG colors equal to the default BG color\n if is_on_kitty and cluster2 == bg_color:\n r += r < 255 or -1\n buf_write(SGR_BG_DIRECT % (r, g, b))\n if cluster1 == cluster2:\n buf_write(blank * n)\n else:\n buf_write(SGR_FG_DIRECT % cluster1)\n buf_write(upper_pixel * n)\n\n buffer = io.StringIO()\n buf_write = buffer.write # Eliminate attribute resolution cost\n\n bg_color = get_fg_bg_colors()[1]\n is_on_kitty = self._is_on_kitty()\n if split_cells:\n blank = \" \\0\"\n lower_pixel = LOWER_PIXEL + \"\\0\"\n upper_pixel = UPPER_PIXEL + \"\\0\"\n else:\n blank = \" \"\n lower_pixel = LOWER_PIXEL\n upper_pixel = UPPER_PIXEL\n end_of_line = SGR_DEFAULT + \"\\n\"\n\n width, height = self._get_render_size()\n frame_img = img if frame else None\n img, rgb, a = self._get_render_data(img, alpha, round_alpha=True, frame=frame)\n alpha = img.mode == \"RGBA\"\n\n # clean up (ImageIterator uses one PIL image throughout)\n if frame_img is not img:\n self._close_image(img)\n\n rgb_pairs = (\n (\n zip(rgb[x : x + width], rgb[x + width : x + width * 2]),\n (rgb[x], rgb[x + width]),\n )\n for x in range(0, len(rgb), width * 2)\n )\n a_pairs = (\n (\n zip(a[x : x + width], a[x + width : x + width * 2]),\n (a[x], a[x + width]),\n )\n for x in range(0, len(a), width * 2)\n )\n\n row_no = 0\n # Two rows of pixels per line\n for (rgb_pair, (cluster1, cluster2)), (a_pair, (a_cluster1, a_cluster2)) in zip(\n rgb_pairs, a_pairs\n ):\n row_no += 2\n n = 0\n for (px1, px2), (a1, a2) in zip(rgb_pair, a_pair):\n # Color-code characters and write to buffer\n # when upper and/or lower pixel color/alpha-level changes\n if not (alpha and a1 == a_cluster1 == 0 == a_cluster2 == a2) and (\n px1 != cluster1\n or px2 != cluster2\n or alpha\n and (\n # From non-transparent to transparent\n a_cluster1 != a1 == 0\n or a_cluster2 != a2 == 0\n # From transparent to non-transparent\n or 0 == a_cluster1 != a1\n or 0 == a_cluster2 != a2\n )\n ):\n update_buffer()\n cluster1 = px1\n cluster2 = px2\n if alpha:\n a_cluster1 = a1\n a_cluster2 = a2\n n = 0\n n += 1\n\n update_buffer() # Rest of the line\n if split_cells:\n # Set the last \"\\0\" to be overwritten by the next byte\n buffer.seek(buffer.tell() - 1)\n if row_no < height: # last line not yet rendered\n buf_write(end_of_line)\n\n buf_write(SGR_DEFAULT) # Reset color after last line\n\n with buffer:\n return buffer.getvalue()\n\n\n# Source: src/term_image/widget/_urwid.py\nclass UrwidImage(urwid.Widget):\n \"\"\"Image widget (box/flow) for the urwid TUI framework.\n\n Args:\n image: The image to be rendered by the widget.\n format_spec: :ref:`Render format specifier `. Padding width and\n height are ignored.\n upscale: If ``True``, the image will be upscaled to fit maximally within the\n available size, if necessary, while still preserving the aspect ratio.\n Otherwise, the image is never upscaled.\n\n Raises:\n TypeError: An argument is of an inappropriate type.\n ValueError: An argument is of an appropriate type but has an\n unexpected/invalid value.\n term_image.exceptions.StyleError: Invalid style-specific format specifier.\n term_image.exceptions.UrwidImageError: Too many image widgets rendering images\n with the *kitty* render style.\n\n | Any ample space in the widget's render size is filled with spaces.\n | For animated images, the current frame (at render-time) is rendered.\n\n TIP:\n If *image* is of a :ref:`graphics-based ` render style and the\n widget is being used as or within a **flow** widget, with overlays or in any\n other case where the canvas will require vertical trimming, make sure to use a\n render method that splits images across lines such as the **LINES** render\n method for *kitty* and *iterm2* render styles.\n\n NOTE:\n * The `z-index` style-specific format spec field for\n :py:class:`~term_image.image.KittyImage` is ignored as this is used\n internally.\n * A **maximum** of ``2**32 - 2`` instances initialized with\n :py:class:`~term_image.image.KittyImage` instances may exist at the same time.\n\n IMPORTANT:\n This is defined if and only if the ``urwid`` package is available.\n \"\"\"\n\n _sizing = frozenset((urwid.BOX, urwid.FLOW))\n ignore_focus = True\n\n _ti_error_placeholder = None\n\n # For kitty images\n _ti_disguise_state = 0\n _ti_free_z_indexes = set()\n\n # Progresses thus: 1, -1, 2, -2, 3, ..., 2**31 - 1, -(2**31 - 1)\n # This sequence results in shorter image escape sequences compared to starting\n # from -(2**31)\n _ti_next_z_index = 1\n\n def __init__(\n self, image: BaseImage, format_spec: str = \"\", *, upscale: bool = False\n ) -> None:\n if not isinstance(image, BaseImage):\n raise arg_type_error(\"image\", image)\n\n if not isinstance(format_spec, str):\n raise arg_type_error(\"format_spec\", format_spec)\n *fmt, alpha, style_args = image._check_format_spec(format_spec)\n\n if not isinstance(upscale, bool):\n raise arg_type_error(\"upscale\", upscale)\n\n super().__init__()\n self._ti_image = image\n self._ti_h_align, _, self._ti_v_align, _ = fmt\n self._ti_alpha = alpha\n self._ti_style_args = style_args\n self._ti_sizing = Size.FIT if upscale else Size.AUTO\n\n if isinstance(image, TextImage):\n style_args[\"split_cells\"] = True\n elif isinstance(image, KittyImage):\n style_args[\"z_index\"] = self._ti_z_index = self._ti_get_z_index()\n\n # Since Konsole doesn't blend images placed at the same location and\n # z-index, unlike Kitty (and potentially others), `blend=True` is\n # better on Konsole as it reduces/eliminates flicker.\n if get_terminal_name_version()[0] != \"konsole\":\n # To clear directly overlapped images when urwid redraws a line without\n # a change in image position\n style_args[\"blend\"] = False\n\n def __del__(self) -> None:\n if hasattr(self, \"_ti_z_index\"):\n __class__._ti_free_z_indexes.add(self._ti_z_index)\n\n image = property(\n lambda self: self._ti_image,\n doc=\"\"\"\n The image rendered by the widget\n\n :type: BaseImage\n\n GET:\n Returns the image instance rendered by the widget.\n \"\"\",\n )\n\n def render(self, size: Tuple[int, int], focus: bool = False) -> urwid.Canvas:\n image = self._ti_image\n\n if len(size) == 2: # box\n image.set_size(self._ti_sizing, frame_size=size)\n elif len(size) == 1: # flow\n if self._ti_sizing is Size.FIT:\n image.set_size(size[0])\n else:\n fit_size = self._ti_image._valid_size(size[0])\n ori_size = self._ti_image._valid_size(Size.ORIGINAL)\n image._size = (\n ori_size\n if ori_size[0] <= fit_size[0] and ori_size[1] <= fit_size[1]\n else fit_size\n )\n size = (size[0], image._size[1])\n else: # fixed\n raise UrwidImageError(\"Not a fixed widget\")\n\n try:\n render = image._format_render(\n image._renderer(\n image._render_image, self._ti_alpha, **self._ti_style_args\n ),\n self._ti_h_align,\n size[0],\n self._ti_v_align,\n size[1],\n )\n except Exception:\n if type(self)._ti_error_placeholder is None:\n raise\n canv = type(self)._ti_error_placeholder.render(size, focus)\n else:\n canv = UrwidImageCanvas(render, size, image._size)\n\n return canv\n\n def rows(self, size: Tuple[int], focus: bool = False) -> int:\n fit_size = self._ti_image._valid_size(size[0])\n if self._ti_sizing is Size.FIT:\n n_rows = fit_size[1]\n else:\n ori_size = self._ti_image._valid_size(Size.ORIGINAL)\n n_rows = (\n ori_size[1]\n if ori_size[0] <= fit_size[0] and ori_size[1] <= fit_size[1]\n else fit_size[1]\n )\n\n return n_rows\n\n @classmethod\n def set_error_placeholder(cls, widget: Optional[urwid.Widget]) -> None:\n \"\"\"Sets the widget to be rendered in place of an image when rendering fails.\n\n Args:\n widget: The placeholder widget or ``None`` to remove the placeholder.\n\n Raises:\n TypeError: *widget* is not an urwid widget.\n\n If set, any exception raised during rendering is **suppressed** and the\n placeholder is rendered in place of the image.\n \"\"\"\n if not isinstance(widget, urwid.Widget):\n raise arg_type_error(\"widget\", widget)\n\n cls._ti_error_placeholder = widget\n\n @staticmethod\n def _ti_get_z_index() -> int:\n if __class__._ti_free_z_indexes:\n return __class__._ti_free_z_indexes.pop()\n\n z_index = __class__._ti_next_z_index\n if z_index == 2**31:\n raise UrwidImageError(\"Too many image widgets with the kitty render style\")\n __class__._ti_next_z_index = -z_index if z_index > 0 else -z_index + 1\n\n return z_index\n\n def _ti_change_disguise(self) -> None:\n \"\"\"See :py:meth`UrwidImageCanvas._ti_change_disguise`.\"\"\"\n self._ti_disguise_state = (self._ti_disguise_state + 1) % 3", "n_imports_parsed": 10, "n_files_resolved": 8, "n_chars_extracted": 12826}, "tests/test_padding.py::385": {"resolved_imports": ["src/term_image/_ctlseqs.py", "src/term_image/geometry.py", "src/term_image/padding.py"], "used_names": ["ExactPadding"], "enclosing_function": "test_left", "extracted_code": "# Source: src/term_image/padding.py\nclass ExactPadding(Padding):\n \"\"\"Exact :term:`render output` padding.\n\n Args:\n left: Left padding dimension\n top: Top padding dimension.\n right: Right padding dimension\n bottom: Bottom padding dimension\n\n Raises:\n ValueError: A dimension is negative.\n\n Pads a render output on each side by the specified amount of lines or columns.\n\n TIP:\n * Instances are immutable and hashable.\n * Instances with equal fields compare equal.\n \"\"\"\n\n # Class Attributes =========================================================\n\n __slots__ = (\"left\", \"top\", \"right\", \"bottom\")\n\n # Instance Attributes ======================================================\n\n left: int\n \"\"\"Left padding dimension\"\"\"\n\n top: int\n \"\"\"Top padding dimension\"\"\"\n\n right: int\n \"\"\"Right padding dimension\"\"\"\n\n bottom: int\n \"\"\"Bottom padding dimension\"\"\"\n\n fill: str\n\n # Special Methods ==========================================================\n\n def __init__(\n self,\n left: int = 0,\n top: int = 0,\n right: int = 0,\n bottom: int = 0,\n fill: str = \" \",\n ) -> None:\n super().__init__(fill)\n\n _setattr = super().__setattr__\n for name in (\"left\", \"top\", \"right\", \"bottom\"):\n value = locals()[name]\n if value < 0:\n raise arg_value_error_range(name, value)\n _setattr(name, value)\n\n # Properties ===============================================================\n\n @property\n def dimensions(self) -> tuple[int, int, int, int]:\n \"\"\"Padding dimensions\n\n GET:\n Returns the padding dimensions, ``(left, top, right, bottom)``.\n \"\"\"\n return astuple(self)[:4]\n\n # Extension methods ========================================================\n\n @override\n def _get_exact_dimensions_(self, render_size: Size) -> tuple[int, int, int, int]:\n return astuple(self)[:4]", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 2021}, "tests/widget/urwid/test_screen.py::265": {"resolved_imports": ["src/term_image/__init__.py", "src/term_image/_ctlseqs.py", "src/term_image/image/block.py", "src/term_image/image/iterm2.py", "src/term_image/image/kitty.py", "src/term_image/widget/_urwid.py"], "used_names": ["get_terminal_name_version", "set_terminal_name_version"], "enclosing_function": "test_move_top_widget", "extracted_code": "", "n_imports_parsed": 10, "n_files_resolved": 6, "n_chars_extracted": 0}, "tests/test_geometry.py::30": {"resolved_imports": ["src/term_image/geometry.py"], "used_names": ["RawSize"], "enclosing_function": "test_instance_type", "extracted_code": "# Source: src/term_image/geometry.py\nclass RawSize(NamedTuple):\n \"\"\"The dimensions of a rectangular region.\n\n Args:\n width: The horizontal dimension\n height: The vertical dimension\n\n NOTE:\n * A dimension may be non-positive but the validity and meaning would be\n determined by the receiving interface.\n * This is a subclass of :py:class:`tuple`. Hence, instances can be used anyway\n and anywhere tuples can.\n \"\"\"\n\n width: int\n height: int\n\n @classmethod\n def _new(cls, width: int, height: int) -> Self:\n \"\"\"Alternate constructor for internal use only.\"\"\"\n return tuple.__new__(cls, (width, height))", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 682}, "tests/test_image/test_url.py::37": {"resolved_imports": ["src/term_image/exceptions.py", "src/term_image/image/block.py", "src/term_image/image/common.py", "src/term_image/image/__init__.py"], "used_names": ["BlockImage", "ImageSource", "Size", "URLNotFoundError", "UnidentifiedImageError", "from_url", "os", "pytest"], "enclosing_function": "test_from_url", "extracted_code": "# Source: src/term_image/exceptions.py\nclass URLNotFoundError(TermImageError, FileNotFoundError):\n \"\"\"Raised for 404 errors.\"\"\"\n\n\n# Source: src/term_image/image/block.py\nclass BlockImage(TextImage):\n \"\"\"A render style using unicode half blocks and direct-color colour escape\n sequences.\n\n See :py:class:`TextImage` for the description of the constructor.\n \"\"\"\n\n @classmethod\n def is_supported(cls):\n if cls._supported is None:\n COLORTERM = os.environ.get(\"COLORTERM\") or \"\"\n TERM = os.environ.get(\"TERM\") or \"\"\n cls._supported = (\n \"truecolor\" in COLORTERM or \"24bit\" in COLORTERM or \"256color\" in TERM\n )\n\n return cls._supported\n\n def _get_render_size(self) -> Tuple[int, int]:\n return tuple(map(mul, self.rendered_size, (1, 2)))\n\n @staticmethod\n def _pixels_cols(\n *, pixels: Optional[int] = None, cols: Optional[int] = None\n ) -> int:\n return pixels if pixels is not None else cols\n\n @staticmethod\n def _pixels_lines(\n *, pixels: Optional[int] = None, lines: Optional[int] = None\n ) -> int:\n return ceil(pixels / 2) if pixels is not None else lines * 2\n\n def _render_image(\n self,\n img: PIL.Image.Image,\n alpha: Union[None, float, str],\n *,\n frame: bool = False,\n split_cells: bool = False,\n ) -> str:\n # NOTE:\n # It's more efficient to write separate strings to the buffer separately\n # than concatenate and write together.\n\n def update_buffer():\n if alpha:\n no_alpha = False\n if a_cluster1 == 0 == a_cluster2:\n buf_write(SGR_DEFAULT)\n buf_write(blank * n)\n elif a_cluster1 == 0: # up is transparent\n buf_write(SGR_DEFAULT)\n buf_write(SGR_FG_DIRECT % cluster2)\n buf_write(lower_pixel * n)\n elif a_cluster2 == 0: # down is transparent\n buf_write(SGR_DEFAULT)\n buf_write(SGR_FG_DIRECT % cluster1)\n buf_write(upper_pixel * n)\n else:\n no_alpha = True\n\n if not alpha or no_alpha:\n r, g, b = cluster2\n # Kitty does not render BG colors equal to the default BG color\n if is_on_kitty and cluster2 == bg_color:\n r += r < 255 or -1\n buf_write(SGR_BG_DIRECT % (r, g, b))\n if cluster1 == cluster2:\n buf_write(blank * n)\n else:\n buf_write(SGR_FG_DIRECT % cluster1)\n buf_write(upper_pixel * n)\n\n buffer = io.StringIO()\n buf_write = buffer.write # Eliminate attribute resolution cost\n\n bg_color = get_fg_bg_colors()[1]\n is_on_kitty = self._is_on_kitty()\n if split_cells:\n blank = \" \\0\"\n lower_pixel = LOWER_PIXEL + \"\\0\"\n upper_pixel = UPPER_PIXEL + \"\\0\"\n else:\n blank = \" \"\n lower_pixel = LOWER_PIXEL\n upper_pixel = UPPER_PIXEL\n end_of_line = SGR_DEFAULT + \"\\n\"\n\n width, height = self._get_render_size()\n frame_img = img if frame else None\n img, rgb, a = self._get_render_data(img, alpha, round_alpha=True, frame=frame)\n alpha = img.mode == \"RGBA\"\n\n # clean up (ImageIterator uses one PIL image throughout)\n if frame_img is not img:\n self._close_image(img)\n\n rgb_pairs = (\n (\n zip(rgb[x : x + width], rgb[x + width : x + width * 2]),\n (rgb[x], rgb[x + width]),\n )\n for x in range(0, len(rgb), width * 2)\n )\n a_pairs = (\n (\n zip(a[x : x + width], a[x + width : x + width * 2]),\n (a[x], a[x + width]),\n )\n for x in range(0, len(a), width * 2)\n )\n\n row_no = 0\n # Two rows of pixels per line\n for (rgb_pair, (cluster1, cluster2)), (a_pair, (a_cluster1, a_cluster2)) in zip(\n rgb_pairs, a_pairs\n ):\n row_no += 2\n n = 0\n for (px1, px2), (a1, a2) in zip(rgb_pair, a_pair):\n # Color-code characters and write to buffer\n # when upper and/or lower pixel color/alpha-level changes\n if not (alpha and a1 == a_cluster1 == 0 == a_cluster2 == a2) and (\n px1 != cluster1\n or px2 != cluster2\n or alpha\n and (\n # From non-transparent to transparent\n a_cluster1 != a1 == 0\n or a_cluster2 != a2 == 0\n # From transparent to non-transparent\n or 0 == a_cluster1 != a1\n or 0 == a_cluster2 != a2\n )\n ):\n update_buffer()\n cluster1 = px1\n cluster2 = px2\n if alpha:\n a_cluster1 = a1\n a_cluster2 = a2\n n = 0\n n += 1\n\n update_buffer() # Rest of the line\n if split_cells:\n # Set the last \"\\0\" to be overwritten by the next byte\n buffer.seek(buffer.tell() - 1)\n if row_no < height: # last line not yet rendered\n buf_write(end_of_line)\n\n buf_write(SGR_DEFAULT) # Reset color after last line\n\n with buffer:\n return buffer.getvalue()\n\n\n# Source: src/term_image/image/common.py\nclass ImageSource(Enum):\n \"\"\"Image source type.\"\"\"\n\n #: The instance was derived from a path to a local image file.\n #:\n #: :meta hide-value:\n FILE_PATH = SourceAttr(\"_source\")\n\n #: The instance was derived from a PIL image instance.\n #:\n #: :meta hide-value:\n PIL_IMAGE = SourceAttr(\"_source\")\n\n #: The instance was derived from an image URL.\n #:\n #: :meta hide-value:\n URL = SourceAttr(\"_url\")\n\nclass Size(Enum):\n \"\"\"Enumeration for :term:`automatic sizing`.\"\"\"\n\n #: Equivalent to :py:attr:`ORIGINAL` if it will fit into the\n #: :term:`frame size`, else :py:attr:`FIT`.\n #:\n #: :meta hide-value:\n AUTO = Hidden()\n\n #: The image size is set to fit optimally **within** the :term:`frame size`.\n #:\n #: :meta hide-value:\n FIT = Hidden()\n\n #: The size is set such that the width is exactly the :term:`frame width`,\n #: regardless of the :term:`cell ratio`.\n #:\n #: :meta hide-value:\n FIT_TO_WIDTH = Hidden()\n\n #: The image size is set such that the image is rendered with as many pixels as the\n #: the original image consists of.\n #:\n #: :meta hide-value:\n ORIGINAL = Hidden()\n\n\n# Source: src/term_image/image/__init__.py\ndef from_url(\n url: str,\n **kwargs: Union[None, int],\n) -> BaseImage:\n \"\"\"Creates an image instance from an image URL.\n\n Returns:\n An instance of the automatically selected image render style (as returned by\n :py:func:`auto_image_class`).\n\n Same arguments and raised exceptions as :py:meth:`BaseImage.from_url`.\n \"\"\"\n return auto_image_class().from_url(url, **kwargs)", "n_imports_parsed": 6, "n_files_resolved": 4, "n_chars_extracted": 7364}, "tests/widget/urwid/test_screen.py::442": {"resolved_imports": ["src/term_image/__init__.py", "src/term_image/_ctlseqs.py", "src/term_image/image/block.py", "src/term_image/image/iterm2.py", "src/term_image/image/kitty.py", "src/term_image/widget/_urwid.py"], "used_names": ["get_terminal_name_version", "set_terminal_name_version"], "enclosing_function": "test_change_top_widget", "extracted_code": "", "n_imports_parsed": 10, "n_files_resolved": 6, "n_chars_extracted": 0}, "tests/render/test_iterator.py::377": {"resolved_imports": ["src/term_image/geometry.py", "src/term_image/padding.py", "src/term_image/render/_iterator.py", "src/term_image/renderable/_enum.py", "src/term_image/renderable/_renderable.py", "src/term_image/renderable/_types.py"], "used_names": ["RenderIterator"], "enclosing_function": "test_after_seek", "extracted_code": "# Source: src/term_image/render/_iterator.py\nclass RenderIterator:\n \"\"\"An iterator for efficient iteration over :term:`rendered` frames of an\n :term:`animated` renderable.\n\n Args:\n renderable: An animated renderable.\n render_args: Render arguments.\n padding: :term:`Render output` padding.\n loops: The number of times to go over all frames.\n\n * ``< 0`` -> loop infinitely.\n * ``0`` -> invalid.\n * ``> 0`` -> loop the given number of times.\n\n .. note::\n The value is ignored and taken to be ``1`` (one), if *renderable* has\n :py:class:`~term_image.renderable.FrameCount.INDEFINITE` frame count.\n\n cache: Determines if :term:`rendered` frames are cached.\n\n If the value is ``True`` or a positive integer greater than or equal to the\n frame count of *renderable*, caching is enabled. Otherwise i.e ``False`` or\n a positive integer less than the frame count, caching is disabled.\n\n .. note::\n The value is ignored and taken to be ``False``, if *renderable* has\n :py:class:`~term_image.renderable.FrameCount.INDEFINITE` frame count.\n\n Raises:\n ValueError: An argument has an invalid value.\n IncompatibleRenderArgsError: Incompatible render arguments.\n\n The iterator yields a :py:class:`~term_image.renderable.Frame` instance on every\n iteration.\n\n NOTE:\n * Seeking the underlying renderable\n (via :py:meth:`Renderable.seek() `)\n does not affect an iterator, use :py:meth:`RenderIterator.seek` instead.\n Likewise, the iterator does not modify the underlying renderable's current\n frame number.\n * Changes to the underlying renderable's :term:`render size` does not affect\n an iterator's :term:`render outputs`, use :py:meth:`set_render_size` instead.\n * Changes to the underlying renderable's\n :py:attr:`~term_image.renderable.Renderable.frame_duration` does not affect\n the value yiedled by an iterator, the value when initializing the iterator\n is what it will use.\n * :py:exc:`StopDefiniteIterationError` is raised when a renderable with\n *definite* frame count raises :py:exc:`StopIteration` when rendering a frame.\n\n .. seealso::\n\n :py:meth:`Renderable.__iter__() `\n Renderables are iterable\n\n :ref:`render-iterator-ext-api`\n :py:class:`RenderIterator`\\\\ 's Extension API\n \"\"\"\n\n # Instance Attributes ======================================================\n\n loop: int\n \"\"\"Iteration loop countdown\n\n * A negative integer, if iteration is infinite.\n * Otherwise, the current iteration loop countdown value.\n\n * Starts from the value of the *loops* constructor argument,\n * decreases by one upon rendering the first frame of every loop after the\n first,\n * and ends at zero after the iterator is exhausted.\n\n NOTE:\n Modifying this doesn't affect the iterator.\n \"\"\"\n\n _cached: bool\n _closed: bool\n _finalize_data: bool\n _iterator: Generator[Frame, None, None]\n _loops: int\n _padding: Padding\n _padded_size: Size\n _render_args: RenderArgs\n _render_data: RenderData\n _renderable: Renderable\n _renderable_data: RenderableData\n\n # Special Methods ==========================================================\n\n def __init__(\n self,\n renderable: Renderable,\n render_args: RenderArgs | None = None,\n padding: Padding = ExactPadding(),\n loops: int = 1,\n cache: bool | int = 100,\n ) -> None:\n self._init(renderable, render_args, padding, loops, cache)\n self._iterator, self._padding = renderable._init_render_(\n self._iterate, render_args, padding, iteration=True, finalize=False\n )\n self._finalize_data = True\n next(self._iterator)\n\n def __del__(self) -> None:\n try:\n self.close()\n except AttributeError:\n pass\n\n def __iter__(self) -> Self:\n return self\n\n def __next__(self) -> Frame:\n try:\n return next(self._iterator)\n except StopIteration:\n self.close()\n raise StopIteration(\"Iteration has ended\") from None\n except AttributeError:\n if self._closed:\n raise StopIteration(\"This iterator has been finalized\") from None\n else:\n self.close()\n raise\n except Exception:\n self.close()\n raise\n\n def __repr__(self) -> str:\n return (\n f\"<{type(self).__name__}: \"\n f\"type(renderable)={type(self._renderable).__name__}, \"\n f\"frame_count={self._renderable.frame_count}, loops={self._loops}, \"\n f\"loop={self.loop}, cached={self._cached}>\"\n )\n\n # Public Methods ===========================================================\n\n def close(self) -> None:\n \"\"\"Finalizes the iterator and releases resources used.\n\n NOTE:\n This method is automatically called when the iterator is exhausted or\n garbage-collected but it's recommended to call it manually if iteration\n is ended prematurely (i.e before the iterator itself is exhausted),\n especially if frames are cached.\n\n This method is safe for multiple invocations.\n \"\"\"\n if not self._closed:\n self._iterator.close()\n del self._iterator\n if self._finalize_data:\n self._render_data.finalize()\n del self._render_data\n self._closed = True\n\n def seek(self, offset: int, whence: Seek = Seek.START) -> None:\n \"\"\"Sets the frame to be rendered on the next iteration, without affecting\n the loop count.\n\n Args:\n offset: Frame offset (relative to *whence*).\n whence: Reference position for *offset*.\n\n Raises:\n FinalizedIteratorError: The iterator has been finalized.\n ValueError: *offset* is out of range.\n\n The value range for *offset* depends on the\n :py:attr:`~term_image.renderable.Renderable.frame_count` of the underlying\n renderable and *whence*:\n\n .. list-table:: *definite* frame count\n :align: left\n :header-rows: 1\n :width: 90%\n :widths: auto\n\n * - *whence*\n - Valid value range for *offset*\n\n * - :py:attr:`~term_image.renderable.Seek.START`\n - ``0`` <= *offset*\n < :py:attr:`~term_image.renderable.Renderable.frame_count`\n * - :py:attr:`~term_image.renderable.Seek.CURRENT`\n - -*next_frame_number* [#ri-nf]_ <= *offset*\n < :py:attr:`~term_image.renderable.Renderable.frame_count`\n - *next_frame_number*\n * - :py:attr:`~term_image.renderable.Seek.END`\n - -:py:attr:`~term_image.renderable.Renderable.frame_count` < *offset*\n <= ``0``\n\n .. list-table:: :py:attr:`~term_image.renderable.FrameCount.INDEFINITE` frame\n count\n :align: left\n :header-rows: 1\n :width: 90%\n :widths: auto\n\n * - *whence*\n - Valid value range for *offset*\n\n * - :py:attr:`~term_image.renderable.Seek.START`\n - ``0`` <= *offset*\n * - :py:attr:`~term_image.renderable.Seek.CURRENT`\n - *any value*\n * - :py:attr:`~term_image.renderable.Seek.END`\n - *offset* <= ``0``\n\n NOTE:\n If the underlying renderable has *definite* frame count, seek operations\n have **immeditate** effect. Hence, multiple consecutive seek operations,\n starting with any kind and followed by one or more with *whence* =\n :py:attr:`~term_image.renderable.Seek.CURRENT`, between any two\n consecutive renders have a **cumulative** effect. In particular, any seek\n operation with *whence* = :py:attr:`~term_image.renderable.Seek.CURRENT`\n is relative to the frame to be rendered next [#ri-nf]_.\n\n .. collapse:: Example\n\n >>> animated_renderable.frame_count\n 10\n >>> render_iter = RenderIterator(animated_renderable) # next = 0\n >>> render_iter.seek(5) # next = 5\n >>> next(render_iter).number # next = 5 + 1 = 6\n 5\n >>> # cumulative\n >>> render_iter.seek(2, Seek.CURRENT) # next = 6 + 2 = 8\n >>> render_iter.seek(-4, Seek.CURRENT) # next = 8 - 4 = 4\n >>> next(render_iter).number # next = 4 + 1 = 5\n 4\n >>> # cumulative\n >>> render_iter.seek(7) # next = 7\n >>> render_iter.seek(1, Seek.CURRENT) # next = 7 + 1 = 8\n >>> render_iter.seek(-5, Seek.CURRENT) # next = 8 - 5 = 3\n >>> next(render_iter).number # next = 3 + 1 = 4\n 3\n >>> # NOT cumulative\n >>> render_iter.seek(3, Seek.CURRENT) # next = 4 + 3 = 7\n >>> render_iter.seek(2) # next = 2\n >>> next(render_iter).number # next = 2 + 1 = 3\n 2\n\n On the other hand, if the underlying renderable has\n :py:attr:`~term_image.renderable.FrameCount.INDEFINITE` frame count, seek\n operations don't take effect **until the next render**. Hence, multiple\n consecutive seek operations between any two consecutive renders do **not**\n have a **cumulative** effect; rather, only **the last one** takes effect.\n In particular, any seek operation with *whence* =\n :py:attr:`~term_image.renderable.Seek.CURRENT` is relative to the frame\n after that which was rendered last.\n\n .. collapse:: Example\n\n >>> animated_renderable.frame_count is FrameCount.INDEFINITE\n True\n >>> # iterating normally without seeking\n >>> [frame.render_output for frame in animated_renderable]\n ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', ...]\n >>>\n >>> # Assuming the renderable implements all kinds of seek operations\n >>> render_iter = RenderIterator(animated_renderable) # next = 0\n >>> render_iter.seek(5) # next = 5\n >>> next(render_iter).render_output # next = 5 + 1 = 6\n '5'\n >>> render_iter.seek(2, Seek.CURRENT) # next = 6 + 2 = 8\n >>> render_iter.seek(-4, Seek.CURRENT) # next = 6 - 4 = 2\n >>> next(render_iter).render_output # next = 2 + 1 = 3\n '2'\n >>> render_iter.seek(7) # next = 7\n >>> render_iter.seek(3, Seek.CURRENT) # next = 3 + 3 = 6\n >>> next(render_iter).render_output # next = 6 + 1 = 7\n '6'\n\n A renderable with :py:attr:`~term_image.renderable.FrameCount.INDEFINITE`\n frame count may not support/implement all kinds of seek operations or any\n at all. If the underlying renderable doesn't support/implement a given\n seek operation, the seek operation should simply have no effect on\n iteration i.e the next frame should be the one after that which was\n rendered last. See each :term:`render class` that implements\n :py:attr:`~term_image.renderable.FrameCount.INDEFINITE` frame count for\n the seek operations it supports and any other specific related details.\n \"\"\"\n if self._closed:\n raise FinalizedIteratorError(\"This iterator has been finalized\") from None\n\n frame_count = self._renderable.frame_count\n renderable_data = self._renderable_data\n if frame_count is FrameCount.INDEFINITE:\n if whence is Seek.START and offset < 0 or whence is Seek.END and offset > 0:\n raise arg_value_error_range(\"offset\", offset, f\"whence={whence.name}\")\n renderable_data.update(frame_offset=offset, seek_whence=whence)\n else:\n frame = (\n offset\n if whence is Seek.START\n else (\n renderable_data.frame_offset + offset\n if whence is Seek.CURRENT\n else frame_count + offset - 1\n )\n )\n if not 0 <= frame < frame_count:\n raise arg_value_error_range(\n \"offset\",\n offset,\n (\n f\"whence={whence.name}, frame_count={frame_count}\"\n + (\n f\", next={renderable_data.frame_offset}\"\n if whence is Seek.CURRENT\n else \"\"\n )\n ),\n )\n renderable_data.update(frame_offset=frame, seek_whence=Seek.START)\n\n def set_frame_duration(self, duration: int | FrameDuration) -> None:\n \"\"\"Sets the frame duration.\n\n Args:\n duration: Frame duration (see\n :py:attr:`~term_image.renderable.Renderable.frame_duration`).\n\n Raises:\n FinalizedIteratorError: The iterator has been finalized.\n ValueError: *duration* is out of range.\n\n NOTE:\n Takes effect from the next [#ri-nf]_ rendered frame.\n \"\"\"\n if self._closed:\n raise FinalizedIteratorError(\"This iterator has been finalized\") from None\n\n if isinstance(duration, int) and duration <= 0:\n raise arg_value_error_range(\"duration\", duration)\n\n self._renderable_data.duration = duration\n\n def set_padding(self, padding: Padding) -> None:\n \"\"\"Sets the :term:`render output` padding.\n\n Args:\n padding: Render output padding.\n\n Raises:\n FinalizedIteratorError: The iterator has been finalized.\n\n NOTE:\n Takes effect from the next [#ri-nf]_ rendered frame.\n \"\"\"\n if self._closed:\n raise FinalizedIteratorError(\"This iterator has been finalized\") from None\n\n self._padding = (\n padding.resolve(get_terminal_size())\n if isinstance(padding, AlignedPadding) and padding.relative\n else padding\n )\n self._padded_size = padding.get_padded_size(self._renderable_data.size)\n\n def set_render_args(self, render_args: RenderArgs) -> None:\n \"\"\"Sets the render arguments.\n\n Args:\n render_args: Render arguments.\n\n Raises:\n FinalizedIteratorError: The iterator has been finalized.\n IncompatibleRenderArgsError: Incompatible render arguments.\n\n NOTE:\n Takes effect from the next [#ri-nf]_ rendered frame.\n \"\"\"\n if self._closed:\n raise FinalizedIteratorError(\"This iterator has been finalized\") from None\n\n render_cls = type(self._renderable)\n self._render_args = (\n render_args\n if render_args.render_cls is render_cls\n # Validate compatibility (and convert, if compatible)\n else RenderArgs(render_cls, render_args)\n )\n\n def set_render_size(self, render_size: Size) -> None:\n \"\"\"Sets the :term:`render size`.\n\n Args:\n render_size: Render size.\n\n Raises:\n FinalizedIteratorError: The iterator has been finalized.\n\n NOTE:\n Takes effect from the next [#ri-nf]_ rendered frame.\n \"\"\"\n if self._closed:\n raise FinalizedIteratorError(\"This iterator has been finalized\") from None\n\n self._renderable_data.size = render_size\n self._padded_size = self._padding.get_padded_size(render_size)\n\n # Extension methods ========================================================\n\n @classmethod\n def _from_render_data_(\n cls,\n renderable: Renderable,\n render_data: RenderData,\n render_args: RenderArgs | None = None,\n padding: Padding = ExactPadding(),\n *args: Any,\n finalize: bool = True,\n **kwargs: Any,\n ) -> Self:\n \"\"\"Constructs an iterator with pre-generated render data.\n\n Args:\n renderable: An animated renderable.\n render_data: Render data.\n render_args: Render arguments.\n args: Other positional arguments accepted by the class constructor.\n finalize: Whether *render_data* is finalized along with the iterator.\n kwargs: Other keyword arguments accepted by the class constructor.\n\n Returns:\n A new iterator instance.\n\n Raises the same exceptions as the class constructor.\n\n NOTE:\n *render_data* may be modified by the iterator or the underlying renderable.\n \"\"\"\n new = cls.__new__(cls)\n new._init(renderable, render_args, padding, *args, **kwargs)\n\n if render_data.render_cls is not type(renderable):\n raise arg_value_error_msg(\n \"Invalid render data for renderable of type \"\n f\"{type(renderable).__name__!r}\",\n render_data,\n )\n if render_data.finalized:\n raise ValueError(\"The render data has been finalized\")\n if not render_data[Renderable].iteration:\n raise arg_value_error_msg(\"Invalid render data for iteration\", render_data)\n\n if not (render_args and render_args.render_cls is type(renderable)):\n # Validate compatibility (and convert, if compatible)\n render_args = RenderArgs(type(renderable), render_args)\n\n new._padding = (\n padding.resolve(get_terminal_size())\n if isinstance(padding, AlignedPadding) and padding.relative\n else padding\n )\n new._iterator = new._iterate(render_data, render_args)\n new._finalize_data = finalize\n next(new._iterator)\n\n return new\n\n # Private Methods ==========================================================\n\n def _init(\n self,\n renderable: Renderable,\n render_args: RenderArgs | None = None,\n padding: Padding = ExactPadding(),\n loops: int = 1,\n cache: bool | int = 100,\n ) -> None:\n \"\"\"Partially initializes an instance.\n\n Performs the part of the initialization common to all constructors.\n \"\"\"\n if not renderable.animated:\n raise arg_value_error_msg(\"'renderable' is not animated\", renderable)\n if not loops:\n raise arg_value_error(\"loops\", loops)\n if False is not cache <= 0:\n raise arg_value_error_range(\"cache\", cache)\n\n indefinite = renderable.frame_count is FrameCount.INDEFINITE\n self._closed = False\n self._renderable = renderable\n self.loop = self._loops = 1 if indefinite else loops\n self._cached = (\n False\n if indefinite\n else (\n cache\n # `isinstance` is much costlier on failure and `bool` cannot be\n # subclassed\n if type(cache) is bool\n else renderable.frame_count <= cache # type: ignore[operator]\n )\n )\n\n def _iterate(\n self,\n render_data: RenderData,\n render_args: RenderArgs,\n ) -> Generator[Frame, None, None]:\n \"\"\"Performs the actual render iteration operation.\"\"\"\n # Instance init completion\n self._render_data = render_data\n self._render_args = render_args\n renderable_data: RenderableData\n self._renderable_data = renderable_data = render_data[Renderable]\n self._padded_size = self._padding.get_padded_size(renderable_data.size)\n\n # Setup\n renderable = self._renderable\n frame_count = renderable.frame_count\n if frame_count is FrameCount.INDEFINITE:\n frame_count = 1\n definite = frame_count > 1\n loop = self.loop\n CURRENT = Seek.CURRENT\n renderable_data.frame_offset = 0\n cache: list[tuple[Frame | None, Size, int | FrameDuration, RenderArgs]] | None\n cache = (\n [(None,) * 4] * frame_count # type: ignore[list-item]\n if self._cached\n else None\n )\n\n # Initial dummy frame, yielded but unused by initializers.\n # Acts as a breakpoint between completion of instance init + iteration setup\n # and render iteration.\n yield DUMMY_FRAME\n\n # Render iteration\n frame_no = renderable_data.frame_offset * definite\n while loop:\n while frame_no < frame_count:\n if cache:\n frame = (cache_entry := cache[frame_no])[0]\n frame_details = cache_entry[1:]\n else:\n frame = None\n\n if not frame or frame_details != (\n renderable_data.size,\n renderable_data.duration,\n self._render_args,\n ):\n # NOTE: Re-render is required even when only `duration` changes\n # and the new value is *static* because frame duration may affect\n # the render output of some renderables.\n try:\n frame = renderable._render_(render_data, self._render_args)\n except StopIteration as exc:\n if definite:\n raise StopDefiniteIterationError(\n f\"{renderable!r} with definite frame count raised \"\n \"`StopIteration` when rendering a frame\"\n ) from exc\n self.loop = 0\n return\n\n if cache:\n cache[frame_no] = (\n frame,\n renderable_data.size,\n renderable_data.duration,\n self._render_args,\n )\n\n if self._padded_size != frame.render_size:\n frame = Frame(\n frame.number,\n frame.duration,\n self._padded_size,\n self._padding.pad(frame.render_output, frame.render_size),\n )\n\n if definite:\n renderable_data.frame_offset += 1\n elif (\n renderable_data.frame_offset\n or renderable_data.seek_whence != CURRENT\n ): # was seeked\n renderable_data.update(frame_offset=0, seek_whence=CURRENT)\n\n yield frame\n\n if definite:\n frame_no = renderable_data.frame_offset\n\n # INDEFINITE can never reach here\n frame_no = renderable_data.frame_offset = 0\n if loop > 0: # Avoid infinitely large negative numbers\n self.loop = loop = loop - 1", "n_imports_parsed": 9, "n_files_resolved": 6, "n_chars_extracted": 23350}, "tests/test_image/test_base.py::417": {"resolved_imports": ["src/term_image/__init__.py", "src/term_image/_ctlseqs.py", "src/term_image/exceptions.py", "src/term_image/image/block.py", "src/term_image/image/common.py"], "used_names": ["BlockImage", "pytest", "python_img"], "enclosing_function": "test_seek_tell", "extracted_code": "# Source: src/term_image/image/block.py\nclass BlockImage(TextImage):\n \"\"\"A render style using unicode half blocks and direct-color colour escape\n sequences.\n\n See :py:class:`TextImage` for the description of the constructor.\n \"\"\"\n\n @classmethod\n def is_supported(cls):\n if cls._supported is None:\n COLORTERM = os.environ.get(\"COLORTERM\") or \"\"\n TERM = os.environ.get(\"TERM\") or \"\"\n cls._supported = (\n \"truecolor\" in COLORTERM or \"24bit\" in COLORTERM or \"256color\" in TERM\n )\n\n return cls._supported\n\n def _get_render_size(self) -> Tuple[int, int]:\n return tuple(map(mul, self.rendered_size, (1, 2)))\n\n @staticmethod\n def _pixels_cols(\n *, pixels: Optional[int] = None, cols: Optional[int] = None\n ) -> int:\n return pixels if pixels is not None else cols\n\n @staticmethod\n def _pixels_lines(\n *, pixels: Optional[int] = None, lines: Optional[int] = None\n ) -> int:\n return ceil(pixels / 2) if pixels is not None else lines * 2\n\n def _render_image(\n self,\n img: PIL.Image.Image,\n alpha: Union[None, float, str],\n *,\n frame: bool = False,\n split_cells: bool = False,\n ) -> str:\n # NOTE:\n # It's more efficient to write separate strings to the buffer separately\n # than concatenate and write together.\n\n def update_buffer():\n if alpha:\n no_alpha = False\n if a_cluster1 == 0 == a_cluster2:\n buf_write(SGR_DEFAULT)\n buf_write(blank * n)\n elif a_cluster1 == 0: # up is transparent\n buf_write(SGR_DEFAULT)\n buf_write(SGR_FG_DIRECT % cluster2)\n buf_write(lower_pixel * n)\n elif a_cluster2 == 0: # down is transparent\n buf_write(SGR_DEFAULT)\n buf_write(SGR_FG_DIRECT % cluster1)\n buf_write(upper_pixel * n)\n else:\n no_alpha = True\n\n if not alpha or no_alpha:\n r, g, b = cluster2\n # Kitty does not render BG colors equal to the default BG color\n if is_on_kitty and cluster2 == bg_color:\n r += r < 255 or -1\n buf_write(SGR_BG_DIRECT % (r, g, b))\n if cluster1 == cluster2:\n buf_write(blank * n)\n else:\n buf_write(SGR_FG_DIRECT % cluster1)\n buf_write(upper_pixel * n)\n\n buffer = io.StringIO()\n buf_write = buffer.write # Eliminate attribute resolution cost\n\n bg_color = get_fg_bg_colors()[1]\n is_on_kitty = self._is_on_kitty()\n if split_cells:\n blank = \" \\0\"\n lower_pixel = LOWER_PIXEL + \"\\0\"\n upper_pixel = UPPER_PIXEL + \"\\0\"\n else:\n blank = \" \"\n lower_pixel = LOWER_PIXEL\n upper_pixel = UPPER_PIXEL\n end_of_line = SGR_DEFAULT + \"\\n\"\n\n width, height = self._get_render_size()\n frame_img = img if frame else None\n img, rgb, a = self._get_render_data(img, alpha, round_alpha=True, frame=frame)\n alpha = img.mode == \"RGBA\"\n\n # clean up (ImageIterator uses one PIL image throughout)\n if frame_img is not img:\n self._close_image(img)\n\n rgb_pairs = (\n (\n zip(rgb[x : x + width], rgb[x + width : x + width * 2]),\n (rgb[x], rgb[x + width]),\n )\n for x in range(0, len(rgb), width * 2)\n )\n a_pairs = (\n (\n zip(a[x : x + width], a[x + width : x + width * 2]),\n (a[x], a[x + width]),\n )\n for x in range(0, len(a), width * 2)\n )\n\n row_no = 0\n # Two rows of pixels per line\n for (rgb_pair, (cluster1, cluster2)), (a_pair, (a_cluster1, a_cluster2)) in zip(\n rgb_pairs, a_pairs\n ):\n row_no += 2\n n = 0\n for (px1, px2), (a1, a2) in zip(rgb_pair, a_pair):\n # Color-code characters and write to buffer\n # when upper and/or lower pixel color/alpha-level changes\n if not (alpha and a1 == a_cluster1 == 0 == a_cluster2 == a2) and (\n px1 != cluster1\n or px2 != cluster2\n or alpha\n and (\n # From non-transparent to transparent\n a_cluster1 != a1 == 0\n or a_cluster2 != a2 == 0\n # From transparent to non-transparent\n or 0 == a_cluster1 != a1\n or 0 == a_cluster2 != a2\n )\n ):\n update_buffer()\n cluster1 = px1\n cluster2 = px2\n if alpha:\n a_cluster1 = a1\n a_cluster2 = a2\n n = 0\n n += 1\n\n update_buffer() # Rest of the line\n if split_cells:\n # Set the last \"\\0\" to be overwritten by the next byte\n buffer.seek(buffer.tell() - 1)\n if row_no < height: # last line not yet rendered\n buf_write(end_of_line)\n\n buf_write(SGR_DEFAULT) # Reset color after last line\n\n with buffer:\n return buffer.getvalue()", "n_imports_parsed": 16, "n_files_resolved": 5, "n_chars_extracted": 5566}, "tests/test_color.py::72": {"resolved_imports": ["src/term_image/color.py"], "used_names": ["Color", "pytest"], "enclosing_function": "test_rgb", "extracted_code": "# Source: src/term_image/color.py\nclass Color(_DummyColor):\n \"\"\"A color.\n\n Args:\n r: The red channel.\n g: The green channel.\n b: The blue channel.\n a: The alpha channel (opacity).\n\n Raises:\n ValueError: The value of a channel is not within the valid range.\n\n NOTE:\n The valid value range for all channels is 0 to 255, both inclusive.\n\n TIP:\n This class is a :py:class:`~typing.NamedTuple` of four fields.\n\n WARNING:\n In the case of multiple inheritance i.e if subclassing this class along with\n other classes, this class should appear last (i.e to the far right) in the\n base class list.\n \"\"\"\n\n __slots__ = ()\n\n # Overrides these descriptors in order to speed up attribute resolution and to\n # simplify auto documentation.\n r: int = _DummyColor.r\n r.__doc__ = \"\"\"The red channel\"\"\"\n\n g: int = _DummyColor.g\n g.__doc__ = \"\"\"The green channel\"\"\"\n\n b: int = _DummyColor.b\n b.__doc__ = \"\"\"The blue channel\"\"\"\n\n a: int = _DummyColor.a\n a.__doc__ = \"\"\"The alpha channel (opacity)\"\"\"\n\n def __new__(cls, r: int, g: int, b: int, a: int = 255) -> Self:\n # Only the 8 LSb may be set for any value within the range [0, 255].\n # `x & ~255` unsets the 8 LSb. Hence, if the result is non-zero (i.e any\n # of the bits above the lowest 8 is set), it implies `x` is out of range.\n #\n # Actually benchmarked *this* against the \"simpler\" logically-negated chained\n # comparison (i.e `0 <= x <= 255`) and *this* was significantly faster for all\n # cases i.e within, on the boundaries, and outside (on both sides).\n if (r | g | b | a) & ~255: # First test to see if *any* is out of range\n if r & ~255:\n raise arg_value_error_range(\"r\", r)\n if g & ~255:\n raise arg_value_error_range(\"g\", g)\n if b & ~255:\n raise arg_value_error_range(\"b\", b)\n # There's no point checking since at least one is out of range\n raise arg_value_error_range(\"a\", a)\n\n # Using `tuple` directly instead of `super()` for performance\n return tuple.__new__(cls, (r, g, b, a))\n\n @property\n def hex(self) -> str:\n \"\"\"Converts the color to its RGBA hexadecimal representation.\n\n Returns:\n The RGBA hex color string, starting with the ``#`` character i.e\n ``#rrggbbaa``.\n\n Each channel is represented by two **lowercase** hex digits ranging from\n ``00`` to ``ff``.\n \"\"\"\n return \"#%02x%02x%02x%02x\" % self\n\n @property\n def rgb(self) -> tuple[int, int, int]:\n \"\"\"Extracts the R, G and B channels of the color.\n\n Returns:\n A 3-tuple containing the red, green and blue channel values.\n \"\"\"\n return self[:3]\n\n @property\n def rgb_hex(self) -> str:\n \"\"\"Converts the color to its RGB hexadecimal representation.\n\n Returns:\n The RGB hex color string, starting with the ``#`` character i.e ``#rrggbb``.\n\n Each channel is represented by two **lowercase** hex digits ranging from\n ``00`` to ``ff``.\n \"\"\"\n return \"#%02x%02x%02x\" % self[:3]\n\n @classmethod\n def from_hex(cls, color: str) -> Self:\n \"\"\"Creates a new instance from a hexadecimal color string.\n\n Args:\n color: A **case-insensitive** RGB or RGBA hex color string, **optionally**\n starting with the ``#`` (pound) character i.e ``[#]rrggbb[aa]``.\n\n Returns:\n A new instance representing the given hex color string.\n\n Raises:\n ValueError: Invalid hex color string.\n\n NOTE:\n For an RGB hex color string, the value of A (the alpha channel) is\n taken to be 255.\n \"\"\"\n if not (match := _RGBA_HEX_RE.fullmatch(color)):\n raise ValueError(f\"Invalid hex color string (got: {color!r})\")\n\n return tuple.__new__(cls, [int(x, 16) for x in match.groups(\"ff\")])\n\n @classmethod\n def _new(cls, r: int, g: int, b: int, a: int = 255) -> Self:\n \"\"\"Alternate constructor for internal use only.\"\"\"\n return tuple.__new__(cls, (r, g, b, a))", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 4255}, "tests/renderable/test_types.py::977": {"resolved_imports": ["src/term_image/geometry.py", "src/term_image/renderable/_renderable.py", "src/term_image/renderable/_types.py"], "used_names": ["ArgsNamespace", "Renderable", "pytest"], "enclosing_function": "test_render_cls_update", "extracted_code": "# Source: src/term_image/renderable/_renderable.py\nclass Renderable(metaclass=RenderableMeta, _base=True):\n \"\"\"A renderable.\n\n Args:\n frame_count: Number of frames. If it's a\n\n * positive integer, the number of frames is as given.\n * :py:class:`~term_image.renderable.FrameCount` enum member, see the\n member's description.\n\n If equal to 1 (one), the renderable is non-animated.\n Otherwise, it is animated.\n\n frame_duration: The duration of a frame. If it's a\n\n * positive integer, it implies a static duration (in **milliseconds**)\n i.e the same duration applies to every frame.\n * :py:class:`~term_image.renderable.FrameDuration` enum member, see the\n member's description.\n\n This argument is ignored if *frame_count* equals 1 (one)\n i.e the renderable is non-animated.\n\n Raises:\n ValueError: An argument has an invalid value.\n\n ATTENTION:\n This is an abstract base class. Hence, only **concrete** subclasses can be\n instantiated.\n\n .. seealso::\n\n :ref:`renderable-ext-api`\n :py:class:`Renderable`\\\\ 's Extension API\n \"\"\"\n\n # Class Attributes =========================================================\n\n # Initialized by `RenderableMeta` and may be updated by `ArgsNamespaceMeta`\n Args: ClassVar[type[ArgsNamespace] | None]\n \"\"\":term:`Render class`\\\\ -specific render arguments.\n\n This is either:\n\n - a render argument namespace class (subclass of :py:class:`ArgsNamespace`)\n associated [#an-ass]_ with the render class, or\n - :py:data:`None`, if the render class has no render arguments.\n\n If this is a class, an instance of it (or a subclass thereof) is contained within\n any :py:class:`RenderArgs` instance associated [#ra-ass]_ with the render class or\n any of its subclasses. Also, an instance of this class (or a subclass of it) is\n returned by :py:meth:`render_args[render_cls]\n `; where *render_args* is\n an instance of :py:class:`~term_image.renderable.RenderArgs` as previously\n described and *render_cls* is the render class with which this namespace class\n is associated [#an-ass]_.\n\n .. collapse:: Example\n\n >>> class Foo(Renderable):\n ... pass\n ...\n ... class FooArgs(ArgsNamespace, render_cls=Foo):\n ... foo: str | None = None\n ...\n >>> Foo.Args is FooArgs\n True\n >>>\n >>> # default\n >>> foo_args = Foo.Args()\n >>> foo_args\n FooArgs(foo=None)\n >>> foo_args.foo is None\n True\n >>>\n >>> render_args = RenderArgs(Foo)\n >>> render_args[Foo]\n FooArgs(foo=None)\n >>>\n >>> # non-default\n >>> foo_args = Foo.Args(\"FOO\")\n >>> foo_args\n FooArgs(foo='FOO')\n >>> foo_args.foo\n 'FOO'\n >>>\n >>> render_args = RenderArgs(Foo, foo_args.update(foo=\"bar\"))\n >>> render_args[Foo]\n FooArgs(foo='bar')\n\n On the other hand, if this is :py:data:`None`, it implies the render class has no\n render arguments.\n\n .. collapse:: Example\n\n >>> class Bar(Renderable):\n ... pass\n ...\n >>> Bar.Args is None\n True\n >>> render_args = RenderArgs(Bar)\n >>> render_args[Bar]\n Traceback (most recent call last):\n ...\n NoArgsNamespaceError: 'Bar' has no render arguments\n \"\"\"\n\n # Initialized by `RenderableMeta` and may be updated by `DataNamespaceMeta`\n _Data_: ClassVar[type[DataNamespace] | None]\n \"\"\":term:`Render class`\\\\ -specific render data.\n\n This is either:\n\n - a render data namespace class (subclass of :py:class:`DataNamespace`)\n associated [#dn-ass]_ with the render class, or\n - :py:data:`None`, if the render class has no render data.\n\n If this is a class, an instance of it (or a subclass thereof) is contained within\n any :py:class:`RenderData` instance associated [#rd-ass]_ with the render class or\n any of its subclasses. Also, an instance of this class (or a subclass of it) is\n returned by :py:meth:`render_data[render_cls]\n `; where *render_data* is\n an instance of :py:class:`~term_image.renderable.RenderData` as previously\n described and *render_cls* is the render class with which this namespace class\n is associated [#dn-ass]_.\n\n .. collapse:: Example\n\n >>> class Foo(Renderable):\n ... pass\n ...\n ... class _Data_(DataNamespace, render_cls=Foo):\n ... foo: str | None\n ...\n >>> Foo._Data_ is FooData\n True\n >>>\n >>> foo_data = Foo._Data_()\n >>> foo_data\n >\n >>> foo_data.foo\n Traceback (most recent call last):\n ...\n UninitializedDataFieldError: The render data field 'foo' of 'Foo' has not \\\nbeen initialized\n >>>\n >>> foo_data.foo = \"FOO\"\n >>> foo_data\n \n >>> foo_data.foo\n 'FOO'\n >>>\n >>> render_data = RenderData(Foo)\n >>> render_data[Foo]\n >\n >>>\n >>> render_data[Foo].foo = \"bar\"\n >>> render_data[Foo]\n \n\n On the other hand, if this is :py:data:`None`, it implies the render class has no\n render data.\n\n .. collapse:: Example\n\n >>> class Bar(Renderable):\n ... pass\n ...\n >>> Bar._Data_ is None\n True\n >>>\n >>> render_data = RenderData(Bar)\n >>> render_data[Bar]\n Traceback (most recent call last):\n ...\n NoDataNamespaceError: 'Bar' has no render data\n\n .. seealso::\n\n :py:class:`~term_image.renderable.RenderableData`\n Render data for :py:class:`~term_image.renderable.Renderable`.\n \"\"\"\n\n _EXPORTED_ATTRS_: ClassVar[tuple[str, ...]]\n \"\"\"Exported attributes.\n\n This specifies class attributes defined by the class (not a parent) on itself\n **but not** its subclasses which should be exported to definitions of the class\n in subprocesses.\n\n These attributes are typically assigned using ``__class__.*`` within methods.\n\n NOTE:\n * Defining this is optional.\n * The attributes are exported for a class if and only if they are defined\n on that class when starting a subprocess.\n * The attributes are exported only for subprocesses started via\n :py:class:`multiprocessing.Process`.\n\n TIP:\n This can be used to export \"private\" attributes of the class across\n subprocesses.\n \"\"\"\n\n _EXPORTED_DESCENDANT_ATTRS_: ClassVar[tuple[str, ...]]\n \"\"\"Exported :term:`descendant` attributes.\n\n This specifies class attributes defined by the class (not a parent) on itself\n **and** its subclasses (i.e :term:`descendant` attributes) which should be exported\n to definitions of the class and its subclasses in subprocesses.\n\n These attributes are typically assigned using ``cls.*`` within class methods.\n\n This extends the exported descendant attributes of parent classes i.e all\n exported descendant attributes of a class are also exported for its subclasses.\n\n NOTE:\n * Defining this is optional.\n * The attributes are exported for a class if and only if they are defined\n on that class when starting a subprocess.\n * The attributes are exported only for subprocesses started via\n :py:class:`multiprocessing.Process`.\n\n TIP:\n This can be used to export \"private\" :term:`descendant` attributes of the\n class across subprocesses.\n \"\"\"\n\n _ALL_DEFAULT_ARGS: ClassVar[MappingProxyType[type[Renderable], ArgsNamespace]]\n _RENDER_DATA_MRO: ClassVar[MappingProxyType[type[Renderable], type[DataNamespace]]]\n _ALL_EXPORTED_ATTRS: ClassVar[tuple[str, ...]]\n\n # Instance Attributes ======================================================\n\n animated: bool\n \"\"\"``True`` if the renderable is :term:`animated`. Otherwise, ``False``.\"\"\"\n\n _frame: int\n _frame_count: int | FrameCount\n _frame_duration: int | FrameDuration\n\n # Special Methods ==========================================================\n\n def __init__(\n self,\n frame_count: int | FrameCount,\n frame_duration: int | FrameDuration,\n ) -> None:\n if isinstance(frame_count, int) and frame_count < 1:\n raise arg_value_error_range(\"frame_count\", frame_count)\n\n if frame_count != 1:\n if isinstance(frame_duration, int) and frame_duration <= 0:\n raise arg_value_error_range(\"frame_duration\", frame_duration)\n self._frame_duration = frame_duration\n\n self.animated = frame_count != 1\n self._frame_count = frame_count\n self._frame = 0\n\n def __iter__(self) -> term_image.render.RenderIterator:\n \"\"\"Returns a render iterator.\n\n Returns:\n A render iterator (with frame caching disabled and all other optional\n arguments to :py:class:`~term_image.render.RenderIterator` being the\n default values).\n\n Raises:\n NonAnimatedRenderableError: The renderable is non-animated.\n\n :term:`Animated` renderables are iterable i.e they can be used with various\n means of iteration such as the ``for`` statement and iterable unpacking.\n \"\"\"\n from term_image.render import RenderIterator\n\n try:\n return RenderIterator(self, cache=False)\n except ValueError:\n raise NonAnimatedRenderableError(\n \"Non-animated renderables are not iterable\"\n ) from None\n\n def __repr__(self) -> str:\n return f\"<{type(self).__name__}: frame_count={self._frame_count}>\"\n\n def __str__(self) -> str:\n \"\"\":term:`Renders` the current frame with default arguments and no padding.\n\n Returns:\n The frame :term:`render output`.\n\n Raises:\n RenderError: An error occurred during :term:`rendering`.\n \"\"\"\n return self._init_render_(self._render_)[0].render_output\n\n # Properties ===============================================================\n\n @property\n def frame_count(self) -> int | Literal[FrameCount.INDEFINITE]:\n \"\"\"Frame count\n\n GET:\n Returns either\n\n * the number of frames the renderable has, or\n * :py:attr:`~term_image.renderable.FrameCount.INDEFINITE`.\n \"\"\"\n if self._frame_count is FrameCount.POSTPONED:\n self._frame_count = self._get_frame_count_()\n\n return self._frame_count\n\n @property\n def frame_duration(self) -> int | FrameDuration:\n \"\"\"Frame duration\n\n GET:\n Returns\n\n * a positive integer, a static duration (in **milliseconds**) i.e the\n same duration applies to every frame; or\n * :py:attr:`~term_image.renderable.FrameDuration.DYNAMIC`.\n\n SET:\n If the value is\n\n * a positive integer, it implies a static duration (in **milliseconds**)\n i.e the same duration applies to every frame.\n * :py:attr:`~term_image.renderable.FrameDuration.DYNAMIC`, see the\n enum member's description.\n\n Raises:\n NonAnimatedRenderableError: The renderable is non-animated.\n \"\"\"\n try:\n return self._frame_duration\n except AttributeError:\n if not self.animated:\n raise NonAnimatedRenderableError(\n \"Non-animated renderables have no frame duration\"\n ) from None\n raise\n\n @frame_duration.setter\n def frame_duration(self, duration: int | FrameDuration) -> None:\n if not self.animated:\n raise NonAnimatedRenderableError(\n \"Cannot set frame duration for a non-animated renderable\"\n )\n\n if isinstance(duration, int) and duration <= 0:\n raise arg_value_error_range(\"frame_duration\", duration)\n\n self._frame_duration = duration\n\n @property\n def render_size(self) -> geometry.Size:\n \"\"\":term:`Render size`\n\n GET:\n Returns the size of the renderable's :term:`render output`.\n \"\"\"\n return self._get_render_size_()\n\n # Public Methods ===========================================================\n\n def draw(\n self,\n render_args: RenderArgs | None = None,\n padding: Padding = AlignedPadding(0, -2),\n *,\n animate: bool = True,\n loops: int = -1,\n cache: bool | int = 100,\n check_size: bool = True,\n allow_scroll: bool = False,\n hide_cursor: bool = True,\n echo_input: bool = False,\n ) -> None:\n \"\"\"Draws the current frame or an animation to standard output.\n\n Args:\n render_args: Render arguments.\n padding: :term:`Render output` padding.\n animate: Whether to enable animation for :term:`animated` renderables.\n If disabled, only the current frame is drawn.\n loops: See :py:class:`~term_image.render.RenderIterator`\n (applies to **animations only**).\n cache: See :py:class:`~term_image.render.RenderIterator`.\n (applies to **animations only**).\n check_size: Whether to validate the padded :term:`render size` of\n **non-animations**.\n allow_scroll: Whether to validate the padded :term:`render height` of\n **non-animations**. Ignored if *check_size* is ``False``.\n hide_cursor: Whether to hide the cursor **while drawing**.\n echo_input: Whether to display input **while drawing** (applies on **Unix\n only**).\n\n .. note::\n * If disabled (default), input is not read/consumed, it's just not\n displayed.\n * If enabled, echoed input may affect cursor positioning and\n therefore, the output (especially for animations).\n\n Raises:\n RenderSizeOutofRangeError: The padded :term:`render size` can not fit into\n the :term:`terminal size`.\n IncompatibleRenderArgsError: Incompatible render arguments.\n RenderError: An error occurred during :term:`rendering`.\n\n If *check_size* is ``True`` (or it's an animation),\n\n * the padded :term:`render width` must not be greater than the\n :term:`terminal width`.\n * and *allow_scroll* is ``False`` (or it's an animation), the padded\n :term:`render height` must not be greater than the :term:`terminal height`.\n\n NOTE:\n * *hide_cursor* and *echo_input* apply if and only if the output stream\n is connected to a terminal.\n * For animations (i.e animated renderables with *animate* = ``True``),\n the padded :term:`render size` is always validated.\n * Animations with **definite** frame count, **by default**, are infinitely\n looped but can be terminated with :py:data:`~signal.SIGINT`\n (``CTRL + C``), **without** raising :py:class:`KeyboardInterrupt`.\n \"\"\"\n animation = self.animated and animate\n output = sys.stdout\n not_echo_input = OS_IS_UNIX and not echo_input and output.isatty()\n hide_cursor = hide_cursor and output.isatty()\n\n # Validate size and get render data and args\n render_data: RenderData\n real_render_args: RenderArgs\n (render_data, real_render_args), padding = self._init_render_(\n lambda *args: args,\n render_args,\n padding,\n iteration=animation,\n finalize=False,\n check_size=animation or check_size,\n allow_scroll=not animation and allow_scroll,\n )\n\n if not_echo_input:\n output_fd = output.fileno()\n old_attr = termios.tcgetattr(output_fd)\n new_attr = termios.tcgetattr(output_fd)\n new_attr[3] &= ~termios.ECHO\n try:\n if hide_cursor:\n output.write(HIDE_CURSOR)\n if not_echo_input:\n termios.tcsetattr(output_fd, termios.TCSAFLUSH, new_attr)\n\n if animation:\n self._animate_(\n render_data, real_render_args, padding, loops, cache, output\n )\n else:\n frame = self._render_(render_data, real_render_args)\n padded_size = padding.get_padded_size(frame.render_size)\n render = (\n frame.render_output\n if frame.render_size == padded_size\n else padding.pad(frame.render_output, frame.render_size)\n )\n try:\n output.write(render)\n output.flush()\n except KeyboardInterrupt:\n self._handle_interrupted_draw_(\n render_data, real_render_args, output\n )\n raise\n finally:\n output.write(\"\\n\")\n if hide_cursor:\n output.write(SHOW_CURSOR)\n output.flush()\n if not_echo_input:\n termios.tcsetattr(output_fd, termios.TCSANOW, old_attr)\n render_data.finalize()\n\n def render(\n self,\n render_args: RenderArgs | None = None,\n padding: Padding = NO_PADDING,\n ) -> Frame:\n \"\"\":term:`Renders` the current frame.\n\n Args:\n render_args: Render arguments.\n padding: :term:`Render output` padding.\n\n Returns:\n The rendered frame.\n\n Raises:\n IncompatibleRenderArgsError: Incompatible render arguments.\n RenderError: An error occurred during :term:`rendering`.\n \"\"\"\n frame, padding = self._init_render_(self._render_, render_args, padding)\n padded_size = padding.get_padded_size(frame.render_size)\n\n return (\n frame\n if frame.render_size == padded_size\n else Frame(\n frame.number,\n frame.duration,\n padded_size,\n padding.pad(frame.render_output, frame.render_size),\n )\n )\n\n def seek(self, offset: int, whence: Seek = Seek.START) -> int:\n \"\"\"Sets the current frame number.\n\n Args:\n offset: Frame offset (relative to *whence*).\n whence: Reference position for *offset*.\n\n Returns:\n The new current frame number.\n\n Raises:\n IndefiniteSeekError: The renderable has\n :py:attr:`~term_image.renderable.FrameCount.INDEFINITE` frame count.\n ValueError: *offset* is out of range.\n\n The value range for *offset* depends on *whence*:\n\n .. list-table::\n :align: left\n :header-rows: 1\n :widths: auto\n\n * - *whence*\n - Valid value range for *offset*\n\n * - :py:attr:`~term_image.renderable.Seek.START`\n - ``0`` <= *offset* < :py:attr:`frame_count`\n * - :py:attr:`~term_image.renderable.Seek.CURRENT`\n - -:py:meth:`tell` <= *offset* < :py:attr:`frame_count` - :py:meth:`tell`\n * - :py:attr:`~term_image.renderable.Seek.END`\n - -:py:attr:`frame_count` < *offset* <= ``0``\n \"\"\"\n frame_count = self.frame_count\n\n if frame_count is FrameCount.INDEFINITE:\n raise IndefiniteSeekError(\n \"Cannot seek a renderable with INDEFINITE frame count\"\n )\n\n frame = (\n offset\n if whence is Seek.START\n else (\n self._frame + offset\n if whence is Seek.CURRENT\n else frame_count + offset - 1\n )\n )\n if not 0 <= frame < frame_count:\n raise arg_value_error_range(\n \"offset\",\n offset,\n (\n f\"whence={whence.name}, frame_count={frame_count}\"\n + (f\", current={self._frame}\" if whence is Seek.CURRENT else \"\")\n ),\n )\n self._frame = frame\n\n return frame\n\n def tell(self) -> int:\n \"\"\"Returns the current frame number.\n\n Returns:\n Zero, if the renderable is non-animated or has\n :py:attr:`~term_image.renderable.FrameCount.INDEFINITE` frame count.\n Otherwise, the current frame number.\n \"\"\"\n return self._frame\n\n # Extension methods ========================================================\n\n def _animate_(\n self,\n render_data: RenderData,\n render_args: RenderArgs,\n padding: Padding,\n loops: int,\n cache: bool | int,\n output: TextIO,\n ) -> None:\n \"\"\"Animates frames of a renderable.\n\n Args:\n render_data: Render data.\n render_args: Render arguments associated with the renderable's class.\n output: The text I/O stream to which rendered frames will be written.\n\n All other parameters are the same as for :py:meth:`draw`, except that\n *padding* must have **absolute** dimensions if it's an instance of\n :py:class:`~term_image.padding.AlignedPadding`.\n\n This is called by :py:meth:`draw` for animations.\n\n NOTE:\n * The base implementation does not finalize *render_data*.\n * :term:`Render size` validation is expected to have been performed by\n the caller.\n * When called by :py:meth:`draw` (at least, the base implementation),\n *loops* and *cache* wouldn't have been validated.\n \"\"\"\n from term_image.render import RenderIterator\n\n render_size: Size = render_data[Renderable].size\n height = render_size.height\n pad_left, _, _, pad_bottom = padding._get_exact_dimensions_(render_size)\n render_iter = RenderIterator._from_render_data_(\n self,\n render_data,\n render_args,\n padding,\n loops,\n False if loops == 1 else cache,\n finalize=False,\n )\n cursor_to_next_render_line = f\"\\n{cursor_forward(pad_left)}\"\n cursor_to_render_top_left = (\n f\"\\r{cursor_up(height - 1)}{cursor_forward(pad_left)}\"\n )\n write = output.write\n flush = output.flush\n first_frame_written = False\n\n try:\n # first frame\n try:\n frame = next(render_iter)\n except StopIteration: # `INDEFINITE` frame count\n return\n\n try:\n write(frame.render_output)\n flush()\n except KeyboardInterrupt:\n self._handle_interrupted_draw_(render_data, render_args, output)\n return\n else:\n # Move the cursor to the top-left cell of the region occupied by the\n # render output\n write(\n f\"\\r{cursor_up(height + pad_bottom - 1)}{cursor_forward(pad_left)}\"\n )\n flush()\n\n first_frame_written = True\n\n # Padding has been drawn with the first frame, only the actual render is\n # needed henceforth.\n render_iter.set_padding(NO_PADDING)\n\n # render next frame during previous frame's duration\n duration_ms = frame.duration\n start_ns = perf_counter_ns()\n\n for frame in render_iter: # Render next frame\n # left-over of previous frame's duration\n sleep(\n max(0, duration_ms * 10**6 - (perf_counter_ns() - start_ns)) / 10**9\n )\n\n # clear previous frame, if necessary\n self._clear_frame_(render_data, render_args, pad_left + 1, output)\n\n # draw next frame\n try:\n write(frame.render_output.replace(\"\\n\", cursor_to_next_render_line))\n flush()\n except KeyboardInterrupt:\n self._handle_interrupted_draw_(render_data, render_args, output)\n return\n\n write(cursor_to_render_top_left)\n flush()\n\n # render next frame during previous frame's duration\n start_ns = perf_counter_ns()\n duration_ms = frame.duration\n\n # left-over of last frame's duration\n sleep(max(0, duration_ms * 10**6 - (perf_counter_ns() - start_ns)) / 10**9)\n except KeyboardInterrupt:\n pass\n finally:\n render_iter.close()\n if first_frame_written:\n # Move the cursor to the last line to prevent \"overlaid\" output\n write(cursor_down(height + pad_bottom - 1))\n flush()\n\n def _clear_frame_(\n self,\n render_data: RenderData,\n render_args: RenderArgs,\n cursor_x: int,\n output: TextIO,\n ) -> None:\n \"\"\"Clears the previous frame of an animation, if necessary.\n\n Args:\n render_data: Render data.\n render_args: Render arguments.\n cursor_x: Column/horizontal position of the cursor at the point of calling\n this method.\n\n .. note:: The position is **1-based** i.e the leftmost column on the\n screen is at position 1 (one).\n\n output: The text I/O stream to which frames of the animation are being\n written.\n\n Called by the base implementation of :py:meth:`_animate_` just before drawing\n the next frame of an animation.\n\n Upon calling this method, the cursor should be positioned at the top-left-most\n cell of the region occupied by the frame render output on the terminal screen.\n\n Upon return, ensure the cursor is at the same position it was at the point of\n calling this method (at least logically, since *output* shouldn't be flushed\n yet).\n\n The base implementation does nothing.\n\n NOTE:\n * This is required only if drawing the next frame doesn't inherently\n overwrite the previous frame.\n * This is only meant (and should only be used) as a last resort since\n clearing the previous frame before drawing the next may result in\n visible flicker.\n * Ensure whatever this method does doesn't result in the screen being\n scrolled.\n\n TIP:\n To reduce flicker, it's advisable to **not** flush *output*. It will be\n flushed after writing the next frame.\n \"\"\"\n\n @classmethod\n def _finalize_render_data_(cls, render_data: RenderData) -> None:\n \"\"\"Finalizes render data.\n\n Args:\n render_data: Render data.\n\n Typically, an overriding method should\n\n * finalize the data generated by :py:meth:`_get_render_data_` of the\n **same class**, if necessary,\n * call the overridden method, passing on *render_data*.\n\n NOTE:\n * It's recommended to call :py:meth:`RenderData.finalize()\n `\n instead as that assures a single invocation of this method.\n * Any definition of this method should be safe for multiple invocations on\n the same :py:class:`~term_image.renderable.RenderData` instance, just in\n case.\n\n .. seealso::\n :py:meth:`_get_render_data_`,\n :py:meth:`RenderData.finalize()\n `,\n the *finalize* parameter of :py:meth:`_init_render_`.\n \"\"\"\n\n def _get_frame_count_(self) -> int | Literal[FrameCount.INDEFINITE]:\n \"\"\"Implements :py:attr:`~term_image.renderable.FrameCount.POSTPONED` frame\n count evaluation.\n\n Returns:\n The frame count of the renderable. See :py:attr:`frame_count`.\n\n .. note::\n Returning :py:attr:`~term_image.renderable.FrameCount.POSTPONED` or\n ``1`` (one) is invalid and may result in unexpected/undefined behaviour\n across various interfaces defined by this library (and those derived\n from them), since re-postponing evaluation is unsupported and the\n renderable would have been taken to be animated.\n\n The base implementation raises :py:class:`NotImplementedError`.\n \"\"\"\n raise NotImplementedError(\"POSTPONED frame count evaluation isn't implemented\")\n\n def _get_render_data_(self, *, iteration: bool) -> RenderData:\n \"\"\"Generates data required for rendering that's based on internal or\n external state.\n\n Args:\n iteration: Whether the render operation requiring the data involves a\n sequence of :term:`renders` (most likely of different frames), or it's\n a one-off render.\n\n Returns:\n The generated render data.\n\n The render data should include **copies** of any **variable/mutable**\n internal/external state required for rendering and other data generated from\n constant state but which should **persist** throughout a render operation\n (which may involve consecutive/repeated renders of one or more frames).\n\n May also be used to \"allocate\" and initialize storage for mutable/variable\n data specific to a render operation.\n\n Typically, an overriding method should\n\n * call the overridden method,\n * update the namespace for its defining class (i.e\n :py:meth:`render_data[__class__]\n `) within the\n :py:class:`~term_image.renderable.RenderData` instance returned by the\n overridden method,\n * return the same :py:class:`~term_image.renderable.RenderData` instance.\n\n IMPORTANT:\n The :py:class:`~term_image.renderable.RenderData` instance returned must be\n associated [#rd-ass]_ with the type of the renderable on which this method\n is called i.e ``type(self)``. This is always the case for the base\n implementation of this method.\n\n NOTE:\n This method being called doesn't mean the data generated will be used\n immediately.\n\n .. seealso::\n :py:class:`~term_image.renderable.RenderData`,\n :py:meth:`_finalize_render_data_`,\n :py:meth:`~term_image.renderable.Renderable._init_render_`.\n \"\"\"\n render_data = RenderData(type(self))\n renderable_data: RenderableData = render_data[Renderable]\n renderable_data.update(\n size=self._get_render_size_(),\n frame_offset=self._frame,\n seek_whence=Seek.START,\n iteration=iteration,\n )\n if self.animated:\n renderable_data.duration = self._frame_duration\n\n return render_data\n\n @abstractmethod\n def _get_render_size_(self) -> geometry.Size:\n \"\"\"Returns the renderable's :term:`render size`.\n\n Returns:\n The size of the renderable's :term:`render output`.\n\n The base implementation raises :py:class:`NotImplementedError`.\n\n NOTE:\n Both dimensions are expected to be positive.\n\n .. seealso:: :py:attr:`render_size`\n \"\"\"\n raise NotImplementedError\n\n def _handle_interrupted_draw_(\n self, render_data: RenderData, render_args: RenderArgs, output: TextIO\n ) -> None:\n \"\"\"Performs any special handling necessary when an interruption occurs while\n writing a :term:`render output` to a stream.\n\n Args:\n render_data: Render data.\n render_args: Render arguments.\n output: The text I/O stream to which the render output was being written.\n\n Called by the base implementations of :py:meth:`draw` (for non-animations)\n and :py:meth:`_animate_` when :py:class:`KeyboardInterrupt` is raised while\n writing a render output.\n\n The base implementation does nothing.\n\n NOTE:\n *output* should be flushed by this method.\n\n HINT:\n For a renderable that uses SGR sequences in its render output, this method\n may write ``CSI 0 m`` to *output*.\n \"\"\"\n\n # *render_args*, no *padding*; or neither\n @overload\n def _init_render_(\n self,\n renderer: Callable[[RenderData, RenderArgs], T],\n render_args: RenderArgs | None = None,\n *,\n iteration: bool = False,\n finalize: bool = True,\n check_size: bool = False,\n allow_scroll: bool = False,\n ) -> tuple[T, None]: ...\n\n # both *render_args* and *padding*\n @overload\n def _init_render_(\n self,\n renderer: Callable[[RenderData, RenderArgs], T],\n render_args: RenderArgs | None,\n padding: OptionalPaddingT,\n *,\n iteration: bool = False,\n finalize: bool = True,\n check_size: bool = False,\n allow_scroll: bool = False,\n ) -> tuple[T, OptionalPaddingT]: ...\n\n # *padding*, no *render_args*\n @overload\n def _init_render_(\n self,\n renderer: Callable[[RenderData, RenderArgs], T],\n *,\n padding: OptionalPaddingT,\n iteration: bool = False,\n finalize: bool = True,\n check_size: bool = False,\n allow_scroll: bool = False,\n ) -> tuple[T, OptionalPaddingT]: ...\n\n def _init_render_(\n self,\n renderer: Callable[[RenderData, RenderArgs], T],\n render_args: RenderArgs | None = None,\n padding: Padding | None = None,\n *,\n iteration: bool = False,\n finalize: bool = True,\n check_size: bool = False,\n allow_scroll: bool = False,\n ) -> tuple[T, Padding | None]:\n \"\"\"Initiates a render operation.\n\n Args:\n renderer: Performs a render operation or extracts render data and arguments\n for a render operation to be performed later on.\n render_args: Render arguments.\n padding (:py:data:`OptionalPaddingT`): :term:`Render output` padding.\n iteration: Whether the render operation involves a sequence of renders\n (most likely of different frames), or it's a one-off render.\n finalize: Whether to finalize the render data passed to *renderer*\n immediately *renderer* returns.\n check_size: Whether to validate the [padded] :term:`render size` of\n **non-animations**.\n allow_scroll: Whether to validate the [padded] :term:`render height` of\n **non-animations**. Ignored if *check_size* is ``False``.\n\n Returns:\n A tuple containing\n\n * The return value of *renderer*.\n * *padding* (with equivalent **absolute** dimensions if it's an instance of\n :py:class:`~term_image.padding.AlignedPadding`).\n\n Raises:\n IncompatibleRenderArgsError: Incompatible render arguments.\n RenderSizeOutofRangeError: *check_size* is ``True`` and the [padded]\n :term:`render size` cannot fit into the :term:`terminal size`.\n\n :rtype: tuple[T, :py:data:`OptionalPaddingT`]\n\n After preparing render data and processing arguments, *renderer* is called with\n the following positional arguments:\n\n 1. Render data associated with **the renderable's class**\n 2. Render arguments associated with **the renderable's class** and initialized\n with *render_args*\n\n Any exception raised by *renderer* is propagated.\n\n IMPORTANT:\n Beyond this method (i.e any context from *renderer* onwards), use of any\n variable state (internal or external) should be avoided if possible.\n Any variable state (internal or external) required for rendering should\n be provided via :py:meth:`_get_render_data_`.\n\n If at all any variable state has to be used and is not\n reasonable/practicable to be provided via :py:meth:`_get_render_data_`,\n it should be read only once during a single render and passed to any\n nested/subsequent calls that require the value of that state during the\n same render.\n\n This is to prevent inconsistency in data used for the same render which may\n result in unexpected output.\n \"\"\"\n if not (render_args and render_args.render_cls is type(self)):\n # Validate compatibility (and convert, if compatible)\n render_args = RenderArgs(type(self), render_args)\n terminal_size = get_terminal_size()\n render_data = self._get_render_data_(iteration=iteration)\n try:\n if padding and isinstance(padding, AlignedPadding) and padding.relative:\n padding = padding.resolve(terminal_size)\n\n if check_size:\n render_size: Size = render_data[Renderable].size\n width, height = (\n padding.get_padded_size(render_size) if padding else render_size\n )\n terminal_width, terminal_height = terminal_size\n\n if width > terminal_width:\n raise RenderSizeOutofRangeError(\n f\"{'Padded render' if padding else 'Render'} width out of \"\n f\"range (got: {width}; terminal_width={terminal_width})\"\n )\n if not allow_scroll and height > terminal_height:\n raise RenderSizeOutofRangeError(\n f\"{'Padded render' if padding else 'Render'} height out of \"\n f\"range (got: {height}; terminal_height={terminal_height})\"\n )\n\n return renderer(render_data, render_args), padding\n finally:\n if finalize:\n render_data.finalize()\n\n @abstractmethod\n def _render_(self, render_data: RenderData, render_args: RenderArgs) -> Frame:\n \"\"\":term:`Renders` a frame.\n\n Args:\n render_data: Render data.\n render_args: Render arguments.\n\n Returns:\n The rendered frame.\n\n * The :py:attr:`~term_image.renderable.Frame.render_size` field =\n :py:attr:`render_data[Renderable].size\n `.\n * The :py:attr:`~term_image.renderable.Frame.render_output` field holds the\n :term:`render output`. This string should:\n\n * contain as many lines as ``render_size.height`` i.e exactly\n ``render_size.height - 1`` occurrences of ``\\\\n`` (the newline\n sequence).\n * occupy exactly ``render_size.height`` lines and ``render_size.width``\n columns on each line when drawn onto a terminal screen, **at least**\n when the render **size** it not greater than the terminal size on\n either axis.\n\n .. tip::\n If for any reason, the output behaves differently when the render\n **height** is greater than the terminal height, the behaviour, along\n with any possible alternatives or workarounds, should be duely noted.\n This doesn't apply to the **width**.\n\n * **not** end with ``\\\\n`` (the newline sequence).\n\n * As for the :py:attr:`~term_image.renderable.Frame.duration` field, if\n the renderable is:\n\n * **animated**; the value should be determined from the frame data\n source (or a default/fallback value, if undeterminable), if\n :py:attr:`render_data[Renderable].duration\n ` is\n :py:attr:`~term_image.renderable.FrameDuration.DYNAMIC`.\n Otherwise, it should be equal to\n :py:attr:`render_data[Renderable].duration\n `.\n * **non-animated**; the value range is unspecified i.e it may be given\n any value.\n\n Raises:\n StopIteration: End of iteration for an animated renderable with\n :py:attr:`~term_image.renderable.FrameCount.INDEFINITE` frame count.\n RenderError: An error occurred while rendering.\n\n NOTE:\n :py:class:`StopIteration` may be raised if and only if\n :py:attr:`render_data[Renderable].iteration\n ` is ``True``.\n Otherwise, it would be out of place.\n\n .. seealso:: :py:class:`~term_image.renderable.RenderableData`.\n \"\"\"\n raise NotImplementedError\n\n\n# Source: src/term_image/renderable/_types.py\nclass ArgsNamespace(ArgsDataNamespace, metaclass=ArgsNamespaceMeta, _base=True):\n \"\"\"ArgsNamespace(*values, **fields)\n\n :term:`Render class`\\\\ -specific render argument namespace.\n\n Args:\n values: Render argument field values.\n\n The values are mapped to fields in the order in which the fields were\n defined.\n\n fields: Render argument fields.\n\n The keywords must be names of render argument fields for the associated\n [#an-ass]_ render class.\n\n Raises:\n UnassociatedNamespaceError: The namespace class hasn't been associated\n [#an-ass]_ with a render class.\n TypeError: More values (positional arguments) than there are fields.\n UnknownArgsFieldError: Unknown field name(s).\n TypeError: Multiple values given for a field.\n\n If no value is given for a field, its default value is used.\n\n NOTE:\n * Fields are exposed as instance attributes.\n * Instances are immutable but updated copies can be created via\n :py:meth:`update`.\n\n .. Completed in /docs/source/api/renderable.rst\n \"\"\"\n\n def __init__(self, *values: Any, **fields: Any) -> None:\n default_fields = type(self)._FIELDS\n\n if len(values) > len(default_fields):\n raise TypeError(\n f\"{type(self).__name__!r} defines {len(default_fields)} render \"\n f\"argument field(s) but {len(values)} values were given\"\n )\n value_fields = dict(zip(default_fields, values))\n\n unknown = fields.keys() - default_fields.keys()\n if unknown:\n raise UnknownArgsFieldError(\n f\"Unknown render argument fields {tuple(unknown)} for \"\n f\"{type(self)._RENDER_CLS.__name__!r}\"\n )\n multiple = fields.keys() & value_fields.keys()\n if multiple:\n raise TypeError(\n f\"Got multiple values for render argument fields \"\n f\"{tuple(multiple)} of {type(self)._RENDER_CLS.__name__!r}\"\n )\n\n super().__init__({**default_fields, **value_fields, **fields})\n\n def __repr__(self) -> str:\n return \"\".join(\n (\n f\"{type(self).__name__}(\",\n \", \".join(\n f\"{name}={getattr(self, name)!r}\" for name in type(self)._FIELDS\n ),\n \")\",\n )\n )\n\n def __getattr__(self, name: str) -> Never:\n raise UnknownArgsFieldError(\n f\"Unknown render argument field {name!r} for \"\n f\"{type(self)._RENDER_CLS.__name__!r}\"\n )\n\n def __setattr__(self, name: str, value: Never) -> Never:\n raise AttributeError(\n \"Cannot modify render argument fields, use the `update()` method \"\n \"of the namespace or the containing `RenderArgs` instance, as \"\n \"applicable, instead\"\n )\n\n def __eq__(self, other: object) -> bool:\n \"\"\"Compares the namespace with another.\n\n Args:\n other: Another render argument namespace.\n\n Returns:\n ``True`` if both operands are associated with the same\n :term:`render class` and have equal field values.\n Otherwise, ``False``.\n \"\"\"\n if isinstance(other, ArgsNamespace):\n return self is other or (\n type(self)._RENDER_CLS is type(other)._RENDER_CLS\n and all(\n getattr(self, name) == getattr(other, name)\n for name in type(self)._FIELDS\n )\n )\n\n return NotImplemented\n\n def __hash__(self) -> int:\n \"\"\"Computes the hash of the namespace.\n\n Returns:\n The computed hash.\n\n IMPORTANT:\n Like tuples, an instance is hashable if and only if the field values\n are hashable.\n \"\"\"\n # Field names and their order is the same for all instances associated\n # with the same render class.\n return hash(\n (\n type(self)._RENDER_CLS,\n tuple([getattr(self, field) for field in type(self)._FIELDS]),\n )\n )\n\n def __or__(self, other: ArgsNamespace | RenderArgs) -> RenderArgs:\n \"\"\"Derives a set of render arguments from the combination of both operands.\n\n Args:\n other: Another render argument namespace or a set of render arguments.\n\n Returns:\n A set of render arguments associated with the **most derived** one\n of the associated :term:`render classes` of both operands.\n\n Raises:\n IncompatibleArgsNamespaceError: *other* is a render argument namespace\n and neither operand is compatible [#ra-com]_ [#an-com]_ with the\n associated :term:`render class` of the other.\n IncompatibleRenderArgsError: *other* is a set of render arguments\n and neither operand is compatible [#ra-com]_ [#an-com]_ with the\n associated :term:`render class` of the other.\n\n NOTE:\n * If *other* is a render argument namespace associated with the\n same :term:`render class` as *self*, *other* takes precedence.\n * If *other* is a set of render arguments that contains a namespace\n associated with the same :term:`render class` as *self*, *self* takes\n precedence.\n \"\"\"\n self_render_cls = type(self)._RENDER_CLS\n\n if isinstance(other, ArgsNamespace):\n other_render_cls = type(other)._RENDER_CLS\n if self_render_cls is other_render_cls:\n return RenderArgs(other_render_cls, other)\n if issubclass(self_render_cls, other_render_cls):\n return RenderArgs(self_render_cls, self, other)\n if issubclass(other_render_cls, self_render_cls):\n return RenderArgs(other_render_cls, self, other)\n raise IncompatibleArgsNamespaceError(\n f\"A render argument namespace for {other_render_cls.__name__!r} \"\n \"cannot be combined with a render argument namespace for \"\n f\"{self_render_cls.__name__!r}.\"\n )\n\n if isinstance(other, RenderArgs):\n other_render_cls = other.render_cls\n if issubclass(self_render_cls, other_render_cls):\n return RenderArgs(self_render_cls, other, self)\n if issubclass(other_render_cls, self_render_cls):\n return RenderArgs(other_render_cls, other, self)\n raise IncompatibleRenderArgsError(\n f\"A set of render arguments for {other_render_cls.__name__!r} \"\n \"cannot be combined with a render argument namespace for \"\n f\"{self_render_cls.__name__!r}.\"\n )\n\n return NotImplemented\n\n def __pos__(self) -> RenderArgs:\n \"\"\"Creates a set of render arguments from the namespace.\n\n Returns:\n A set of render arguments associated with the same :term:`render class`\n as the namespace and initialized with the namespace.\n\n TIP:\n ``+namespace`` is shorthand for\n :py:meth:`namespace.to_render_args() `.\n \"\"\"\n return RenderArgs(type(self)._RENDER_CLS, self)\n\n def __ror__(self, other: ArgsNamespace | RenderArgs) -> RenderArgs:\n \"\"\"Same as :py:meth:`__or__` but with reflected operands.\n\n NOTE:\n Unlike :py:meth:`__or__`, if *other* is a render argument namespace\n associated with the same :term:`render class` as *self*, *self* takes\n precedence.\n \"\"\"\n # Not commutative\n if isinstance(other, ArgsNamespace) and (\n type(self)._RENDER_CLS is type(other)._RENDER_CLS\n ):\n return RenderArgs(type(self)._RENDER_CLS, self)\n\n return type(self).__or__(self, other) # All other cases are commutative\n\n def as_dict(self) -> dict[str, Any]:\n \"\"\"Copies the namespace as a dictionary.\n\n Returns:\n A dictionary mapping field names to their values.\n\n WARNING:\n The number and order of fields are guaranteed to be the same for a\n namespace class that defines fields, its subclasses, and all their\n instances; but beyond this, should not be relied upon as the details\n (such as the specific number or order) may change without notice.\n\n The order is an implementation detail of the Render Arguments/Data API\n and the number should be considered an implementation detail of the\n specific namespace subclass.\n \"\"\"\n return {name: getattr(self, name) for name in type(self)._FIELDS}\n\n @classmethod\n def get_fields(cls) -> Mapping[str, Any]:\n \"\"\"Returns the field definitions.\n\n Returns:\n A mapping of field names to their default values.\n\n WARNING:\n The number and order of fields are guaranteed to be the same for a\n namespace class that defines fields, its subclasses, and all their\n instances; but beyond this, should not be relied upon as the details\n (such as the specific number or order) may change without notice.\n\n The order is an implementation detail of the Render Arguments/Data API\n and the number should be considered an implementation detail of the\n specific namespace subclass.\n \"\"\"\n return cls._FIELDS\n\n def to_render_args(self, render_cls: type[Renderable] | None = None) -> RenderArgs:\n \"\"\"Creates a set of render arguments from the namespace.\n\n Args:\n render_cls: A :term:`render class`, with which the namespace is\n compatible [#an-com]_.\n\n Returns:\n A set of render arguments associated with *render_cls* (or the\n associated [#an-ass]_ render class of the namespace, if ``None``) and\n initialized with the namespace.\n\n Propagates exceptions raised by the\n :py:class:`~term_image.renderable.RenderArgs` constructor, as applicable.\n\n .. seealso:: :py:meth:`__pos__`.\n \"\"\"\n return RenderArgs(render_cls or type(self)._RENDER_CLS, self)\n\n def update(self, **fields: Any) -> Self:\n \"\"\"Updates render argument fields.\n\n Args:\n fields: Render argument fields.\n\n Returns:\n A namespace with the given fields updated.\n\n Raises:\n UnknownArgsFieldError: Unknown field name(s).\n \"\"\"\n if not fields:\n return self\n\n unknown = fields.keys() - type(self)._FIELDS.keys()\n if unknown:\n raise UnknownArgsFieldError(\n f\"Unknown render argument field(s) {tuple(unknown)} for \"\n f\"{type(self)._RENDER_CLS.__name__!r}\"\n )\n\n new = type(self).__new__(type(self))\n new_fields = self.as_dict()\n new_fields.update(fields)\n super(ArgsNamespace, new).__init__(new_fields)\n\n return new", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 52244}, "tests/renderable/test_renderable.py::701": {"resolved_imports": ["src/term_image/_ctlseqs.py", "src/term_image/geometry.py", "src/term_image/padding.py", "src/term_image/renderable/_enum.py", "src/term_image/renderable/_exceptions.py", "src/term_image/renderable/_renderable.py", "src/term_image/renderable/_types.py"], "used_names": ["RenderArgs", "Size"], "enclosing_function": "test_animated", "extracted_code": "# Source: src/term_image/geometry.py\nclass Size(RawSize):\n \"\"\"The dimensions of a rectangular region.\n\n Raises:\n ValueError: Either dimension is non-positive.\n\n Same as :py:class:`RawSize`, except that both dimensions must be **positive**.\n\n IMPORTANT:\n In the case of multiple inheritance i.e if subclassing this class along with\n other classes, this class should appear last (i.e to the far right) in the\n base class list.\n \"\"\"\n\n __slots__ = ()\n\n def __new__(cls, width: int, height: int) -> Self:\n if width < 1:\n raise arg_value_error_range(\"width\", width)\n if height < 1:\n raise arg_value_error_range(\"height\", height)\n\n # Using `tuple` directly instead of `super()` for performance\n return tuple.__new__(cls, (width, height))\n\n\n# Source: src/term_image/renderable/_types.py\nclass RenderArgs(RenderArgsData):\n \"\"\"RenderArgs(render_cls, /, *namespaces)\n RenderArgs(render_cls, init_render_args, /, *namespaces)\n\n Render arguments.\n\n Args:\n render_cls: A :term:`render class`.\n init_render_args (RenderArgs | None): A set of render arguments.\n If not ``None``,\n\n * it must be compatible [#ra-com]_ with *render_cls*,\n * it'll be used to initialize the render arguments.\n\n namespaces: Render argument namespaces compatible [#an-com]_ with *render_cls*.\n\n .. note:: If multiple namespaces associated with the same :term:`render\n class` are given, the last of them takes precedence.\n\n Raises:\n IncompatibleRenderArgsError: *init_render_args* is incompatible [#ra-com]_ with\n *render_cls*.\n IncompatibleArgsNamespaceError: Incompatible [#an-com]_ render argument\n namespace.\n\n A set of render arguments (an instance of this class) is basically a container of\n render argument namespaces (instances of\n :py:class:`~term_image.renderable.ArgsNamespace`); one for\n each :term:`render class`, which has render arguments, in the Method Resolution\n Order of its associated [#ra-ass]_ render class.\n\n The namespace for each render class is derived from the following sources, in\n [descending] order of precedence:\n\n * *namespaces*\n * *init_render_args*\n * default render argument namespaces\n\n NOTE:\n Instances are immutable but updated copies can be created via :py:meth:`update`.\n\n .. seealso::\n\n :py:attr:`~term_image.renderable.Renderable.Args`\n Render class-specific render arguments.\n\n .. Completed in /docs/source/api/renderable.rst\n \"\"\"\n\n # Class Attributes =========================================================\n\n __slots__ = ()\n\n _interned: ClassVar[dict[type[Renderable], Self]] = {}\n _namespaces: MappingProxyType[type[Renderable], ArgsNamespace]\n\n # Instance Attributes ======================================================\n\n render_cls: type[Renderable]\n \"\"\"The associated :term:`render class`\"\"\"\n\n # Special Methods ==========================================================\n\n def __new__(\n cls,\n render_cls: type[Renderable],\n init_or_namespace: RenderArgs | ArgsNamespace | None = None,\n *namespaces: ArgsNamespace,\n ) -> Self:\n if init_or_namespace is None:\n init_render_args = None\n elif isinstance(init_or_namespace, RenderArgs):\n init_render_args = init_or_namespace\n else:\n init_render_args = None\n namespaces = (init_or_namespace, *namespaces)\n\n if init_render_args and not issubclass(render_cls, init_render_args.render_cls):\n raise IncompatibleRenderArgsError(\n f\"'init_render_args' (associated with \"\n f\"{init_render_args.render_cls.__name__!r}) is incompatible with \"\n f\"{render_cls.__name__!r} \"\n )\n\n if not namespaces:\n # has default namespaces only\n if (\n not init_render_args\n or init_render_args is BASE_RENDER_ARGS\n or cls._interned.get(init_render_args.render_cls) is init_render_args\n ):\n try:\n return cls._interned[render_cls]\n except KeyError:\n pass\n\n if (\n init_render_args\n and type(init_render_args) is cls\n and init_render_args.render_cls is render_cls\n ):\n return init_render_args\n\n return super().__new__(cls)\n\n def __init__(\n self,\n render_cls: type[Renderable],\n init_or_namespace: RenderArgs | ArgsNamespace | None = None,\n *namespaces: ArgsNamespace,\n ) -> None:\n if init_or_namespace is None:\n init_render_args = None\n elif isinstance(init_or_namespace, RenderArgs):\n init_render_args = init_or_namespace\n else:\n init_render_args = None\n namespaces = (init_or_namespace, *namespaces)\n\n # has default namespaces only\n if not namespaces and (\n not init_render_args\n or init_render_args is BASE_RENDER_ARGS\n or (\n type(self)._interned.get(init_render_args.render_cls)\n is init_render_args\n )\n ):\n if render_cls in type(self)._interned: # has been initialized\n return\n intern = True\n else:\n intern = False\n\n if init_render_args is self:\n return\n\n namespaces_dict = render_cls._ALL_DEFAULT_ARGS.copy()\n\n # if `init_render_args` is non-default\n if init_render_args and BASE_RENDER_ARGS is not init_render_args is not (\n type(self)._interned.get(init_render_args.render_cls)\n ):\n namespaces_dict.update(init_render_args._namespaces)\n\n for index, namespace in enumerate(namespaces):\n if namespace._RENDER_CLS not in namespaces_dict:\n raise IncompatibleArgsNamespaceError(\n f\"'namespaces[{index}]' (associated with \"\n f\"{namespace._RENDER_CLS.__name__!r}) is incompatible with \"\n f\"{render_cls.__name__!r} \"\n )\n namespaces_dict[namespace._RENDER_CLS] = namespace\n\n super().__init__(render_cls, namespaces_dict)\n\n if intern:\n type(self)._interned[render_cls] = self\n\n def __init_subclass__(cls, **kwargs: Any) -> None:\n cls._interned = {}\n super().__init_subclass__(**kwargs)\n\n def __contains__(self, namespace: ArgsNamespace) -> bool:\n \"\"\"Checks if a render argument namespace is contained in this set of render\n arguments.\n\n Args:\n namespace: A render argument namespace.\n\n Returns:\n ``True`` if the given namespace is equal to any of the namespaces\n contained in this set of render arguments. Otherwise, ``False``.\n \"\"\"\n return None is not self._namespaces.get(namespace._RENDER_CLS) == namespace\n\n def __eq__(self, other: object) -> bool:\n \"\"\"Compares this set of render arguments with another.\n\n Args:\n other: Another set of render arguments.\n\n Returns:\n ``True`` if both are associated with the same :term:`render class`\n and have equal argument values. Otherwise, ``False``.\n \"\"\"\n if isinstance(other, RenderArgs):\n return (\n self is other\n or self.render_cls is other.render_cls\n and self._namespaces == other._namespaces\n )\n\n return NotImplemented\n\n def __getitem__(self, render_cls: type[Renderable]) -> Any:\n \"\"\"Returns a constituent namespace.\n\n Args:\n render_cls: A :term:`render class` of which :py:attr:`render_cls` is a\n subclass (which may be :py:attr:`render_cls` itself) and which has\n render arguments.\n\n Returns:\n The constituent namespace associated with *render_cls*.\n\n Raises:\n TypeError: *render_cls* is not a render class.\n ValueError: :py:attr:`render_cls` is not a subclass of *render_cls*.\n NoArgsNamespaceError: *render_cls* has no render arguments.\n\n NOTE:\n The return type hint is :py:class:`~typing.Any` only for compatibility\n with static type checking, as this aspect of the interface seems too\n dynamic to be correctly expressed with the exisiting type system.\n\n Regardless, the return value is guaranteed to always be an instance\n of a render argument namespace class associated with *render_cls*.\n For instance, the following would always be valid for\n :py:class:`~term_image.renderable.Renderable`::\n\n renderable_args: RenderableArgs = render_args[Renderable]\n\n and similar idioms are encouraged to be used for other render classes.\n \"\"\"\n try:\n return self._namespaces[render_cls]\n except TypeError:\n raise arg_type_error(\"render_cls\", render_cls) from None\n except KeyError:\n if not isinstance(render_cls, RenderableMeta):\n raise arg_type_error(\"render_cls\", render_cls) from None\n\n if issubclass(self.render_cls, render_cls):\n raise NoArgsNamespaceError(\n f\"{render_cls.__name__!r} has no render arguments\"\n ) from None\n\n raise ValueError(\n f\"{self.render_cls.__name__!r} is not a subclass of \"\n f\"{render_cls.__name__!r}\"\n ) from None\n\n def __hash__(self) -> int:\n \"\"\"Computes the hash of the render arguments.\n\n Returns:\n The computed hash.\n\n IMPORTANT:\n Like tuples, an instance is hashable if and only if the constituent\n namespaces are hashable.\n \"\"\"\n # Namespaces are always in the same order, wrt their respective associated\n # render classes, for all instances associated with the same render class.\n return hash((self.render_cls, tuple(self._namespaces.values())))\n\n def __iter__(self) -> Iterator[ArgsNamespace]:\n \"\"\"Returns an iterator that yields the constituent namespaces.\n\n Returns:\n An iterator that yields the constituent namespaces.\n\n WARNING:\n The number and order of namespaces is guaranteed to be the same across all\n instances associated [#ra-ass]_ with the same :term:`render class` but\n beyond this, should not be relied upon as the details (such as the\n specific number or order) may change without notice.\n\n The order is an implementation detail of the Renderable API and the number\n should be considered alike with respect to the associated render class.\n \"\"\"\n return iter(self._namespaces.values())\n\n def __repr__(self) -> str:\n return \"\".join(\n (\n f\"{type(self).__name__}({self.render_cls.__name__}\",\n \", \" if self._namespaces else \"\",\n \", \".join(map(repr, self._namespaces.values())),\n \")\",\n )\n )\n\n # Public Methods ===========================================================\n\n def convert(self, render_cls: type[Renderable]) -> RenderArgs:\n \"\"\"Converts the set of render arguments to one for a related render class.\n\n Args:\n render_cls: A :term:`render class` of which :py:attr:`render_cls` is a\n parent or child (which may be :py:attr:`render_cls` itself).\n\n Returns:\n A set of render arguments associated [#ra-ass]_ with *render_cls* and\n initialized with all constituent namespaces (of this set of render\n arguments, *self*) that are compatible [#an-com]_ with *render_cls*.\n\n Raises:\n ValueError: *render_cls* is not a parent or child of :py:attr:`render_cls`.\n \"\"\"\n if render_cls is self.render_cls:\n return self\n\n if issubclass(render_cls, self.render_cls):\n return RenderArgs(render_cls, self)\n\n if issubclass(self.render_cls, render_cls):\n render_cls_args_mro = render_cls._ALL_DEFAULT_ARGS\n return RenderArgs(\n render_cls,\n *[\n namespace\n for cls, namespace in self._namespaces.items()\n if cls in render_cls_args_mro\n ],\n )\n\n raise ValueError(\n f\"{render_cls.__name__!r} is not a parent or child of \"\n f\"{self.render_cls.__name__!r}\"\n )\n\n @overload\n def update(\n self,\n namespace: ArgsNamespace,\n /,\n *namespaces: ArgsNamespace,\n ) -> RenderArgs: ...\n\n @overload\n def update(\n self,\n render_cls: type[Renderable],\n /,\n **fields: Any,\n ) -> RenderArgs: ...\n\n def update(\n self,\n render_cls_or_namespace: type[Renderable] | ArgsNamespace,\n /,\n *namespaces: ArgsNamespace,\n **fields: Any,\n ) -> RenderArgs:\n \"\"\"update(namespace, /, *namespaces) -> RenderArgs\n update(render_cls, /, **fields) -> RenderArgs\n\n Replaces or updates render argument namespaces.\n\n Args:\n namespace (ArgsNamespace): Prepended to *namespaces*.\n namespaces: Render argument namespaces compatible [#an-com]_ with\n :py:attr:`render_cls`.\n\n .. note:: If multiple namespaces associated with the same :term:`render\n class` are given, the last of them takes precedence.\n\n render_cls (type[Renderable]): A :term:`render class` of which\n :py:attr:`render_cls` is a subclass (which may be :py:attr:`render_cls`\n itself) and which has render arguments.\n fields: Render argument fields.\n\n The keywords must be names of render argument fields for *render_cls*.\n\n Returns:\n For the **first** form, an instance with the namespaces for the respective\n associated :term:`render classes` of the given namespaces replaced.\n\n For the **second** form, an instance with the given render argument fields\n for *render_cls* updated, if any.\n\n Raises:\n TypeError: The arguments given do not conform to any of the expected forms.\n\n Propagates exceptions raised by:\n\n * the class constructor, for the **first** form.\n * :py:meth:`__getitem__` and :py:meth:`ArgsNamespace.update()\n `, for the **second** form.\n \"\"\"\n if isinstance(render_cls_or_namespace, RenderableMeta):\n if namespaces:\n raise TypeError(\n \"No other positional argument is expected when the first argument \"\n \"is a render class\"\n )\n render_cls = render_cls_or_namespace\n else:\n if fields:\n raise TypeError(\n \"No keyword argument is expected when the first argument is \"\n \"a render argument namespace\"\n )\n render_cls = None\n namespaces = (render_cls_or_namespace, *namespaces)\n\n return RenderArgs(\n self.render_cls,\n self,\n *((self[render_cls].update(**fields),) if render_cls else namespaces),\n )", "n_imports_parsed": 14, "n_files_resolved": 7, "n_chars_extracted": 15637}, "tests/test_image/test_base.py::430": {"resolved_imports": ["src/term_image/__init__.py", "src/term_image/_ctlseqs.py", "src/term_image/exceptions.py", "src/term_image/image/block.py", "src/term_image/image/common.py"], "used_names": ["BlockImage", "pytest", "python_img"], "enclosing_function": "test_seek_tell", "extracted_code": "# Source: src/term_image/image/block.py\nclass BlockImage(TextImage):\n \"\"\"A render style using unicode half blocks and direct-color colour escape\n sequences.\n\n See :py:class:`TextImage` for the description of the constructor.\n \"\"\"\n\n @classmethod\n def is_supported(cls):\n if cls._supported is None:\n COLORTERM = os.environ.get(\"COLORTERM\") or \"\"\n TERM = os.environ.get(\"TERM\") or \"\"\n cls._supported = (\n \"truecolor\" in COLORTERM or \"24bit\" in COLORTERM or \"256color\" in TERM\n )\n\n return cls._supported\n\n def _get_render_size(self) -> Tuple[int, int]:\n return tuple(map(mul, self.rendered_size, (1, 2)))\n\n @staticmethod\n def _pixels_cols(\n *, pixels: Optional[int] = None, cols: Optional[int] = None\n ) -> int:\n return pixels if pixels is not None else cols\n\n @staticmethod\n def _pixels_lines(\n *, pixels: Optional[int] = None, lines: Optional[int] = None\n ) -> int:\n return ceil(pixels / 2) if pixels is not None else lines * 2\n\n def _render_image(\n self,\n img: PIL.Image.Image,\n alpha: Union[None, float, str],\n *,\n frame: bool = False,\n split_cells: bool = False,\n ) -> str:\n # NOTE:\n # It's more efficient to write separate strings to the buffer separately\n # than concatenate and write together.\n\n def update_buffer():\n if alpha:\n no_alpha = False\n if a_cluster1 == 0 == a_cluster2:\n buf_write(SGR_DEFAULT)\n buf_write(blank * n)\n elif a_cluster1 == 0: # up is transparent\n buf_write(SGR_DEFAULT)\n buf_write(SGR_FG_DIRECT % cluster2)\n buf_write(lower_pixel * n)\n elif a_cluster2 == 0: # down is transparent\n buf_write(SGR_DEFAULT)\n buf_write(SGR_FG_DIRECT % cluster1)\n buf_write(upper_pixel * n)\n else:\n no_alpha = True\n\n if not alpha or no_alpha:\n r, g, b = cluster2\n # Kitty does not render BG colors equal to the default BG color\n if is_on_kitty and cluster2 == bg_color:\n r += r < 255 or -1\n buf_write(SGR_BG_DIRECT % (r, g, b))\n if cluster1 == cluster2:\n buf_write(blank * n)\n else:\n buf_write(SGR_FG_DIRECT % cluster1)\n buf_write(upper_pixel * n)\n\n buffer = io.StringIO()\n buf_write = buffer.write # Eliminate attribute resolution cost\n\n bg_color = get_fg_bg_colors()[1]\n is_on_kitty = self._is_on_kitty()\n if split_cells:\n blank = \" \\0\"\n lower_pixel = LOWER_PIXEL + \"\\0\"\n upper_pixel = UPPER_PIXEL + \"\\0\"\n else:\n blank = \" \"\n lower_pixel = LOWER_PIXEL\n upper_pixel = UPPER_PIXEL\n end_of_line = SGR_DEFAULT + \"\\n\"\n\n width, height = self._get_render_size()\n frame_img = img if frame else None\n img, rgb, a = self._get_render_data(img, alpha, round_alpha=True, frame=frame)\n alpha = img.mode == \"RGBA\"\n\n # clean up (ImageIterator uses one PIL image throughout)\n if frame_img is not img:\n self._close_image(img)\n\n rgb_pairs = (\n (\n zip(rgb[x : x + width], rgb[x + width : x + width * 2]),\n (rgb[x], rgb[x + width]),\n )\n for x in range(0, len(rgb), width * 2)\n )\n a_pairs = (\n (\n zip(a[x : x + width], a[x + width : x + width * 2]),\n (a[x], a[x + width]),\n )\n for x in range(0, len(a), width * 2)\n )\n\n row_no = 0\n # Two rows of pixels per line\n for (rgb_pair, (cluster1, cluster2)), (a_pair, (a_cluster1, a_cluster2)) in zip(\n rgb_pairs, a_pairs\n ):\n row_no += 2\n n = 0\n for (px1, px2), (a1, a2) in zip(rgb_pair, a_pair):\n # Color-code characters and write to buffer\n # when upper and/or lower pixel color/alpha-level changes\n if not (alpha and a1 == a_cluster1 == 0 == a_cluster2 == a2) and (\n px1 != cluster1\n or px2 != cluster2\n or alpha\n and (\n # From non-transparent to transparent\n a_cluster1 != a1 == 0\n or a_cluster2 != a2 == 0\n # From transparent to non-transparent\n or 0 == a_cluster1 != a1\n or 0 == a_cluster2 != a2\n )\n ):\n update_buffer()\n cluster1 = px1\n cluster2 = px2\n if alpha:\n a_cluster1 = a1\n a_cluster2 = a2\n n = 0\n n += 1\n\n update_buffer() # Rest of the line\n if split_cells:\n # Set the last \"\\0\" to be overwritten by the next byte\n buffer.seek(buffer.tell() - 1)\n if row_no < height: # last line not yet rendered\n buf_write(end_of_line)\n\n buf_write(SGR_DEFAULT) # Reset color after last line\n\n with buffer:\n return buffer.getvalue()", "n_imports_parsed": 16, "n_files_resolved": 5, "n_chars_extracted": 5566}, "tests/test_iterator.py::136": {"resolved_imports": ["src/term_image/_ctlseqs.py", "src/term_image/exceptions.py", "src/term_image/image/block.py", "src/term_image/image/common.py"], "used_names": ["BlockImage", "ImageIterator"], "enclosing_function": "test_iter", "extracted_code": "# Source: src/term_image/image/block.py\nclass BlockImage(TextImage):\n \"\"\"A render style using unicode half blocks and direct-color colour escape\n sequences.\n\n See :py:class:`TextImage` for the description of the constructor.\n \"\"\"\n\n @classmethod\n def is_supported(cls):\n if cls._supported is None:\n COLORTERM = os.environ.get(\"COLORTERM\") or \"\"\n TERM = os.environ.get(\"TERM\") or \"\"\n cls._supported = (\n \"truecolor\" in COLORTERM or \"24bit\" in COLORTERM or \"256color\" in TERM\n )\n\n return cls._supported\n\n def _get_render_size(self) -> Tuple[int, int]:\n return tuple(map(mul, self.rendered_size, (1, 2)))\n\n @staticmethod\n def _pixels_cols(\n *, pixels: Optional[int] = None, cols: Optional[int] = None\n ) -> int:\n return pixels if pixels is not None else cols\n\n @staticmethod\n def _pixels_lines(\n *, pixels: Optional[int] = None, lines: Optional[int] = None\n ) -> int:\n return ceil(pixels / 2) if pixels is not None else lines * 2\n\n def _render_image(\n self,\n img: PIL.Image.Image,\n alpha: Union[None, float, str],\n *,\n frame: bool = False,\n split_cells: bool = False,\n ) -> str:\n # NOTE:\n # It's more efficient to write separate strings to the buffer separately\n # than concatenate and write together.\n\n def update_buffer():\n if alpha:\n no_alpha = False\n if a_cluster1 == 0 == a_cluster2:\n buf_write(SGR_DEFAULT)\n buf_write(blank * n)\n elif a_cluster1 == 0: # up is transparent\n buf_write(SGR_DEFAULT)\n buf_write(SGR_FG_DIRECT % cluster2)\n buf_write(lower_pixel * n)\n elif a_cluster2 == 0: # down is transparent\n buf_write(SGR_DEFAULT)\n buf_write(SGR_FG_DIRECT % cluster1)\n buf_write(upper_pixel * n)\n else:\n no_alpha = True\n\n if not alpha or no_alpha:\n r, g, b = cluster2\n # Kitty does not render BG colors equal to the default BG color\n if is_on_kitty and cluster2 == bg_color:\n r += r < 255 or -1\n buf_write(SGR_BG_DIRECT % (r, g, b))\n if cluster1 == cluster2:\n buf_write(blank * n)\n else:\n buf_write(SGR_FG_DIRECT % cluster1)\n buf_write(upper_pixel * n)\n\n buffer = io.StringIO()\n buf_write = buffer.write # Eliminate attribute resolution cost\n\n bg_color = get_fg_bg_colors()[1]\n is_on_kitty = self._is_on_kitty()\n if split_cells:\n blank = \" \\0\"\n lower_pixel = LOWER_PIXEL + \"\\0\"\n upper_pixel = UPPER_PIXEL + \"\\0\"\n else:\n blank = \" \"\n lower_pixel = LOWER_PIXEL\n upper_pixel = UPPER_PIXEL\n end_of_line = SGR_DEFAULT + \"\\n\"\n\n width, height = self._get_render_size()\n frame_img = img if frame else None\n img, rgb, a = self._get_render_data(img, alpha, round_alpha=True, frame=frame)\n alpha = img.mode == \"RGBA\"\n\n # clean up (ImageIterator uses one PIL image throughout)\n if frame_img is not img:\n self._close_image(img)\n\n rgb_pairs = (\n (\n zip(rgb[x : x + width], rgb[x + width : x + width * 2]),\n (rgb[x], rgb[x + width]),\n )\n for x in range(0, len(rgb), width * 2)\n )\n a_pairs = (\n (\n zip(a[x : x + width], a[x + width : x + width * 2]),\n (a[x], a[x + width]),\n )\n for x in range(0, len(a), width * 2)\n )\n\n row_no = 0\n # Two rows of pixels per line\n for (rgb_pair, (cluster1, cluster2)), (a_pair, (a_cluster1, a_cluster2)) in zip(\n rgb_pairs, a_pairs\n ):\n row_no += 2\n n = 0\n for (px1, px2), (a1, a2) in zip(rgb_pair, a_pair):\n # Color-code characters and write to buffer\n # when upper and/or lower pixel color/alpha-level changes\n if not (alpha and a1 == a_cluster1 == 0 == a_cluster2 == a2) and (\n px1 != cluster1\n or px2 != cluster2\n or alpha\n and (\n # From non-transparent to transparent\n a_cluster1 != a1 == 0\n or a_cluster2 != a2 == 0\n # From transparent to non-transparent\n or 0 == a_cluster1 != a1\n or 0 == a_cluster2 != a2\n )\n ):\n update_buffer()\n cluster1 = px1\n cluster2 = px2\n if alpha:\n a_cluster1 = a1\n a_cluster2 = a2\n n = 0\n n += 1\n\n update_buffer() # Rest of the line\n if split_cells:\n # Set the last \"\\0\" to be overwritten by the next byte\n buffer.seek(buffer.tell() - 1)\n if row_no < height: # last line not yet rendered\n buf_write(end_of_line)\n\n buf_write(SGR_DEFAULT) # Reset color after last line\n\n with buffer:\n return buffer.getvalue()\n\n\n# Source: src/term_image/image/common.py\nclass ImageIterator:\n \"\"\"Efficiently iterate over :term:`rendered` frames of an :term:`animated` image\n\n Args:\n image: Animated image.\n repeat: The number of times to go over the entire image. A negative value\n implies infinite repetition.\n format_spec: The :ref:`format specifier ` for the rendered\n frames (default: auto).\n cached: Determines if the :term:`rendered` frames will be cached (for speed up\n of subsequent renders) or not. If it is\n\n * a boolean, caching is enabled if ``True``. Otherwise, caching is disabled.\n * a positive integer, caching is enabled only if the framecount of the image\n is less than or equal to the given number.\n\n Raises:\n TypeError: An argument is of an inappropriate type.\n ValueError: An argument is of an appropriate type but has an\n unexpected/invalid value.\n term_image.exceptions.StyleError: Invalid style-specific format specifier.\n\n * If *repeat* equals ``1``, caching is disabled.\n * The iterator has immediate response to changes in the image size.\n * If the image size is :term:`dynamic `, it's computed per frame.\n * The number of the last yielded frame is set as the image's seek position.\n * Directly adjusting the seek position of the image doesn't affect iteration.\n Use :py:meth:`ImageIterator.seek` instead.\n * After the iterator is exhausted, the underlying image is set to frame ``0``.\n \"\"\"\n\n def __init__(\n self,\n image: BaseImage,\n repeat: int = -1,\n format_spec: str = \"\",\n cached: Union[bool, int] = 100,\n ) -> None:\n if not isinstance(image, BaseImage):\n raise arg_type_error(\"image\", image)\n if not image._is_animated:\n raise ValueError(\"'image' is not animated\")\n\n if not isinstance(repeat, int):\n raise arg_type_error(\"repeat\", repeat)\n if not repeat:\n raise arg_value_error(\"repeat\", repeat)\n\n if not isinstance(format_spec, str):\n raise arg_type_error(\"format_spec\", format_spec)\n *fmt, alpha, style_args = image._check_format_spec(format_spec)\n\n if not isinstance(cached, int): # `bool` is a subclass of `int`\n raise arg_type_error(\"cached\", cached)\n if False is not cached <= 0:\n raise arg_value_error_range(\"cached\", cached)\n\n self._image = image\n self._repeat = repeat\n self._format = format_spec\n self._cached = repeat != 1 and (\n cached if isinstance(cached, bool) else image.n_frames <= cached\n )\n self._loop_no = None\n self._animator = image._renderer(\n self._animate, alpha, fmt, style_args, check_size=False\n )\n\n def __del__(self) -> None:\n self.close()\n\n def __iter__(self) -> ImageIterator:\n return self\n\n def __next__(self) -> str:\n try:\n return next(self._animator)\n except StopIteration:\n self.close()\n raise StopIteration(\n \"Iteration has reached the given repeat count\"\n ) from None\n except AttributeError as e:\n if str(e).endswith(\"'_animator'\"):\n raise StopIteration(\"Iterator exhausted or closed\") from None\n else:\n self.close()\n raise\n except Exception:\n self.close()\n raise\n\n def __repr__(self) -> str:\n return (\n \"{}(image={!r}, repeat={}, format_spec={!r}, cached={}, loop_no={})\".format(\n type(self).__name__,\n *self.__dict__.values(),\n )\n )\n\n loop_no = property(\n lambda self: self._loop_no,\n doc=\"\"\"Iteration repeat countdown\n\n :type: Optional[int]\n\n GET:\n Returns:\n\n * ``None``, if iteration hasn't started.\n * Otherwise, the current iteration repeat countdown value.\n\n Changes on the first iteration of each loop, except for infinite iteration\n where it's always ``-1``. When iteration has ended, the value is zero.\n \"\"\",\n )\n\n def close(self) -> None:\n \"\"\"Closes the iterator and releases resources used.\n\n Does not reset the frame number of the underlying image.\n\n NOTE:\n This method is automatically called when the iterator is exhausted or\n garbage-collected.\n \"\"\"\n try:\n self._animator.close()\n del self._animator\n self._image._close_image(self._img)\n del self._img\n except AttributeError:\n pass\n\n def seek(self, pos: int) -> None:\n \"\"\"Sets the frame number to be yielded on the next iteration without affecting\n the repeat count.\n\n Args:\n pos: Next frame number.\n\n Raises:\n TypeError: An argument is of an inappropriate type.\n ValueError: An argument is of an appropriate type but has an\n unexpected/invalid value.\n term_image.exceptions.TermImageError: Iteration has not yet started or the\n iterator is exhausted/closed.\n\n Frame numbers start from ``0`` (zero).\n \"\"\"\n if not isinstance(pos, int):\n raise arg_type_error(\"pos\", pos)\n if not 0 <= pos < self._image.n_frames:\n raise arg_value_error_range(\"pos\", pos, f\"n_frames={self._image.n_frames}\")\n\n try:\n self._animator.send(pos)\n except TypeError:\n raise TermImageError(\"Iteration has not yet started\") from None\n except AttributeError:\n raise TermImageError(\"Iterator exhausted or closed\") from None\n\n def _animate(\n self,\n img: PIL.Image.Image,\n alpha: Union[None, float, str],\n fmt: Tuple[Union[None, str, int]],\n style_args: Dict[str, Any],\n ) -> Generator[str, int, None]:\n \"\"\"Returns a generator that yields rendered and formatted frames of the\n underlying image.\n \"\"\"\n self._img = img # For cleanup\n image = self._image\n cached = self._cached\n self._loop_no = repeat = self._repeat\n if cached:\n cache = [(None,) * 2] * image.n_frames\n\n sent = None\n n = 0\n while repeat:\n if sent is None:\n image._seek_position = n\n try:\n frame = image._format_render(\n image._render_image(img, alpha, frame=True, **style_args), *fmt\n )\n except EOFError:\n image._seek_position = n = 0\n if repeat > 0: # Avoid infinitely large negative numbers\n self._loop_no = repeat = repeat - 1\n if cached:\n break\n continue\n else:\n if cached:\n cache[n] = (frame, hash(image.rendered_size))\n\n sent = yield frame\n n = n + 1 if sent is None else sent - 1\n\n if cached:\n n_frames = len(cache)\n while repeat:\n while n < n_frames:\n if sent is None:\n image._seek_position = n\n frame, size_hash = cache[n]\n if hash(image.rendered_size) != size_hash:\n frame = image._format_render(\n image._render_image(img, alpha, frame=True, **style_args),\n *fmt,\n )\n cache[n] = (frame, hash(image.rendered_size))\n\n sent = yield frame\n n = n + 1 if sent is None else sent - 1\n\n image._seek_position = n = 0\n if repeat > 0: # Avoid infinitely large negative numbers\n self._loop_no = repeat = repeat - 1\n\n # For consistency in behaviour\n if img is image._source:\n img.seek(0)", "n_imports_parsed": 7, "n_files_resolved": 4, "n_chars_extracted": 13671}, "tests/test_image/test_base.py::237": {"resolved_imports": ["src/term_image/__init__.py", "src/term_image/_ctlseqs.py", "src/term_image/exceptions.py", "src/term_image/image/block.py", "src/term_image/image/common.py"], "used_names": ["BlockImage", "Size", "_size", "pytest", "python_img"], "enclosing_function": "test_height", "extracted_code": "# Source: src/term_image/image/block.py\nclass BlockImage(TextImage):\n \"\"\"A render style using unicode half blocks and direct-color colour escape\n sequences.\n\n See :py:class:`TextImage` for the description of the constructor.\n \"\"\"\n\n @classmethod\n def is_supported(cls):\n if cls._supported is None:\n COLORTERM = os.environ.get(\"COLORTERM\") or \"\"\n TERM = os.environ.get(\"TERM\") or \"\"\n cls._supported = (\n \"truecolor\" in COLORTERM or \"24bit\" in COLORTERM or \"256color\" in TERM\n )\n\n return cls._supported\n\n def _get_render_size(self) -> Tuple[int, int]:\n return tuple(map(mul, self.rendered_size, (1, 2)))\n\n @staticmethod\n def _pixels_cols(\n *, pixels: Optional[int] = None, cols: Optional[int] = None\n ) -> int:\n return pixels if pixels is not None else cols\n\n @staticmethod\n def _pixels_lines(\n *, pixels: Optional[int] = None, lines: Optional[int] = None\n ) -> int:\n return ceil(pixels / 2) if pixels is not None else lines * 2\n\n def _render_image(\n self,\n img: PIL.Image.Image,\n alpha: Union[None, float, str],\n *,\n frame: bool = False,\n split_cells: bool = False,\n ) -> str:\n # NOTE:\n # It's more efficient to write separate strings to the buffer separately\n # than concatenate and write together.\n\n def update_buffer():\n if alpha:\n no_alpha = False\n if a_cluster1 == 0 == a_cluster2:\n buf_write(SGR_DEFAULT)\n buf_write(blank * n)\n elif a_cluster1 == 0: # up is transparent\n buf_write(SGR_DEFAULT)\n buf_write(SGR_FG_DIRECT % cluster2)\n buf_write(lower_pixel * n)\n elif a_cluster2 == 0: # down is transparent\n buf_write(SGR_DEFAULT)\n buf_write(SGR_FG_DIRECT % cluster1)\n buf_write(upper_pixel * n)\n else:\n no_alpha = True\n\n if not alpha or no_alpha:\n r, g, b = cluster2\n # Kitty does not render BG colors equal to the default BG color\n if is_on_kitty and cluster2 == bg_color:\n r += r < 255 or -1\n buf_write(SGR_BG_DIRECT % (r, g, b))\n if cluster1 == cluster2:\n buf_write(blank * n)\n else:\n buf_write(SGR_FG_DIRECT % cluster1)\n buf_write(upper_pixel * n)\n\n buffer = io.StringIO()\n buf_write = buffer.write # Eliminate attribute resolution cost\n\n bg_color = get_fg_bg_colors()[1]\n is_on_kitty = self._is_on_kitty()\n if split_cells:\n blank = \" \\0\"\n lower_pixel = LOWER_PIXEL + \"\\0\"\n upper_pixel = UPPER_PIXEL + \"\\0\"\n else:\n blank = \" \"\n lower_pixel = LOWER_PIXEL\n upper_pixel = UPPER_PIXEL\n end_of_line = SGR_DEFAULT + \"\\n\"\n\n width, height = self._get_render_size()\n frame_img = img if frame else None\n img, rgb, a = self._get_render_data(img, alpha, round_alpha=True, frame=frame)\n alpha = img.mode == \"RGBA\"\n\n # clean up (ImageIterator uses one PIL image throughout)\n if frame_img is not img:\n self._close_image(img)\n\n rgb_pairs = (\n (\n zip(rgb[x : x + width], rgb[x + width : x + width * 2]),\n (rgb[x], rgb[x + width]),\n )\n for x in range(0, len(rgb), width * 2)\n )\n a_pairs = (\n (\n zip(a[x : x + width], a[x + width : x + width * 2]),\n (a[x], a[x + width]),\n )\n for x in range(0, len(a), width * 2)\n )\n\n row_no = 0\n # Two rows of pixels per line\n for (rgb_pair, (cluster1, cluster2)), (a_pair, (a_cluster1, a_cluster2)) in zip(\n rgb_pairs, a_pairs\n ):\n row_no += 2\n n = 0\n for (px1, px2), (a1, a2) in zip(rgb_pair, a_pair):\n # Color-code characters and write to buffer\n # when upper and/or lower pixel color/alpha-level changes\n if not (alpha and a1 == a_cluster1 == 0 == a_cluster2 == a2) and (\n px1 != cluster1\n or px2 != cluster2\n or alpha\n and (\n # From non-transparent to transparent\n a_cluster1 != a1 == 0\n or a_cluster2 != a2 == 0\n # From transparent to non-transparent\n or 0 == a_cluster1 != a1\n or 0 == a_cluster2 != a2\n )\n ):\n update_buffer()\n cluster1 = px1\n cluster2 = px2\n if alpha:\n a_cluster1 = a1\n a_cluster2 = a2\n n = 0\n n += 1\n\n update_buffer() # Rest of the line\n if split_cells:\n # Set the last \"\\0\" to be overwritten by the next byte\n buffer.seek(buffer.tell() - 1)\n if row_no < height: # last line not yet rendered\n buf_write(end_of_line)\n\n buf_write(SGR_DEFAULT) # Reset color after last line\n\n with buffer:\n return buffer.getvalue()\n\n\n# Source: src/term_image/image/common.py\nclass Size(Enum):\n \"\"\"Enumeration for :term:`automatic sizing`.\"\"\"\n\n #: Equivalent to :py:attr:`ORIGINAL` if it will fit into the\n #: :term:`frame size`, else :py:attr:`FIT`.\n #:\n #: :meta hide-value:\n AUTO = Hidden()\n\n #: The image size is set to fit optimally **within** the :term:`frame size`.\n #:\n #: :meta hide-value:\n FIT = Hidden()\n\n #: The size is set such that the width is exactly the :term:`frame width`,\n #: regardless of the :term:`cell ratio`.\n #:\n #: :meta hide-value:\n FIT_TO_WIDTH = Hidden()\n\n #: The image size is set such that the image is rendered with as many pixels as the\n #: the original image consists of.\n #:\n #: :meta hide-value:\n ORIGINAL = Hidden()", "n_imports_parsed": 16, "n_files_resolved": 5, "n_chars_extracted": 6347}, "tests/test_color.py::22": {"resolved_imports": ["src/term_image/color.py"], "used_names": ["Color"], "enclosing_function": "test_r", "extracted_code": "# Source: src/term_image/color.py\nclass Color(_DummyColor):\n \"\"\"A color.\n\n Args:\n r: The red channel.\n g: The green channel.\n b: The blue channel.\n a: The alpha channel (opacity).\n\n Raises:\n ValueError: The value of a channel is not within the valid range.\n\n NOTE:\n The valid value range for all channels is 0 to 255, both inclusive.\n\n TIP:\n This class is a :py:class:`~typing.NamedTuple` of four fields.\n\n WARNING:\n In the case of multiple inheritance i.e if subclassing this class along with\n other classes, this class should appear last (i.e to the far right) in the\n base class list.\n \"\"\"\n\n __slots__ = ()\n\n # Overrides these descriptors in order to speed up attribute resolution and to\n # simplify auto documentation.\n r: int = _DummyColor.r\n r.__doc__ = \"\"\"The red channel\"\"\"\n\n g: int = _DummyColor.g\n g.__doc__ = \"\"\"The green channel\"\"\"\n\n b: int = _DummyColor.b\n b.__doc__ = \"\"\"The blue channel\"\"\"\n\n a: int = _DummyColor.a\n a.__doc__ = \"\"\"The alpha channel (opacity)\"\"\"\n\n def __new__(cls, r: int, g: int, b: int, a: int = 255) -> Self:\n # Only the 8 LSb may be set for any value within the range [0, 255].\n # `x & ~255` unsets the 8 LSb. Hence, if the result is non-zero (i.e any\n # of the bits above the lowest 8 is set), it implies `x` is out of range.\n #\n # Actually benchmarked *this* against the \"simpler\" logically-negated chained\n # comparison (i.e `0 <= x <= 255`) and *this* was significantly faster for all\n # cases i.e within, on the boundaries, and outside (on both sides).\n if (r | g | b | a) & ~255: # First test to see if *any* is out of range\n if r & ~255:\n raise arg_value_error_range(\"r\", r)\n if g & ~255:\n raise arg_value_error_range(\"g\", g)\n if b & ~255:\n raise arg_value_error_range(\"b\", b)\n # There's no point checking since at least one is out of range\n raise arg_value_error_range(\"a\", a)\n\n # Using `tuple` directly instead of `super()` for performance\n return tuple.__new__(cls, (r, g, b, a))\n\n @property\n def hex(self) -> str:\n \"\"\"Converts the color to its RGBA hexadecimal representation.\n\n Returns:\n The RGBA hex color string, starting with the ``#`` character i.e\n ``#rrggbbaa``.\n\n Each channel is represented by two **lowercase** hex digits ranging from\n ``00`` to ``ff``.\n \"\"\"\n return \"#%02x%02x%02x%02x\" % self\n\n @property\n def rgb(self) -> tuple[int, int, int]:\n \"\"\"Extracts the R, G and B channels of the color.\n\n Returns:\n A 3-tuple containing the red, green and blue channel values.\n \"\"\"\n return self[:3]\n\n @property\n def rgb_hex(self) -> str:\n \"\"\"Converts the color to its RGB hexadecimal representation.\n\n Returns:\n The RGB hex color string, starting with the ``#`` character i.e ``#rrggbb``.\n\n Each channel is represented by two **lowercase** hex digits ranging from\n ``00`` to ``ff``.\n \"\"\"\n return \"#%02x%02x%02x\" % self[:3]\n\n @classmethod\n def from_hex(cls, color: str) -> Self:\n \"\"\"Creates a new instance from a hexadecimal color string.\n\n Args:\n color: A **case-insensitive** RGB or RGBA hex color string, **optionally**\n starting with the ``#`` (pound) character i.e ``[#]rrggbb[aa]``.\n\n Returns:\n A new instance representing the given hex color string.\n\n Raises:\n ValueError: Invalid hex color string.\n\n NOTE:\n For an RGB hex color string, the value of A (the alpha channel) is\n taken to be 255.\n \"\"\"\n if not (match := _RGBA_HEX_RE.fullmatch(color)):\n raise ValueError(f\"Invalid hex color string (got: {color!r})\")\n\n return tuple.__new__(cls, [int(x, 16) for x in match.groups(\"ff\")])\n\n @classmethod\n def _new(cls, r: int, g: int, b: int, a: int = 255) -> Self:\n \"\"\"Alternate constructor for internal use only.\"\"\"\n return tuple.__new__(cls, (r, g, b, a))", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 4255}, "tests/test_top_level.py::41": {"resolved_imports": ["src/term_image/__init__.py", "src/term_image/utils.py", "src/term_image/exceptions.py", "src/term_image/geometry.py"], "used_names": ["AutoCellRatio", "TermImageError", "pytest", "reset_cell_size_ratio", "set_cell_ratio", "set_cell_size"], "enclosing_function": "test_unsupported", "extracted_code": "# Source: src/term_image/__init__.py\nclass AutoCellRatio(Enum):\n \"\"\":ref:`auto-cell-ratio` enumeration and support status.\n\n .. seealso:: :py:func:`set_cell_ratio`.\n \"\"\"\n\n FIXED = auto()\n \"\"\"Fixed cell ratio.\n\n :meta hide-value:\n \"\"\"\n\n DYNAMIC = auto()\n \"\"\"Dynamic cell ratio.\n\n :meta hide-value:\n \"\"\"\n\n is_supported: ClassVar[bool | None]\n \"\"\"Auto cell ratio support status. Can be\n\n :meta hide-value:\n\n - ``None`` -> support status not yet determined\n - ``True`` -> supported\n - ``False`` -> not supported\n\n Can be explicitly set when using auto cell ratio but want to avoid the support\n check in a situation where the support status is foreknown. Can help to avoid\n being wrongly detected as unsupported on a :ref:`queried `\n terminal that doesn't respond on time.\n\n For instance, when using multiprocessing, if the support status has been\n determined in the main process, this value can simply be passed on to and set\n within the child processes.\n \"\"\"\n\ndef set_cell_ratio(ratio: float | AutoCellRatio) -> None:\n \"\"\"Sets the global :term:`cell ratio`.\n\n Args:\n ratio: Can be one of the following values.\n\n * A positive :py:class:`float` value.\n * :py:attr:`AutoCellRatio.FIXED`, the ratio is immediately determined from\n the :term:`active terminal`.\n * :py:attr:`AutoCellRatio.DYNAMIC`, the ratio is determined from the\n :term:`active terminal` whenever :py:func:`get_cell_ratio` is called,\n though with some caching involved, such that the ratio is re-determined\n only if the terminal size changes.\n\n Raises:\n ValueError: *ratio* is a non-positive :py:class:`float`.\n term_image.exceptions.TermImageError: Auto cell ratio is not supported\n in the :term:`active terminal` or on the current platform.\n\n This value is taken into consideration when setting image sizes for **text-based**\n render styles, in order to preserve the aspect ratio of images drawn to the\n terminal.\n\n NOTE:\n Changing the cell ratio does not automatically affect any image that has a\n :term:`fixed size`. For a change in cell ratio to take effect, the image's\n size has to be re-set.\n\n IMPORTANT:\n See :ref:`auto-cell-ratio` for details about the auto modes.\n \"\"\"\n global _cell_ratio\n\n if isinstance(ratio, AutoCellRatio):\n if AutoCellRatio.is_supported is None:\n AutoCellRatio.is_supported = get_cell_size() is not None\n\n if not AutoCellRatio.is_supported:\n raise TermImageError(\n \"Auto cell ratio is not supported in the active terminal or on the \"\n \"current platform\"\n )\n elif ratio is AutoCellRatio.FIXED:\n # `(1, 2)` is a fallback in case the terminal doesn't respond in time\n _cell_ratio = truediv(*(get_cell_size() or (1, 2)))\n else:\n _cell_ratio = None\n else:\n if ratio <= 0.0:\n raise arg_value_error_range(\"ratio\", ratio)\n _cell_ratio = ratio\n\n\n# Source: src/term_image/exceptions.py\nclass TermImageError(Exception):\n \"\"\"Exception baseclass. Raised for generic errors.\"\"\"", "n_imports_parsed": 6, "n_files_resolved": 4, "n_chars_extracted": 3266}, "tests/widget/urwid/test_screen.py::199": {"resolved_imports": ["src/term_image/__init__.py", "src/term_image/_ctlseqs.py", "src/term_image/image/block.py", "src/term_image/image/iterm2.py", "src/term_image/image/kitty.py", "src/term_image/widget/_urwid.py"], "used_names": ["UrwidImage"], "enclosing_function": "test_disguise_state", "extracted_code": "# Source: src/term_image/widget/_urwid.py\nclass UrwidImage(urwid.Widget):\n \"\"\"Image widget (box/flow) for the urwid TUI framework.\n\n Args:\n image: The image to be rendered by the widget.\n format_spec: :ref:`Render format specifier `. Padding width and\n height are ignored.\n upscale: If ``True``, the image will be upscaled to fit maximally within the\n available size, if necessary, while still preserving the aspect ratio.\n Otherwise, the image is never upscaled.\n\n Raises:\n TypeError: An argument is of an inappropriate type.\n ValueError: An argument is of an appropriate type but has an\n unexpected/invalid value.\n term_image.exceptions.StyleError: Invalid style-specific format specifier.\n term_image.exceptions.UrwidImageError: Too many image widgets rendering images\n with the *kitty* render style.\n\n | Any ample space in the widget's render size is filled with spaces.\n | For animated images, the current frame (at render-time) is rendered.\n\n TIP:\n If *image* is of a :ref:`graphics-based ` render style and the\n widget is being used as or within a **flow** widget, with overlays or in any\n other case where the canvas will require vertical trimming, make sure to use a\n render method that splits images across lines such as the **LINES** render\n method for *kitty* and *iterm2* render styles.\n\n NOTE:\n * The `z-index` style-specific format spec field for\n :py:class:`~term_image.image.KittyImage` is ignored as this is used\n internally.\n * A **maximum** of ``2**32 - 2`` instances initialized with\n :py:class:`~term_image.image.KittyImage` instances may exist at the same time.\n\n IMPORTANT:\n This is defined if and only if the ``urwid`` package is available.\n \"\"\"\n\n _sizing = frozenset((urwid.BOX, urwid.FLOW))\n ignore_focus = True\n\n _ti_error_placeholder = None\n\n # For kitty images\n _ti_disguise_state = 0\n _ti_free_z_indexes = set()\n\n # Progresses thus: 1, -1, 2, -2, 3, ..., 2**31 - 1, -(2**31 - 1)\n # This sequence results in shorter image escape sequences compared to starting\n # from -(2**31)\n _ti_next_z_index = 1\n\n def __init__(\n self, image: BaseImage, format_spec: str = \"\", *, upscale: bool = False\n ) -> None:\n if not isinstance(image, BaseImage):\n raise arg_type_error(\"image\", image)\n\n if not isinstance(format_spec, str):\n raise arg_type_error(\"format_spec\", format_spec)\n *fmt, alpha, style_args = image._check_format_spec(format_spec)\n\n if not isinstance(upscale, bool):\n raise arg_type_error(\"upscale\", upscale)\n\n super().__init__()\n self._ti_image = image\n self._ti_h_align, _, self._ti_v_align, _ = fmt\n self._ti_alpha = alpha\n self._ti_style_args = style_args\n self._ti_sizing = Size.FIT if upscale else Size.AUTO\n\n if isinstance(image, TextImage):\n style_args[\"split_cells\"] = True\n elif isinstance(image, KittyImage):\n style_args[\"z_index\"] = self._ti_z_index = self._ti_get_z_index()\n\n # Since Konsole doesn't blend images placed at the same location and\n # z-index, unlike Kitty (and potentially others), `blend=True` is\n # better on Konsole as it reduces/eliminates flicker.\n if get_terminal_name_version()[0] != \"konsole\":\n # To clear directly overlapped images when urwid redraws a line without\n # a change in image position\n style_args[\"blend\"] = False\n\n def __del__(self) -> None:\n if hasattr(self, \"_ti_z_index\"):\n __class__._ti_free_z_indexes.add(self._ti_z_index)\n\n image = property(\n lambda self: self._ti_image,\n doc=\"\"\"\n The image rendered by the widget\n\n :type: BaseImage\n\n GET:\n Returns the image instance rendered by the widget.\n \"\"\",\n )\n\n def render(self, size: Tuple[int, int], focus: bool = False) -> urwid.Canvas:\n image = self._ti_image\n\n if len(size) == 2: # box\n image.set_size(self._ti_sizing, frame_size=size)\n elif len(size) == 1: # flow\n if self._ti_sizing is Size.FIT:\n image.set_size(size[0])\n else:\n fit_size = self._ti_image._valid_size(size[0])\n ori_size = self._ti_image._valid_size(Size.ORIGINAL)\n image._size = (\n ori_size\n if ori_size[0] <= fit_size[0] and ori_size[1] <= fit_size[1]\n else fit_size\n )\n size = (size[0], image._size[1])\n else: # fixed\n raise UrwidImageError(\"Not a fixed widget\")\n\n try:\n render = image._format_render(\n image._renderer(\n image._render_image, self._ti_alpha, **self._ti_style_args\n ),\n self._ti_h_align,\n size[0],\n self._ti_v_align,\n size[1],\n )\n except Exception:\n if type(self)._ti_error_placeholder is None:\n raise\n canv = type(self)._ti_error_placeholder.render(size, focus)\n else:\n canv = UrwidImageCanvas(render, size, image._size)\n\n return canv\n\n def rows(self, size: Tuple[int], focus: bool = False) -> int:\n fit_size = self._ti_image._valid_size(size[0])\n if self._ti_sizing is Size.FIT:\n n_rows = fit_size[1]\n else:\n ori_size = self._ti_image._valid_size(Size.ORIGINAL)\n n_rows = (\n ori_size[1]\n if ori_size[0] <= fit_size[0] and ori_size[1] <= fit_size[1]\n else fit_size[1]\n )\n\n return n_rows\n\n @classmethod\n def set_error_placeholder(cls, widget: Optional[urwid.Widget]) -> None:\n \"\"\"Sets the widget to be rendered in place of an image when rendering fails.\n\n Args:\n widget: The placeholder widget or ``None`` to remove the placeholder.\n\n Raises:\n TypeError: *widget* is not an urwid widget.\n\n If set, any exception raised during rendering is **suppressed** and the\n placeholder is rendered in place of the image.\n \"\"\"\n if not isinstance(widget, urwid.Widget):\n raise arg_type_error(\"widget\", widget)\n\n cls._ti_error_placeholder = widget\n\n @staticmethod\n def _ti_get_z_index() -> int:\n if __class__._ti_free_z_indexes:\n return __class__._ti_free_z_indexes.pop()\n\n z_index = __class__._ti_next_z_index\n if z_index == 2**31:\n raise UrwidImageError(\"Too many image widgets with the kitty render style\")\n __class__._ti_next_z_index = -z_index if z_index > 0 else -z_index + 1\n\n return z_index\n\n def _ti_change_disguise(self) -> None:\n \"\"\"See :py:meth`UrwidImageCanvas._ti_change_disguise`.\"\"\"\n self._ti_disguise_state = (self._ti_disguise_state + 1) % 3", "n_imports_parsed": 10, "n_files_resolved": 6, "n_chars_extracted": 7167}, "tests/test_image/test_block.py::34": {"resolved_imports": ["src/term_image/_ctlseqs.py", "src/term_image/image/block.py", "src/term_image/image/common.py"], "used_names": ["_ALPHA_THRESHOLD"], "enclosing_function": "test_size", "extracted_code": "# Source: src/term_image/image/common.py\n_ALPHA_THRESHOLD = 40 / 255", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 68}, "tests/test_top_level.py::49": {"resolved_imports": ["src/term_image/__init__.py", "src/term_image/utils.py", "src/term_image/exceptions.py", "src/term_image/geometry.py"], "used_names": ["AutoCellRatio", "Size", "get_cell_ratio", "pytest", "reset_cell_size_ratio", "set_cell_ratio", "set_cell_size", "truediv"], "enclosing_function": "test_fixed", "extracted_code": "# Source: src/term_image/__init__.py\nclass AutoCellRatio(Enum):\n \"\"\":ref:`auto-cell-ratio` enumeration and support status.\n\n .. seealso:: :py:func:`set_cell_ratio`.\n \"\"\"\n\n FIXED = auto()\n \"\"\"Fixed cell ratio.\n\n :meta hide-value:\n \"\"\"\n\n DYNAMIC = auto()\n \"\"\"Dynamic cell ratio.\n\n :meta hide-value:\n \"\"\"\n\n is_supported: ClassVar[bool | None]\n \"\"\"Auto cell ratio support status. Can be\n\n :meta hide-value:\n\n - ``None`` -> support status not yet determined\n - ``True`` -> supported\n - ``False`` -> not supported\n\n Can be explicitly set when using auto cell ratio but want to avoid the support\n check in a situation where the support status is foreknown. Can help to avoid\n being wrongly detected as unsupported on a :ref:`queried `\n terminal that doesn't respond on time.\n\n For instance, when using multiprocessing, if the support status has been\n determined in the main process, this value can simply be passed on to and set\n within the child processes.\n \"\"\"\n\ndef get_cell_ratio() -> float:\n \"\"\"Returns the global :term:`cell ratio`.\n\n .. seealso:: :py:func:`set_cell_ratio`.\n \"\"\"\n # `(1, 2)` is a fallback in case the terminal doesn't respond in time\n return _cell_ratio or truediv(*(get_cell_size() or (1, 2)))\n\ndef set_cell_ratio(ratio: float | AutoCellRatio) -> None:\n \"\"\"Sets the global :term:`cell ratio`.\n\n Args:\n ratio: Can be one of the following values.\n\n * A positive :py:class:`float` value.\n * :py:attr:`AutoCellRatio.FIXED`, the ratio is immediately determined from\n the :term:`active terminal`.\n * :py:attr:`AutoCellRatio.DYNAMIC`, the ratio is determined from the\n :term:`active terminal` whenever :py:func:`get_cell_ratio` is called,\n though with some caching involved, such that the ratio is re-determined\n only if the terminal size changes.\n\n Raises:\n ValueError: *ratio* is a non-positive :py:class:`float`.\n term_image.exceptions.TermImageError: Auto cell ratio is not supported\n in the :term:`active terminal` or on the current platform.\n\n This value is taken into consideration when setting image sizes for **text-based**\n render styles, in order to preserve the aspect ratio of images drawn to the\n terminal.\n\n NOTE:\n Changing the cell ratio does not automatically affect any image that has a\n :term:`fixed size`. For a change in cell ratio to take effect, the image's\n size has to be re-set.\n\n IMPORTANT:\n See :ref:`auto-cell-ratio` for details about the auto modes.\n \"\"\"\n global _cell_ratio\n\n if isinstance(ratio, AutoCellRatio):\n if AutoCellRatio.is_supported is None:\n AutoCellRatio.is_supported = get_cell_size() is not None\n\n if not AutoCellRatio.is_supported:\n raise TermImageError(\n \"Auto cell ratio is not supported in the active terminal or on the \"\n \"current platform\"\n )\n elif ratio is AutoCellRatio.FIXED:\n # `(1, 2)` is a fallback in case the terminal doesn't respond in time\n _cell_ratio = truediv(*(get_cell_size() or (1, 2)))\n else:\n _cell_ratio = None\n else:\n if ratio <= 0.0:\n raise arg_value_error_range(\"ratio\", ratio)\n _cell_ratio = ratio\n\n\n# Source: src/term_image/geometry.py\nclass Size(RawSize):\n \"\"\"The dimensions of a rectangular region.\n\n Raises:\n ValueError: Either dimension is non-positive.\n\n Same as :py:class:`RawSize`, except that both dimensions must be **positive**.\n\n IMPORTANT:\n In the case of multiple inheritance i.e if subclassing this class along with\n other classes, this class should appear last (i.e to the far right) in the\n base class list.\n \"\"\"\n\n __slots__ = ()\n\n def __new__(cls, width: int, height: int) -> Self:\n if width < 1:\n raise arg_value_error_range(\"width\", width)\n if height < 1:\n raise arg_value_error_range(\"height\", height)\n\n # Using `tuple` directly instead of `super()` for performance\n return tuple.__new__(cls, (width, height))", "n_imports_parsed": 6, "n_files_resolved": 4, "n_chars_extracted": 4235}, "tests/test_color.py::162": {"resolved_imports": ["src/term_image/color.py"], "used_names": ["Color", "pytest"], "enclosing_function": "test_equal_to_normally_constructed", "extracted_code": "# Source: src/term_image/color.py\nclass Color(_DummyColor):\n \"\"\"A color.\n\n Args:\n r: The red channel.\n g: The green channel.\n b: The blue channel.\n a: The alpha channel (opacity).\n\n Raises:\n ValueError: The value of a channel is not within the valid range.\n\n NOTE:\n The valid value range for all channels is 0 to 255, both inclusive.\n\n TIP:\n This class is a :py:class:`~typing.NamedTuple` of four fields.\n\n WARNING:\n In the case of multiple inheritance i.e if subclassing this class along with\n other classes, this class should appear last (i.e to the far right) in the\n base class list.\n \"\"\"\n\n __slots__ = ()\n\n # Overrides these descriptors in order to speed up attribute resolution and to\n # simplify auto documentation.\n r: int = _DummyColor.r\n r.__doc__ = \"\"\"The red channel\"\"\"\n\n g: int = _DummyColor.g\n g.__doc__ = \"\"\"The green channel\"\"\"\n\n b: int = _DummyColor.b\n b.__doc__ = \"\"\"The blue channel\"\"\"\n\n a: int = _DummyColor.a\n a.__doc__ = \"\"\"The alpha channel (opacity)\"\"\"\n\n def __new__(cls, r: int, g: int, b: int, a: int = 255) -> Self:\n # Only the 8 LSb may be set for any value within the range [0, 255].\n # `x & ~255` unsets the 8 LSb. Hence, if the result is non-zero (i.e any\n # of the bits above the lowest 8 is set), it implies `x` is out of range.\n #\n # Actually benchmarked *this* against the \"simpler\" logically-negated chained\n # comparison (i.e `0 <= x <= 255`) and *this* was significantly faster for all\n # cases i.e within, on the boundaries, and outside (on both sides).\n if (r | g | b | a) & ~255: # First test to see if *any* is out of range\n if r & ~255:\n raise arg_value_error_range(\"r\", r)\n if g & ~255:\n raise arg_value_error_range(\"g\", g)\n if b & ~255:\n raise arg_value_error_range(\"b\", b)\n # There's no point checking since at least one is out of range\n raise arg_value_error_range(\"a\", a)\n\n # Using `tuple` directly instead of `super()` for performance\n return tuple.__new__(cls, (r, g, b, a))\n\n @property\n def hex(self) -> str:\n \"\"\"Converts the color to its RGBA hexadecimal representation.\n\n Returns:\n The RGBA hex color string, starting with the ``#`` character i.e\n ``#rrggbbaa``.\n\n Each channel is represented by two **lowercase** hex digits ranging from\n ``00`` to ``ff``.\n \"\"\"\n return \"#%02x%02x%02x%02x\" % self\n\n @property\n def rgb(self) -> tuple[int, int, int]:\n \"\"\"Extracts the R, G and B channels of the color.\n\n Returns:\n A 3-tuple containing the red, green and blue channel values.\n \"\"\"\n return self[:3]\n\n @property\n def rgb_hex(self) -> str:\n \"\"\"Converts the color to its RGB hexadecimal representation.\n\n Returns:\n The RGB hex color string, starting with the ``#`` character i.e ``#rrggbb``.\n\n Each channel is represented by two **lowercase** hex digits ranging from\n ``00`` to ``ff``.\n \"\"\"\n return \"#%02x%02x%02x\" % self[:3]\n\n @classmethod\n def from_hex(cls, color: str) -> Self:\n \"\"\"Creates a new instance from a hexadecimal color string.\n\n Args:\n color: A **case-insensitive** RGB or RGBA hex color string, **optionally**\n starting with the ``#`` (pound) character i.e ``[#]rrggbb[aa]``.\n\n Returns:\n A new instance representing the given hex color string.\n\n Raises:\n ValueError: Invalid hex color string.\n\n NOTE:\n For an RGB hex color string, the value of A (the alpha channel) is\n taken to be 255.\n \"\"\"\n if not (match := _RGBA_HEX_RE.fullmatch(color)):\n raise ValueError(f\"Invalid hex color string (got: {color!r})\")\n\n return tuple.__new__(cls, [int(x, 16) for x in match.groups(\"ff\")])\n\n @classmethod\n def _new(cls, r: int, g: int, b: int, a: int = 255) -> Self:\n \"\"\"Alternate constructor for internal use only.\"\"\"\n return tuple.__new__(cls, (r, g, b, a))", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 4255}, "tests/test_image/test_block.py::87": {"resolved_imports": ["src/term_image/_ctlseqs.py", "src/term_image/image/block.py", "src/term_image/image/common.py"], "used_names": ["SGR_BG_DIRECT", "SGR_DEFAULT", "set_fg_bg_colors"], "enclosing_function": "test_background_colour", "extracted_code": "# Source: src/term_image/_ctlseqs.py\nSGR_BG_DIRECT = SGR % f\"48;2;{Pm(3)}\"\n\nSGR_DEFAULT = SGR % \"\"", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 98}, "tests/renderable/test_renderable.py::788": {"resolved_imports": ["src/term_image/_ctlseqs.py", "src/term_image/geometry.py", "src/term_image/padding.py", "src/term_image/renderable/_enum.py", "src/term_image/renderable/_exceptions.py", "src/term_image/renderable/_renderable.py", "src/term_image/renderable/_types.py"], "used_names": ["AlignedPadding"], "enclosing_function": "test_padding", "extracted_code": "# Source: src/term_image/padding.py\nclass AlignedPadding(Padding):\n \"\"\"Aligned :term:`render output` padding.\n\n Args:\n width: Minimum :term:`render width`.\n height: Minimum :term:`render height`.\n h_align: Horizontal alignment.\n v_align: Vertical alignment.\n\n If *width* or *height* is:\n\n * positive, it is **absolute** and used as-is.\n * non-positive, it is **relative** to the corresponding terminal dimension\n (**at the point of resolution**) and equivalent to the absolute dimension\n ``max(terminal_dimension + relative_dimension, 1)``.\n\n The *padded render dimension* (i.e the dimension of a :term:`render output` after\n it's padded) on each axis is given by::\n\n padded_dimension = max(render_dimension, absolute_minimum_dimension)\n\n In words... If the **absolute** *minimum render dimension* on an axis is less than\n or equal to the corresponding *render dimension*, there is no padding on that axis\n and the *padded render dimension* on that axis is equal to the *render dimension*.\n Otherwise, the render output will be padded along that axis and the *padded render\n dimension* on that axis is equal to the *minimum render dimension*.\n\n The amount of padding to each side depends on the alignment, defined by *h_align*\n and *v_align*.\n\n IMPORTANT:\n :py:class:`RelativePaddingDimensionError` is raised if any padding-related\n computation/operation (basically, calling any method other than\n :py:meth:`resolve`) is performed on an instance with **relative** *minimum\n render dimension(s)* i.e if :py:attr:`relative` is ``True``.\n\n NOTE:\n Any interface receiving an instance with **relative** dimension(s) should\n typically resolve it/them upon reception.\n\n TIP:\n * Instances are immutable and hashable.\n * Instances with equal fields compare equal.\n \"\"\"\n\n # Class Attributes =========================================================\n\n __slots__ = (\"width\", \"height\", \"h_align\", \"v_align\", \"relative\")\n\n # Instance Attributes ======================================================\n\n width: int\n \"\"\"Minimum :term:`render width`\"\"\"\n\n height: int\n \"\"\"Minimum :term:`render height`\"\"\"\n\n h_align: HAlign\n \"\"\"Horizontal alignment\"\"\"\n\n v_align: VAlign\n \"\"\"Vertical alignment\"\"\"\n\n fill: str\n\n relative: bool\n \"\"\"``True`` if either or both *minimum render dimension(s)* is/are relative i.e\n non-positive. Otherwise, ``False``.\n \"\"\"\n\n # Special Methods ==========================================================\n\n def __init__(\n self,\n width: int,\n height: int,\n h_align: HAlign = HAlign.CENTER,\n v_align: VAlign = VAlign.MIDDLE,\n fill: str = \" \",\n ):\n super().__init__(fill)\n\n _setattr = super().__setattr__\n _setattr(\"width\", width)\n _setattr(\"height\", height)\n _setattr(\"h_align\", h_align)\n _setattr(\"v_align\", v_align)\n _setattr(\"relative\", not width > 0 < height)\n\n def __repr__(self) -> str:\n return \"{}(width={}, height={}, h_align={}, v_align={}, fill={!r})\".format(\n type(self).__name__,\n self.width,\n self.height,\n self.h_align.name,\n self.v_align.name,\n self.fill,\n )\n\n # Properties ===============================================================\n\n @property\n def size(self) -> RawSize:\n \"\"\"Minimum :term:`render size`\n\n GET:\n Returns the *minimum render dimensions*.\n \"\"\"\n return _RawSize(self.width, self.height)\n\n # Public Methods ===========================================================\n\n @override\n def get_padded_size(self, render_size: Size) -> Size:\n \"\"\"Computes an expected padded :term:`render size`.\n\n See :py:meth:`Padding.get_padded_size`.\n\n Raises:\n RelativePaddingDimensionError: Relative *minimum render dimension(s)*.\n \"\"\"\n if self.relative:\n raise RelativePaddingDimensionError(\"Relative minimum render dimension(s)\")\n\n return _Size(max(self.width, render_size[0]), max(self.height, render_size[1]))\n\n def resolve(self, terminal_size: os.terminal_size) -> AlignedPadding:\n \"\"\"Resolves **relative** *minimum render dimensions*.\n\n Args:\n terminal_size: The terminal size against which to resolve relative\n dimensions.\n\n Returns:\n An instance with equivalent **absolute** dimensions.\n \"\"\"\n if not self.relative:\n return self\n\n width, height, *args, _ = astuple(self)\n terminal_width, terminal_height = terminal_size\n if width <= 0:\n width = max(terminal_width + width, 1)\n if height <= 0:\n height = max(terminal_height + height, 1)\n\n return type(self)(width, height, *args)\n\n # Extension methods ========================================================\n\n @override\n def _get_exact_dimensions_(self, render_size: Size) -> tuple[int, int, int, int]:\n if self.relative:\n raise RelativePaddingDimensionError(\"Relative minimum render dimension(s)\")\n\n width, height, h_align, v_align = astuple(self)[:4]\n render_width, render_height = render_size\n\n if width > render_width:\n padding_width = width - render_width\n numerator, denominator = _ALIGN_RATIOS[h_align]\n left = padding_width * numerator // denominator\n right = padding_width - left\n else:\n left = right = 0\n\n if height > render_height:\n padding_height = height - render_height\n numerator, denominator = _ALIGN_RATIOS[v_align]\n top = padding_height * numerator // denominator\n bottom = padding_height - top\n else:\n top = bottom = 0\n\n return left, top, right, bottom", "n_imports_parsed": 14, "n_files_resolved": 7, "n_chars_extracted": 5973}, "tests/test_image/test_block.py::33": {"resolved_imports": ["src/term_image/_ctlseqs.py", "src/term_image/image/block.py", "src/term_image/image/common.py"], "used_names": ["_ALPHA_THRESHOLD"], "enclosing_function": "test_size", "extracted_code": "# Source: src/term_image/image/common.py\n_ALPHA_THRESHOLD = 40 / 255", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 68}, "tests/renderable/test_types.py::146": {"resolved_imports": ["src/term_image/geometry.py", "src/term_image/renderable/_renderable.py", "src/term_image/renderable/_types.py"], "used_names": [], "enclosing_function": "test_no_fields", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/test_iterator.py::91": {"resolved_imports": ["src/term_image/_ctlseqs.py", "src/term_image/exceptions.py", "src/term_image/image/block.py", "src/term_image/image/common.py"], "used_names": ["ImageIterator"], "enclosing_function": "test_image_seek_position_unchanged", "extracted_code": "# Source: src/term_image/image/common.py\nclass ImageIterator:\n \"\"\"Efficiently iterate over :term:`rendered` frames of an :term:`animated` image\n\n Args:\n image: Animated image.\n repeat: The number of times to go over the entire image. A negative value\n implies infinite repetition.\n format_spec: The :ref:`format specifier ` for the rendered\n frames (default: auto).\n cached: Determines if the :term:`rendered` frames will be cached (for speed up\n of subsequent renders) or not. If it is\n\n * a boolean, caching is enabled if ``True``. Otherwise, caching is disabled.\n * a positive integer, caching is enabled only if the framecount of the image\n is less than or equal to the given number.\n\n Raises:\n TypeError: An argument is of an inappropriate type.\n ValueError: An argument is of an appropriate type but has an\n unexpected/invalid value.\n term_image.exceptions.StyleError: Invalid style-specific format specifier.\n\n * If *repeat* equals ``1``, caching is disabled.\n * The iterator has immediate response to changes in the image size.\n * If the image size is :term:`dynamic `, it's computed per frame.\n * The number of the last yielded frame is set as the image's seek position.\n * Directly adjusting the seek position of the image doesn't affect iteration.\n Use :py:meth:`ImageIterator.seek` instead.\n * After the iterator is exhausted, the underlying image is set to frame ``0``.\n \"\"\"\n\n def __init__(\n self,\n image: BaseImage,\n repeat: int = -1,\n format_spec: str = \"\",\n cached: Union[bool, int] = 100,\n ) -> None:\n if not isinstance(image, BaseImage):\n raise arg_type_error(\"image\", image)\n if not image._is_animated:\n raise ValueError(\"'image' is not animated\")\n\n if not isinstance(repeat, int):\n raise arg_type_error(\"repeat\", repeat)\n if not repeat:\n raise arg_value_error(\"repeat\", repeat)\n\n if not isinstance(format_spec, str):\n raise arg_type_error(\"format_spec\", format_spec)\n *fmt, alpha, style_args = image._check_format_spec(format_spec)\n\n if not isinstance(cached, int): # `bool` is a subclass of `int`\n raise arg_type_error(\"cached\", cached)\n if False is not cached <= 0:\n raise arg_value_error_range(\"cached\", cached)\n\n self._image = image\n self._repeat = repeat\n self._format = format_spec\n self._cached = repeat != 1 and (\n cached if isinstance(cached, bool) else image.n_frames <= cached\n )\n self._loop_no = None\n self._animator = image._renderer(\n self._animate, alpha, fmt, style_args, check_size=False\n )\n\n def __del__(self) -> None:\n self.close()\n\n def __iter__(self) -> ImageIterator:\n return self\n\n def __next__(self) -> str:\n try:\n return next(self._animator)\n except StopIteration:\n self.close()\n raise StopIteration(\n \"Iteration has reached the given repeat count\"\n ) from None\n except AttributeError as e:\n if str(e).endswith(\"'_animator'\"):\n raise StopIteration(\"Iterator exhausted or closed\") from None\n else:\n self.close()\n raise\n except Exception:\n self.close()\n raise\n\n def __repr__(self) -> str:\n return (\n \"{}(image={!r}, repeat={}, format_spec={!r}, cached={}, loop_no={})\".format(\n type(self).__name__,\n *self.__dict__.values(),\n )\n )\n\n loop_no = property(\n lambda self: self._loop_no,\n doc=\"\"\"Iteration repeat countdown\n\n :type: Optional[int]\n\n GET:\n Returns:\n\n * ``None``, if iteration hasn't started.\n * Otherwise, the current iteration repeat countdown value.\n\n Changes on the first iteration of each loop, except for infinite iteration\n where it's always ``-1``. When iteration has ended, the value is zero.\n \"\"\",\n )\n\n def close(self) -> None:\n \"\"\"Closes the iterator and releases resources used.\n\n Does not reset the frame number of the underlying image.\n\n NOTE:\n This method is automatically called when the iterator is exhausted or\n garbage-collected.\n \"\"\"\n try:\n self._animator.close()\n del self._animator\n self._image._close_image(self._img)\n del self._img\n except AttributeError:\n pass\n\n def seek(self, pos: int) -> None:\n \"\"\"Sets the frame number to be yielded on the next iteration without affecting\n the repeat count.\n\n Args:\n pos: Next frame number.\n\n Raises:\n TypeError: An argument is of an inappropriate type.\n ValueError: An argument is of an appropriate type but has an\n unexpected/invalid value.\n term_image.exceptions.TermImageError: Iteration has not yet started or the\n iterator is exhausted/closed.\n\n Frame numbers start from ``0`` (zero).\n \"\"\"\n if not isinstance(pos, int):\n raise arg_type_error(\"pos\", pos)\n if not 0 <= pos < self._image.n_frames:\n raise arg_value_error_range(\"pos\", pos, f\"n_frames={self._image.n_frames}\")\n\n try:\n self._animator.send(pos)\n except TypeError:\n raise TermImageError(\"Iteration has not yet started\") from None\n except AttributeError:\n raise TermImageError(\"Iterator exhausted or closed\") from None\n\n def _animate(\n self,\n img: PIL.Image.Image,\n alpha: Union[None, float, str],\n fmt: Tuple[Union[None, str, int]],\n style_args: Dict[str, Any],\n ) -> Generator[str, int, None]:\n \"\"\"Returns a generator that yields rendered and formatted frames of the\n underlying image.\n \"\"\"\n self._img = img # For cleanup\n image = self._image\n cached = self._cached\n self._loop_no = repeat = self._repeat\n if cached:\n cache = [(None,) * 2] * image.n_frames\n\n sent = None\n n = 0\n while repeat:\n if sent is None:\n image._seek_position = n\n try:\n frame = image._format_render(\n image._render_image(img, alpha, frame=True, **style_args), *fmt\n )\n except EOFError:\n image._seek_position = n = 0\n if repeat > 0: # Avoid infinitely large negative numbers\n self._loop_no = repeat = repeat - 1\n if cached:\n break\n continue\n else:\n if cached:\n cache[n] = (frame, hash(image.rendered_size))\n\n sent = yield frame\n n = n + 1 if sent is None else sent - 1\n\n if cached:\n n_frames = len(cache)\n while repeat:\n while n < n_frames:\n if sent is None:\n image._seek_position = n\n frame, size_hash = cache[n]\n if hash(image.rendered_size) != size_hash:\n frame = image._format_render(\n image._render_image(img, alpha, frame=True, **style_args),\n *fmt,\n )\n cache[n] = (frame, hash(image.rendered_size))\n\n sent = yield frame\n n = n + 1 if sent is None else sent - 1\n\n image._seek_position = n = 0\n if repeat > 0: # Avoid infinitely large negative numbers\n self._loop_no = repeat = repeat - 1\n\n # For consistency in behaviour\n if img is image._source:\n img.seek(0)", "n_imports_parsed": 7, "n_files_resolved": 4, "n_chars_extracted": 8102}, "tests/test_geometry.py::41": {"resolved_imports": ["src/term_image/geometry.py"], "used_names": ["Size", "pytest"], "enclosing_function": "test_positive_dimensions_only", "extracted_code": "# Source: src/term_image/geometry.py\nclass Size(RawSize):\n \"\"\"The dimensions of a rectangular region.\n\n Raises:\n ValueError: Either dimension is non-positive.\n\n Same as :py:class:`RawSize`, except that both dimensions must be **positive**.\n\n IMPORTANT:\n In the case of multiple inheritance i.e if subclassing this class along with\n other classes, this class should appear last (i.e to the far right) in the\n base class list.\n \"\"\"\n\n __slots__ = ()\n\n def __new__(cls, width: int, height: int) -> Self:\n if width < 1:\n raise arg_value_error_range(\"width\", width)\n if height < 1:\n raise arg_value_error_range(\"height\", height)\n\n # Using `tuple` directly instead of `super()` for performance\n return tuple.__new__(cls, (width, height))", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 829}, "tests/renderable/test_types.py::77": {"resolved_imports": ["src/term_image/geometry.py", "src/term_image/renderable/_renderable.py", "src/term_image/renderable/_types.py"], "used_names": ["Frame", "Size", "pytest"], "enclosing_function": "test_size", "extracted_code": "# Source: src/term_image/geometry.py\nclass Size(RawSize):\n \"\"\"The dimensions of a rectangular region.\n\n Raises:\n ValueError: Either dimension is non-positive.\n\n Same as :py:class:`RawSize`, except that both dimensions must be **positive**.\n\n IMPORTANT:\n In the case of multiple inheritance i.e if subclassing this class along with\n other classes, this class should appear last (i.e to the far right) in the\n base class list.\n \"\"\"\n\n __slots__ = ()\n\n def __new__(cls, width: int, height: int) -> Self:\n if width < 1:\n raise arg_value_error_range(\"width\", width)\n if height < 1:\n raise arg_value_error_range(\"height\", height)\n\n # Using `tuple` directly instead of `super()` for performance\n return tuple.__new__(cls, (width, height))\n\n\n# Source: src/term_image/renderable/_types.py\nclass Frame(NamedTuple):\n \"\"\"A rendered frame.\n\n TIP:\n - Instances are immutable and hashable.\n - Instances with equal fields compare equal.\n\n WARNING:\n Even though this class inherits from :py:class:`tuple`, the class and its\n instances should not be used as such, because:\n\n * this is an implementation detail,\n * the number or order of fields may change.\n\n Any change to this aspect of the interface may happen without notice and will\n not be considered a breaking change.\n \"\"\"\n\n number: int\n \"\"\"Frame number\n\n The number of the rendered frame (a non-negative integer), if the frame was\n rendered by a renderable with *definite* frame count. Otherwise, the value range\n and meaning of this field is unspecified.\n \"\"\"\n\n duration: int\n \"\"\"Frame duration (in **milliseconds**)\n\n The duration of the rendered frame (a non-negative integer), if the frame was\n rendered by an **animated** renderable. Otherwise, the value range and meaning\n of this field is unspecified.\n\n HINT:\n For animated renderables, a zero value indicates that the next frame should\n be displayed immediately after (without any delay), except stated otherwise.\n \"\"\"\n\n render_size: geometry.Size\n \"\"\"Frame :term:`render size`\"\"\"\n\n render_output: str\n \"\"\"Frame :term:`render output`\"\"\"\n\n def __str__(self) -> str:\n \"\"\"Returns the frame :term:`render output`.\n\n Returns:\n The frame render output, :py:attr:`render_output`.\n \"\"\"\n return self.render_output", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 2474}, "tests/test_image/common.py::197": {"resolved_imports": ["src/term_image/__init__.py", "src/term_image/_ctlseqs.py", "src/term_image/exceptions.py", "src/term_image/image/common.py", "src/term_image/utils.py"], "used_names": ["pytest"], "enclosing_function": "test_set_render_method_All", "extracted_code": "", "n_imports_parsed": 11, "n_files_resolved": 5, "n_chars_extracted": 0}, "tests/widget/urwid/test_screen.py::365": {"resolved_imports": ["src/term_image/__init__.py", "src/term_image/_ctlseqs.py", "src/term_image/image/block.py", "src/term_image/image/iterm2.py", "src/term_image/image/kitty.py", "src/term_image/widget/_urwid.py"], "used_names": ["get_terminal_name_version", "set_terminal_name_version"], "enclosing_function": "test_scroll_listboxes", "extracted_code": "", "n_imports_parsed": 10, "n_files_resolved": 6, "n_chars_extracted": 0}, "tests/test_color.py::156": {"resolved_imports": ["src/term_image/color.py"], "used_names": ["Color"], "enclosing_function": "test_instance_type", "extracted_code": "# Source: src/term_image/color.py\nclass Color(_DummyColor):\n \"\"\"A color.\n\n Args:\n r: The red channel.\n g: The green channel.\n b: The blue channel.\n a: The alpha channel (opacity).\n\n Raises:\n ValueError: The value of a channel is not within the valid range.\n\n NOTE:\n The valid value range for all channels is 0 to 255, both inclusive.\n\n TIP:\n This class is a :py:class:`~typing.NamedTuple` of four fields.\n\n WARNING:\n In the case of multiple inheritance i.e if subclassing this class along with\n other classes, this class should appear last (i.e to the far right) in the\n base class list.\n \"\"\"\n\n __slots__ = ()\n\n # Overrides these descriptors in order to speed up attribute resolution and to\n # simplify auto documentation.\n r: int = _DummyColor.r\n r.__doc__ = \"\"\"The red channel\"\"\"\n\n g: int = _DummyColor.g\n g.__doc__ = \"\"\"The green channel\"\"\"\n\n b: int = _DummyColor.b\n b.__doc__ = \"\"\"The blue channel\"\"\"\n\n a: int = _DummyColor.a\n a.__doc__ = \"\"\"The alpha channel (opacity)\"\"\"\n\n def __new__(cls, r: int, g: int, b: int, a: int = 255) -> Self:\n # Only the 8 LSb may be set for any value within the range [0, 255].\n # `x & ~255` unsets the 8 LSb. Hence, if the result is non-zero (i.e any\n # of the bits above the lowest 8 is set), it implies `x` is out of range.\n #\n # Actually benchmarked *this* against the \"simpler\" logically-negated chained\n # comparison (i.e `0 <= x <= 255`) and *this* was significantly faster for all\n # cases i.e within, on the boundaries, and outside (on both sides).\n if (r | g | b | a) & ~255: # First test to see if *any* is out of range\n if r & ~255:\n raise arg_value_error_range(\"r\", r)\n if g & ~255:\n raise arg_value_error_range(\"g\", g)\n if b & ~255:\n raise arg_value_error_range(\"b\", b)\n # There's no point checking since at least one is out of range\n raise arg_value_error_range(\"a\", a)\n\n # Using `tuple` directly instead of `super()` for performance\n return tuple.__new__(cls, (r, g, b, a))\n\n @property\n def hex(self) -> str:\n \"\"\"Converts the color to its RGBA hexadecimal representation.\n\n Returns:\n The RGBA hex color string, starting with the ``#`` character i.e\n ``#rrggbbaa``.\n\n Each channel is represented by two **lowercase** hex digits ranging from\n ``00`` to ``ff``.\n \"\"\"\n return \"#%02x%02x%02x%02x\" % self\n\n @property\n def rgb(self) -> tuple[int, int, int]:\n \"\"\"Extracts the R, G and B channels of the color.\n\n Returns:\n A 3-tuple containing the red, green and blue channel values.\n \"\"\"\n return self[:3]\n\n @property\n def rgb_hex(self) -> str:\n \"\"\"Converts the color to its RGB hexadecimal representation.\n\n Returns:\n The RGB hex color string, starting with the ``#`` character i.e ``#rrggbb``.\n\n Each channel is represented by two **lowercase** hex digits ranging from\n ``00`` to ``ff``.\n \"\"\"\n return \"#%02x%02x%02x\" % self[:3]\n\n @classmethod\n def from_hex(cls, color: str) -> Self:\n \"\"\"Creates a new instance from a hexadecimal color string.\n\n Args:\n color: A **case-insensitive** RGB or RGBA hex color string, **optionally**\n starting with the ``#`` (pound) character i.e ``[#]rrggbb[aa]``.\n\n Returns:\n A new instance representing the given hex color string.\n\n Raises:\n ValueError: Invalid hex color string.\n\n NOTE:\n For an RGB hex color string, the value of A (the alpha channel) is\n taken to be 255.\n \"\"\"\n if not (match := _RGBA_HEX_RE.fullmatch(color)):\n raise ValueError(f\"Invalid hex color string (got: {color!r})\")\n\n return tuple.__new__(cls, [int(x, 16) for x in match.groups(\"ff\")])\n\n @classmethod\n def _new(cls, r: int, g: int, b: int, a: int = 255) -> Self:\n \"\"\"Alternate constructor for internal use only.\"\"\"\n return tuple.__new__(cls, (r, g, b, a))", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 4255}, "tests/renderable/test_types.py::1483": {"resolved_imports": ["src/term_image/geometry.py", "src/term_image/renderable/_renderable.py", "src/term_image/renderable/_types.py"], "used_names": ["RenderData"], "enclosing_function": "test_finalized", "extracted_code": "# Source: src/term_image/renderable/_types.py\nclass RenderData(RenderArgsData):\n \"\"\"Render data.\n\n Args:\n render_cls: A :term:`render class`.\n\n An instance of this class is basically a container of render data namespaces\n (instances of :py:class:`~term_image.renderable.DataNamespace`); one for each\n :term:`render class`, which has render data, in the Method Resolution Order\n of its associated [#rd-ass]_ render class.\n\n NOTE:\n * Instances are immutable but the constituent namespaces are mutable.\n * Instances and their contents shouldn't be copied by any means because\n finalizing an instance may invalidate all other copies.\n * Instances should always be explicitly finalized as soon as they're no longer\n needed.\n\n .. seealso::\n\n :py:attr:`~term_image.renderable.Renderable._Data_`\n Render class-specific render data.\n \"\"\"\n\n # Class Attributes =========================================================\n\n __slots__ = (\"finalized\",)\n\n # Instance Attributes ======================================================\n\n finalized: bool\n \"\"\"Finalization status\"\"\"\n\n render_cls: type[Renderable]\n \"\"\"The associated :term:`render class`\"\"\"\n\n _namespaces: MappingProxyType[type[Renderable], DataNamespace]\n\n # Special Methods ==========================================================\n\n def __init__(self, render_cls: type[Renderable]) -> None:\n super().__init__(\n render_cls,\n {cls: data_cls() for cls, data_cls in render_cls._RENDER_DATA_MRO.items()},\n )\n self.finalized = False\n\n def __del__(self) -> None:\n try:\n self.finalize()\n except AttributeError: # Unsuccessful initialization\n pass\n\n def __getitem__(self, render_cls: type[Renderable]) -> Any:\n \"\"\"Returns a constituent namespace.\n\n Args:\n render_cls: A :term:`render class` of which :py:attr:`render_cls` is a\n subclass (which may be :py:attr:`render_cls` itself) and which has\n render data.\n\n Returns:\n The constituent namespace associated with *render_cls*.\n\n Raises:\n TypeError: *render_cls* is not a render class.\n ValueError: :py:attr:`render_cls` is not a subclass of *render_cls*.\n NoDataNamespaceError: *render_cls* has no render data.\n\n NOTE:\n The return type hint is :py:class:`~typing.Any` only for compatibility\n with static type checking, as this aspect of the interface seems too\n dynamic to be correctly expressed with the exisiting type system.\n\n Regardless, the return value is guaranteed to always be an instance\n of a render data namespace class associated with *render_cls*.\n For instance, the following would always be valid for\n :py:class:`~term_image.renderable.Renderable`::\n\n renderable_data: RenderableData = render_data[Renderable]\n\n and similar idioms are encouraged to be used for other render classes.\n \"\"\"\n try:\n return self._namespaces[render_cls]\n except TypeError:\n raise arg_type_error(\"render_cls\", render_cls) from None\n except KeyError:\n if not isinstance(render_cls, RenderableMeta):\n raise arg_type_error(\"render_cls\", render_cls) from None\n\n if issubclass(self.render_cls, render_cls):\n raise NoDataNamespaceError(\n f\"{render_cls.__name__!r} has no render data\"\n ) from None\n\n raise ValueError(\n f\"{self.render_cls.__name__!r} is not a subclass of \"\n f\"{render_cls.__name__!r}\"\n ) from None\n\n def __iter__(self) -> Iterator[DataNamespace]:\n \"\"\"Returns an iterator that yields the constituent namespaces.\n\n Returns:\n An iterator that yields the constituent namespaces.\n\n WARNING:\n The number and order of namespaces is guaranteed to be the same across all\n instances associated [#rd-ass]_ with the same :term:`render class` but\n beyond this, should not be relied upon as the details (such as the\n specific number or order) may change without notice.\n\n The order is an implementation detail of the Renderable API and the number\n should be considered alike with respect to the associated render class.\n \"\"\"\n return iter(self._namespaces.values())\n\n def __repr__(self) -> str:\n return \"\".join(\n (\n f\"<{type(self).__name__}({self.render_cls.__name__})\",\n \": \" if self._namespaces else \"\",\n \", \".join(map(repr, self._namespaces.values())),\n \">\",\n )\n )\n\n # Public Methods ===========================================================\n\n def finalize(self) -> None:\n \"\"\"Finalizes the render data.\n\n Calls :py:meth:`~term_image.renderable.Renderable._finalize_render_data_`\n of :py:attr:`render_cls`.\n\n NOTE:\n This method is safe for multiple invocations on the same instance.\n \"\"\"\n if not self.finalized:\n try:\n self.render_cls._finalize_render_data_(self)\n finally:\n self.finalized = True", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 5410}, "tests/test_image/common.py::286": {"resolved_imports": ["src/term_image/__init__.py", "src/term_image/_ctlseqs.py", "src/term_image/exceptions.py", "src/term_image/image/common.py", "src/term_image/utils.py"], "used_names": ["Size"], "enclosing_function": "test_fit_none_default", "extracted_code": "# Source: src/term_image/image/common.py\nclass Size(Enum):\n \"\"\"Enumeration for :term:`automatic sizing`.\"\"\"\n\n #: Equivalent to :py:attr:`ORIGINAL` if it will fit into the\n #: :term:`frame size`, else :py:attr:`FIT`.\n #:\n #: :meta hide-value:\n AUTO = Hidden()\n\n #: The image size is set to fit optimally **within** the :term:`frame size`.\n #:\n #: :meta hide-value:\n FIT = Hidden()\n\n #: The size is set such that the width is exactly the :term:`frame width`,\n #: regardless of the :term:`cell ratio`.\n #:\n #: :meta hide-value:\n FIT_TO_WIDTH = Hidden()\n\n #: The image size is set such that the image is rendered with as many pixels as the\n #: the original image consists of.\n #:\n #: :meta hide-value:\n ORIGINAL = Hidden()", "n_imports_parsed": 11, "n_files_resolved": 5, "n_chars_extracted": 778}, "tests/test_geometry.py::20": {"resolved_imports": ["src/term_image/geometry.py"], "used_names": ["RawSize"], "enclosing_function": "test_is_tuple", "extracted_code": "# Source: src/term_image/geometry.py\nclass RawSize(NamedTuple):\n \"\"\"The dimensions of a rectangular region.\n\n Args:\n width: The horizontal dimension\n height: The vertical dimension\n\n NOTE:\n * A dimension may be non-positive but the validity and meaning would be\n determined by the receiving interface.\n * This is a subclass of :py:class:`tuple`. Hence, instances can be used anyway\n and anywhere tuples can.\n \"\"\"\n\n width: int\n height: int\n\n @classmethod\n def _new(cls, width: int, height: int) -> Self:\n \"\"\"Alternate constructor for internal use only.\"\"\"\n return tuple.__new__(cls, (width, height))", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 682}, "tests/widget/urwid/test_screen.py::285": {"resolved_imports": ["src/term_image/__init__.py", "src/term_image/_ctlseqs.py", "src/term_image/image/block.py", "src/term_image/image/iterm2.py", "src/term_image/image/kitty.py", "src/term_image/widget/_urwid.py"], "used_names": ["get_terminal_name_version", "set_terminal_name_version"], "enclosing_function": "test_move_top_widget", "extracted_code": "", "n_imports_parsed": 10, "n_files_resolved": 6, "n_chars_extracted": 0}, "tests/renderable/test_types.py::356": {"resolved_imports": ["src/term_image/geometry.py", "src/term_image/renderable/_renderable.py", "src/term_image/renderable/_types.py"], "used_names": ["RenderArgs"], "enclosing_function": "test_render_cls", "extracted_code": "# Source: src/term_image/renderable/_types.py\nclass RenderArgs(RenderArgsData):\n \"\"\"RenderArgs(render_cls, /, *namespaces)\n RenderArgs(render_cls, init_render_args, /, *namespaces)\n\n Render arguments.\n\n Args:\n render_cls: A :term:`render class`.\n init_render_args (RenderArgs | None): A set of render arguments.\n If not ``None``,\n\n * it must be compatible [#ra-com]_ with *render_cls*,\n * it'll be used to initialize the render arguments.\n\n namespaces: Render argument namespaces compatible [#an-com]_ with *render_cls*.\n\n .. note:: If multiple namespaces associated with the same :term:`render\n class` are given, the last of them takes precedence.\n\n Raises:\n IncompatibleRenderArgsError: *init_render_args* is incompatible [#ra-com]_ with\n *render_cls*.\n IncompatibleArgsNamespaceError: Incompatible [#an-com]_ render argument\n namespace.\n\n A set of render arguments (an instance of this class) is basically a container of\n render argument namespaces (instances of\n :py:class:`~term_image.renderable.ArgsNamespace`); one for\n each :term:`render class`, which has render arguments, in the Method Resolution\n Order of its associated [#ra-ass]_ render class.\n\n The namespace for each render class is derived from the following sources, in\n [descending] order of precedence:\n\n * *namespaces*\n * *init_render_args*\n * default render argument namespaces\n\n NOTE:\n Instances are immutable but updated copies can be created via :py:meth:`update`.\n\n .. seealso::\n\n :py:attr:`~term_image.renderable.Renderable.Args`\n Render class-specific render arguments.\n\n .. Completed in /docs/source/api/renderable.rst\n \"\"\"\n\n # Class Attributes =========================================================\n\n __slots__ = ()\n\n _interned: ClassVar[dict[type[Renderable], Self]] = {}\n _namespaces: MappingProxyType[type[Renderable], ArgsNamespace]\n\n # Instance Attributes ======================================================\n\n render_cls: type[Renderable]\n \"\"\"The associated :term:`render class`\"\"\"\n\n # Special Methods ==========================================================\n\n def __new__(\n cls,\n render_cls: type[Renderable],\n init_or_namespace: RenderArgs | ArgsNamespace | None = None,\n *namespaces: ArgsNamespace,\n ) -> Self:\n if init_or_namespace is None:\n init_render_args = None\n elif isinstance(init_or_namespace, RenderArgs):\n init_render_args = init_or_namespace\n else:\n init_render_args = None\n namespaces = (init_or_namespace, *namespaces)\n\n if init_render_args and not issubclass(render_cls, init_render_args.render_cls):\n raise IncompatibleRenderArgsError(\n f\"'init_render_args' (associated with \"\n f\"{init_render_args.render_cls.__name__!r}) is incompatible with \"\n f\"{render_cls.__name__!r} \"\n )\n\n if not namespaces:\n # has default namespaces only\n if (\n not init_render_args\n or init_render_args is BASE_RENDER_ARGS\n or cls._interned.get(init_render_args.render_cls) is init_render_args\n ):\n try:\n return cls._interned[render_cls]\n except KeyError:\n pass\n\n if (\n init_render_args\n and type(init_render_args) is cls\n and init_render_args.render_cls is render_cls\n ):\n return init_render_args\n\n return super().__new__(cls)\n\n def __init__(\n self,\n render_cls: type[Renderable],\n init_or_namespace: RenderArgs | ArgsNamespace | None = None,\n *namespaces: ArgsNamespace,\n ) -> None:\n if init_or_namespace is None:\n init_render_args = None\n elif isinstance(init_or_namespace, RenderArgs):\n init_render_args = init_or_namespace\n else:\n init_render_args = None\n namespaces = (init_or_namespace, *namespaces)\n\n # has default namespaces only\n if not namespaces and (\n not init_render_args\n or init_render_args is BASE_RENDER_ARGS\n or (\n type(self)._interned.get(init_render_args.render_cls)\n is init_render_args\n )\n ):\n if render_cls in type(self)._interned: # has been initialized\n return\n intern = True\n else:\n intern = False\n\n if init_render_args is self:\n return\n\n namespaces_dict = render_cls._ALL_DEFAULT_ARGS.copy()\n\n # if `init_render_args` is non-default\n if init_render_args and BASE_RENDER_ARGS is not init_render_args is not (\n type(self)._interned.get(init_render_args.render_cls)\n ):\n namespaces_dict.update(init_render_args._namespaces)\n\n for index, namespace in enumerate(namespaces):\n if namespace._RENDER_CLS not in namespaces_dict:\n raise IncompatibleArgsNamespaceError(\n f\"'namespaces[{index}]' (associated with \"\n f\"{namespace._RENDER_CLS.__name__!r}) is incompatible with \"\n f\"{render_cls.__name__!r} \"\n )\n namespaces_dict[namespace._RENDER_CLS] = namespace\n\n super().__init__(render_cls, namespaces_dict)\n\n if intern:\n type(self)._interned[render_cls] = self\n\n def __init_subclass__(cls, **kwargs: Any) -> None:\n cls._interned = {}\n super().__init_subclass__(**kwargs)\n\n def __contains__(self, namespace: ArgsNamespace) -> bool:\n \"\"\"Checks if a render argument namespace is contained in this set of render\n arguments.\n\n Args:\n namespace: A render argument namespace.\n\n Returns:\n ``True`` if the given namespace is equal to any of the namespaces\n contained in this set of render arguments. Otherwise, ``False``.\n \"\"\"\n return None is not self._namespaces.get(namespace._RENDER_CLS) == namespace\n\n def __eq__(self, other: object) -> bool:\n \"\"\"Compares this set of render arguments with another.\n\n Args:\n other: Another set of render arguments.\n\n Returns:\n ``True`` if both are associated with the same :term:`render class`\n and have equal argument values. Otherwise, ``False``.\n \"\"\"\n if isinstance(other, RenderArgs):\n return (\n self is other\n or self.render_cls is other.render_cls\n and self._namespaces == other._namespaces\n )\n\n return NotImplemented\n\n def __getitem__(self, render_cls: type[Renderable]) -> Any:\n \"\"\"Returns a constituent namespace.\n\n Args:\n render_cls: A :term:`render class` of which :py:attr:`render_cls` is a\n subclass (which may be :py:attr:`render_cls` itself) and which has\n render arguments.\n\n Returns:\n The constituent namespace associated with *render_cls*.\n\n Raises:\n TypeError: *render_cls* is not a render class.\n ValueError: :py:attr:`render_cls` is not a subclass of *render_cls*.\n NoArgsNamespaceError: *render_cls* has no render arguments.\n\n NOTE:\n The return type hint is :py:class:`~typing.Any` only for compatibility\n with static type checking, as this aspect of the interface seems too\n dynamic to be correctly expressed with the exisiting type system.\n\n Regardless, the return value is guaranteed to always be an instance\n of a render argument namespace class associated with *render_cls*.\n For instance, the following would always be valid for\n :py:class:`~term_image.renderable.Renderable`::\n\n renderable_args: RenderableArgs = render_args[Renderable]\n\n and similar idioms are encouraged to be used for other render classes.\n \"\"\"\n try:\n return self._namespaces[render_cls]\n except TypeError:\n raise arg_type_error(\"render_cls\", render_cls) from None\n except KeyError:\n if not isinstance(render_cls, RenderableMeta):\n raise arg_type_error(\"render_cls\", render_cls) from None\n\n if issubclass(self.render_cls, render_cls):\n raise NoArgsNamespaceError(\n f\"{render_cls.__name__!r} has no render arguments\"\n ) from None\n\n raise ValueError(\n f\"{self.render_cls.__name__!r} is not a subclass of \"\n f\"{render_cls.__name__!r}\"\n ) from None\n\n def __hash__(self) -> int:\n \"\"\"Computes the hash of the render arguments.\n\n Returns:\n The computed hash.\n\n IMPORTANT:\n Like tuples, an instance is hashable if and only if the constituent\n namespaces are hashable.\n \"\"\"\n # Namespaces are always in the same order, wrt their respective associated\n # render classes, for all instances associated with the same render class.\n return hash((self.render_cls, tuple(self._namespaces.values())))\n\n def __iter__(self) -> Iterator[ArgsNamespace]:\n \"\"\"Returns an iterator that yields the constituent namespaces.\n\n Returns:\n An iterator that yields the constituent namespaces.\n\n WARNING:\n The number and order of namespaces is guaranteed to be the same across all\n instances associated [#ra-ass]_ with the same :term:`render class` but\n beyond this, should not be relied upon as the details (such as the\n specific number or order) may change without notice.\n\n The order is an implementation detail of the Renderable API and the number\n should be considered alike with respect to the associated render class.\n \"\"\"\n return iter(self._namespaces.values())\n\n def __repr__(self) -> str:\n return \"\".join(\n (\n f\"{type(self).__name__}({self.render_cls.__name__}\",\n \", \" if self._namespaces else \"\",\n \", \".join(map(repr, self._namespaces.values())),\n \")\",\n )\n )\n\n # Public Methods ===========================================================\n\n def convert(self, render_cls: type[Renderable]) -> RenderArgs:\n \"\"\"Converts the set of render arguments to one for a related render class.\n\n Args:\n render_cls: A :term:`render class` of which :py:attr:`render_cls` is a\n parent or child (which may be :py:attr:`render_cls` itself).\n\n Returns:\n A set of render arguments associated [#ra-ass]_ with *render_cls* and\n initialized with all constituent namespaces (of this set of render\n arguments, *self*) that are compatible [#an-com]_ with *render_cls*.\n\n Raises:\n ValueError: *render_cls* is not a parent or child of :py:attr:`render_cls`.\n \"\"\"\n if render_cls is self.render_cls:\n return self\n\n if issubclass(render_cls, self.render_cls):\n return RenderArgs(render_cls, self)\n\n if issubclass(self.render_cls, render_cls):\n render_cls_args_mro = render_cls._ALL_DEFAULT_ARGS\n return RenderArgs(\n render_cls,\n *[\n namespace\n for cls, namespace in self._namespaces.items()\n if cls in render_cls_args_mro\n ],\n )\n\n raise ValueError(\n f\"{render_cls.__name__!r} is not a parent or child of \"\n f\"{self.render_cls.__name__!r}\"\n )\n\n @overload\n def update(\n self,\n namespace: ArgsNamespace,\n /,\n *namespaces: ArgsNamespace,\n ) -> RenderArgs: ...\n\n @overload\n def update(\n self,\n render_cls: type[Renderable],\n /,\n **fields: Any,\n ) -> RenderArgs: ...\n\n def update(\n self,\n render_cls_or_namespace: type[Renderable] | ArgsNamespace,\n /,\n *namespaces: ArgsNamespace,\n **fields: Any,\n ) -> RenderArgs:\n \"\"\"update(namespace, /, *namespaces) -> RenderArgs\n update(render_cls, /, **fields) -> RenderArgs\n\n Replaces or updates render argument namespaces.\n\n Args:\n namespace (ArgsNamespace): Prepended to *namespaces*.\n namespaces: Render argument namespaces compatible [#an-com]_ with\n :py:attr:`render_cls`.\n\n .. note:: If multiple namespaces associated with the same :term:`render\n class` are given, the last of them takes precedence.\n\n render_cls (type[Renderable]): A :term:`render class` of which\n :py:attr:`render_cls` is a subclass (which may be :py:attr:`render_cls`\n itself) and which has render arguments.\n fields: Render argument fields.\n\n The keywords must be names of render argument fields for *render_cls*.\n\n Returns:\n For the **first** form, an instance with the namespaces for the respective\n associated :term:`render classes` of the given namespaces replaced.\n\n For the **second** form, an instance with the given render argument fields\n for *render_cls* updated, if any.\n\n Raises:\n TypeError: The arguments given do not conform to any of the expected forms.\n\n Propagates exceptions raised by:\n\n * the class constructor, for the **first** form.\n * :py:meth:`__getitem__` and :py:meth:`ArgsNamespace.update()\n `, for the **second** form.\n \"\"\"\n if isinstance(render_cls_or_namespace, RenderableMeta):\n if namespaces:\n raise TypeError(\n \"No other positional argument is expected when the first argument \"\n \"is a render class\"\n )\n render_cls = render_cls_or_namespace\n else:\n if fields:\n raise TypeError(\n \"No keyword argument is expected when the first argument is \"\n \"a render argument namespace\"\n )\n render_cls = None\n namespaces = (render_cls_or_namespace, *namespaces)\n\n return RenderArgs(\n self.render_cls,\n self,\n *((self[render_cls].update(**fields),) if render_cls else namespaces),\n )", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 14805}, "tests/widget/urwid/test_main.py::331": {"resolved_imports": ["src/term_image/__init__.py", "src/term_image/_ctlseqs.py", "src/term_image/exceptions.py", "src/term_image/image/block.py", "src/term_image/image/common.py", "src/term_image/image/iterm2.py", "src/term_image/image/kitty.py", "src/term_image/widget/_urwid.py"], "used_names": ["UrwidImage", "gc"], "enclosing_function": "test_free", "extracted_code": "# Source: src/term_image/widget/_urwid.py\nclass UrwidImage(urwid.Widget):\n \"\"\"Image widget (box/flow) for the urwid TUI framework.\n\n Args:\n image: The image to be rendered by the widget.\n format_spec: :ref:`Render format specifier `. Padding width and\n height are ignored.\n upscale: If ``True``, the image will be upscaled to fit maximally within the\n available size, if necessary, while still preserving the aspect ratio.\n Otherwise, the image is never upscaled.\n\n Raises:\n TypeError: An argument is of an inappropriate type.\n ValueError: An argument is of an appropriate type but has an\n unexpected/invalid value.\n term_image.exceptions.StyleError: Invalid style-specific format specifier.\n term_image.exceptions.UrwidImageError: Too many image widgets rendering images\n with the *kitty* render style.\n\n | Any ample space in the widget's render size is filled with spaces.\n | For animated images, the current frame (at render-time) is rendered.\n\n TIP:\n If *image* is of a :ref:`graphics-based ` render style and the\n widget is being used as or within a **flow** widget, with overlays or in any\n other case where the canvas will require vertical trimming, make sure to use a\n render method that splits images across lines such as the **LINES** render\n method for *kitty* and *iterm2* render styles.\n\n NOTE:\n * The `z-index` style-specific format spec field for\n :py:class:`~term_image.image.KittyImage` is ignored as this is used\n internally.\n * A **maximum** of ``2**32 - 2`` instances initialized with\n :py:class:`~term_image.image.KittyImage` instances may exist at the same time.\n\n IMPORTANT:\n This is defined if and only if the ``urwid`` package is available.\n \"\"\"\n\n _sizing = frozenset((urwid.BOX, urwid.FLOW))\n ignore_focus = True\n\n _ti_error_placeholder = None\n\n # For kitty images\n _ti_disguise_state = 0\n _ti_free_z_indexes = set()\n\n # Progresses thus: 1, -1, 2, -2, 3, ..., 2**31 - 1, -(2**31 - 1)\n # This sequence results in shorter image escape sequences compared to starting\n # from -(2**31)\n _ti_next_z_index = 1\n\n def __init__(\n self, image: BaseImage, format_spec: str = \"\", *, upscale: bool = False\n ) -> None:\n if not isinstance(image, BaseImage):\n raise arg_type_error(\"image\", image)\n\n if not isinstance(format_spec, str):\n raise arg_type_error(\"format_spec\", format_spec)\n *fmt, alpha, style_args = image._check_format_spec(format_spec)\n\n if not isinstance(upscale, bool):\n raise arg_type_error(\"upscale\", upscale)\n\n super().__init__()\n self._ti_image = image\n self._ti_h_align, _, self._ti_v_align, _ = fmt\n self._ti_alpha = alpha\n self._ti_style_args = style_args\n self._ti_sizing = Size.FIT if upscale else Size.AUTO\n\n if isinstance(image, TextImage):\n style_args[\"split_cells\"] = True\n elif isinstance(image, KittyImage):\n style_args[\"z_index\"] = self._ti_z_index = self._ti_get_z_index()\n\n # Since Konsole doesn't blend images placed at the same location and\n # z-index, unlike Kitty (and potentially others), `blend=True` is\n # better on Konsole as it reduces/eliminates flicker.\n if get_terminal_name_version()[0] != \"konsole\":\n # To clear directly overlapped images when urwid redraws a line without\n # a change in image position\n style_args[\"blend\"] = False\n\n def __del__(self) -> None:\n if hasattr(self, \"_ti_z_index\"):\n __class__._ti_free_z_indexes.add(self._ti_z_index)\n\n image = property(\n lambda self: self._ti_image,\n doc=\"\"\"\n The image rendered by the widget\n\n :type: BaseImage\n\n GET:\n Returns the image instance rendered by the widget.\n \"\"\",\n )\n\n def render(self, size: Tuple[int, int], focus: bool = False) -> urwid.Canvas:\n image = self._ti_image\n\n if len(size) == 2: # box\n image.set_size(self._ti_sizing, frame_size=size)\n elif len(size) == 1: # flow\n if self._ti_sizing is Size.FIT:\n image.set_size(size[0])\n else:\n fit_size = self._ti_image._valid_size(size[0])\n ori_size = self._ti_image._valid_size(Size.ORIGINAL)\n image._size = (\n ori_size\n if ori_size[0] <= fit_size[0] and ori_size[1] <= fit_size[1]\n else fit_size\n )\n size = (size[0], image._size[1])\n else: # fixed\n raise UrwidImageError(\"Not a fixed widget\")\n\n try:\n render = image._format_render(\n image._renderer(\n image._render_image, self._ti_alpha, **self._ti_style_args\n ),\n self._ti_h_align,\n size[0],\n self._ti_v_align,\n size[1],\n )\n except Exception:\n if type(self)._ti_error_placeholder is None:\n raise\n canv = type(self)._ti_error_placeholder.render(size, focus)\n else:\n canv = UrwidImageCanvas(render, size, image._size)\n\n return canv\n\n def rows(self, size: Tuple[int], focus: bool = False) -> int:\n fit_size = self._ti_image._valid_size(size[0])\n if self._ti_sizing is Size.FIT:\n n_rows = fit_size[1]\n else:\n ori_size = self._ti_image._valid_size(Size.ORIGINAL)\n n_rows = (\n ori_size[1]\n if ori_size[0] <= fit_size[0] and ori_size[1] <= fit_size[1]\n else fit_size[1]\n )\n\n return n_rows\n\n @classmethod\n def set_error_placeholder(cls, widget: Optional[urwid.Widget]) -> None:\n \"\"\"Sets the widget to be rendered in place of an image when rendering fails.\n\n Args:\n widget: The placeholder widget or ``None`` to remove the placeholder.\n\n Raises:\n TypeError: *widget* is not an urwid widget.\n\n If set, any exception raised during rendering is **suppressed** and the\n placeholder is rendered in place of the image.\n \"\"\"\n if not isinstance(widget, urwid.Widget):\n raise arg_type_error(\"widget\", widget)\n\n cls._ti_error_placeholder = widget\n\n @staticmethod\n def _ti_get_z_index() -> int:\n if __class__._ti_free_z_indexes:\n return __class__._ti_free_z_indexes.pop()\n\n z_index = __class__._ti_next_z_index\n if z_index == 2**31:\n raise UrwidImageError(\"Too many image widgets with the kitty render style\")\n __class__._ti_next_z_index = -z_index if z_index > 0 else -z_index + 1\n\n return z_index\n\n def _ti_change_disguise(self) -> None:\n \"\"\"See :py:meth`UrwidImageCanvas._ti_change_disguise`.\"\"\"\n self._ti_disguise_state = (self._ti_disguise_state + 1) % 3", "n_imports_parsed": 10, "n_files_resolved": 8, "n_chars_extracted": 7167}, "tests/test_image/test_iterm2.py::551": {"resolved_imports": ["src/term_image/__init__.py", "src/term_image/_ctlseqs.py", "src/term_image/exceptions.py", "src/term_image/image/__init__.py", "src/term_image/image/iterm2.py"], "used_names": ["ITerm2Image", "pytest"], "enclosing_function": "test_mix", "extracted_code": "", "n_imports_parsed": 15, "n_files_resolved": 5, "n_chars_extracted": 0}, "tests/test_geometry.py::43": {"resolved_imports": ["src/term_image/geometry.py"], "used_names": ["Size", "pytest"], "enclosing_function": "test_positive_dimensions_only", "extracted_code": "# Source: src/term_image/geometry.py\nclass Size(RawSize):\n \"\"\"The dimensions of a rectangular region.\n\n Raises:\n ValueError: Either dimension is non-positive.\n\n Same as :py:class:`RawSize`, except that both dimensions must be **positive**.\n\n IMPORTANT:\n In the case of multiple inheritance i.e if subclassing this class along with\n other classes, this class should appear last (i.e to the far right) in the\n base class list.\n \"\"\"\n\n __slots__ = ()\n\n def __new__(cls, width: int, height: int) -> Self:\n if width < 1:\n raise arg_value_error_range(\"width\", width)\n if height < 1:\n raise arg_value_error_range(\"height\", height)\n\n # Using `tuple` directly instead of `super()` for performance\n return tuple.__new__(cls, (width, height))", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 829}, "tests/test_image/test_iterm2.py::72": {"resolved_imports": ["src/term_image/__init__.py", "src/term_image/_ctlseqs.py", "src/term_image/exceptions.py", "src/term_image/image/__init__.py", "src/term_image/image/iterm2.py"], "used_names": ["ITerm2Image"], "enclosing_function": "test_descendant", "extracted_code": "", "n_imports_parsed": 15, "n_files_resolved": 5, "n_chars_extracted": 0}, "tests/widget/urwid/test_main.py::332": {"resolved_imports": ["src/term_image/__init__.py", "src/term_image/_ctlseqs.py", "src/term_image/exceptions.py", "src/term_image/image/block.py", "src/term_image/image/common.py", "src/term_image/image/iterm2.py", "src/term_image/image/kitty.py", "src/term_image/widget/_urwid.py"], "used_names": ["UrwidImage", "gc"], "enclosing_function": "test_free", "extracted_code": "# Source: src/term_image/widget/_urwid.py\nclass UrwidImage(urwid.Widget):\n \"\"\"Image widget (box/flow) for the urwid TUI framework.\n\n Args:\n image: The image to be rendered by the widget.\n format_spec: :ref:`Render format specifier `. Padding width and\n height are ignored.\n upscale: If ``True``, the image will be upscaled to fit maximally within the\n available size, if necessary, while still preserving the aspect ratio.\n Otherwise, the image is never upscaled.\n\n Raises:\n TypeError: An argument is of an inappropriate type.\n ValueError: An argument is of an appropriate type but has an\n unexpected/invalid value.\n term_image.exceptions.StyleError: Invalid style-specific format specifier.\n term_image.exceptions.UrwidImageError: Too many image widgets rendering images\n with the *kitty* render style.\n\n | Any ample space in the widget's render size is filled with spaces.\n | For animated images, the current frame (at render-time) is rendered.\n\n TIP:\n If *image* is of a :ref:`graphics-based ` render style and the\n widget is being used as or within a **flow** widget, with overlays or in any\n other case where the canvas will require vertical trimming, make sure to use a\n render method that splits images across lines such as the **LINES** render\n method for *kitty* and *iterm2* render styles.\n\n NOTE:\n * The `z-index` style-specific format spec field for\n :py:class:`~term_image.image.KittyImage` is ignored as this is used\n internally.\n * A **maximum** of ``2**32 - 2`` instances initialized with\n :py:class:`~term_image.image.KittyImage` instances may exist at the same time.\n\n IMPORTANT:\n This is defined if and only if the ``urwid`` package is available.\n \"\"\"\n\n _sizing = frozenset((urwid.BOX, urwid.FLOW))\n ignore_focus = True\n\n _ti_error_placeholder = None\n\n # For kitty images\n _ti_disguise_state = 0\n _ti_free_z_indexes = set()\n\n # Progresses thus: 1, -1, 2, -2, 3, ..., 2**31 - 1, -(2**31 - 1)\n # This sequence results in shorter image escape sequences compared to starting\n # from -(2**31)\n _ti_next_z_index = 1\n\n def __init__(\n self, image: BaseImage, format_spec: str = \"\", *, upscale: bool = False\n ) -> None:\n if not isinstance(image, BaseImage):\n raise arg_type_error(\"image\", image)\n\n if not isinstance(format_spec, str):\n raise arg_type_error(\"format_spec\", format_spec)\n *fmt, alpha, style_args = image._check_format_spec(format_spec)\n\n if not isinstance(upscale, bool):\n raise arg_type_error(\"upscale\", upscale)\n\n super().__init__()\n self._ti_image = image\n self._ti_h_align, _, self._ti_v_align, _ = fmt\n self._ti_alpha = alpha\n self._ti_style_args = style_args\n self._ti_sizing = Size.FIT if upscale else Size.AUTO\n\n if isinstance(image, TextImage):\n style_args[\"split_cells\"] = True\n elif isinstance(image, KittyImage):\n style_args[\"z_index\"] = self._ti_z_index = self._ti_get_z_index()\n\n # Since Konsole doesn't blend images placed at the same location and\n # z-index, unlike Kitty (and potentially others), `blend=True` is\n # better on Konsole as it reduces/eliminates flicker.\n if get_terminal_name_version()[0] != \"konsole\":\n # To clear directly overlapped images when urwid redraws a line without\n # a change in image position\n style_args[\"blend\"] = False\n\n def __del__(self) -> None:\n if hasattr(self, \"_ti_z_index\"):\n __class__._ti_free_z_indexes.add(self._ti_z_index)\n\n image = property(\n lambda self: self._ti_image,\n doc=\"\"\"\n The image rendered by the widget\n\n :type: BaseImage\n\n GET:\n Returns the image instance rendered by the widget.\n \"\"\",\n )\n\n def render(self, size: Tuple[int, int], focus: bool = False) -> urwid.Canvas:\n image = self._ti_image\n\n if len(size) == 2: # box\n image.set_size(self._ti_sizing, frame_size=size)\n elif len(size) == 1: # flow\n if self._ti_sizing is Size.FIT:\n image.set_size(size[0])\n else:\n fit_size = self._ti_image._valid_size(size[0])\n ori_size = self._ti_image._valid_size(Size.ORIGINAL)\n image._size = (\n ori_size\n if ori_size[0] <= fit_size[0] and ori_size[1] <= fit_size[1]\n else fit_size\n )\n size = (size[0], image._size[1])\n else: # fixed\n raise UrwidImageError(\"Not a fixed widget\")\n\n try:\n render = image._format_render(\n image._renderer(\n image._render_image, self._ti_alpha, **self._ti_style_args\n ),\n self._ti_h_align,\n size[0],\n self._ti_v_align,\n size[1],\n )\n except Exception:\n if type(self)._ti_error_placeholder is None:\n raise\n canv = type(self)._ti_error_placeholder.render(size, focus)\n else:\n canv = UrwidImageCanvas(render, size, image._size)\n\n return canv\n\n def rows(self, size: Tuple[int], focus: bool = False) -> int:\n fit_size = self._ti_image._valid_size(size[0])\n if self._ti_sizing is Size.FIT:\n n_rows = fit_size[1]\n else:\n ori_size = self._ti_image._valid_size(Size.ORIGINAL)\n n_rows = (\n ori_size[1]\n if ori_size[0] <= fit_size[0] and ori_size[1] <= fit_size[1]\n else fit_size[1]\n )\n\n return n_rows\n\n @classmethod\n def set_error_placeholder(cls, widget: Optional[urwid.Widget]) -> None:\n \"\"\"Sets the widget to be rendered in place of an image when rendering fails.\n\n Args:\n widget: The placeholder widget or ``None`` to remove the placeholder.\n\n Raises:\n TypeError: *widget* is not an urwid widget.\n\n If set, any exception raised during rendering is **suppressed** and the\n placeholder is rendered in place of the image.\n \"\"\"\n if not isinstance(widget, urwid.Widget):\n raise arg_type_error(\"widget\", widget)\n\n cls._ti_error_placeholder = widget\n\n @staticmethod\n def _ti_get_z_index() -> int:\n if __class__._ti_free_z_indexes:\n return __class__._ti_free_z_indexes.pop()\n\n z_index = __class__._ti_next_z_index\n if z_index == 2**31:\n raise UrwidImageError(\"Too many image widgets with the kitty render style\")\n __class__._ti_next_z_index = -z_index if z_index > 0 else -z_index + 1\n\n return z_index\n\n def _ti_change_disguise(self) -> None:\n \"\"\"See :py:meth`UrwidImageCanvas._ti_change_disguise`.\"\"\"\n self._ti_disguise_state = (self._ti_disguise_state + 1) % 3", "n_imports_parsed": 10, "n_files_resolved": 8, "n_chars_extracted": 7167}, "tests/test_color.py::46": {"resolved_imports": ["src/term_image/color.py"], "used_names": ["Color"], "enclosing_function": "test_is_tuple", "extracted_code": "# Source: src/term_image/color.py\nclass Color(_DummyColor):\n \"\"\"A color.\n\n Args:\n r: The red channel.\n g: The green channel.\n b: The blue channel.\n a: The alpha channel (opacity).\n\n Raises:\n ValueError: The value of a channel is not within the valid range.\n\n NOTE:\n The valid value range for all channels is 0 to 255, both inclusive.\n\n TIP:\n This class is a :py:class:`~typing.NamedTuple` of four fields.\n\n WARNING:\n In the case of multiple inheritance i.e if subclassing this class along with\n other classes, this class should appear last (i.e to the far right) in the\n base class list.\n \"\"\"\n\n __slots__ = ()\n\n # Overrides these descriptors in order to speed up attribute resolution and to\n # simplify auto documentation.\n r: int = _DummyColor.r\n r.__doc__ = \"\"\"The red channel\"\"\"\n\n g: int = _DummyColor.g\n g.__doc__ = \"\"\"The green channel\"\"\"\n\n b: int = _DummyColor.b\n b.__doc__ = \"\"\"The blue channel\"\"\"\n\n a: int = _DummyColor.a\n a.__doc__ = \"\"\"The alpha channel (opacity)\"\"\"\n\n def __new__(cls, r: int, g: int, b: int, a: int = 255) -> Self:\n # Only the 8 LSb may be set for any value within the range [0, 255].\n # `x & ~255` unsets the 8 LSb. Hence, if the result is non-zero (i.e any\n # of the bits above the lowest 8 is set), it implies `x` is out of range.\n #\n # Actually benchmarked *this* against the \"simpler\" logically-negated chained\n # comparison (i.e `0 <= x <= 255`) and *this* was significantly faster for all\n # cases i.e within, on the boundaries, and outside (on both sides).\n if (r | g | b | a) & ~255: # First test to see if *any* is out of range\n if r & ~255:\n raise arg_value_error_range(\"r\", r)\n if g & ~255:\n raise arg_value_error_range(\"g\", g)\n if b & ~255:\n raise arg_value_error_range(\"b\", b)\n # There's no point checking since at least one is out of range\n raise arg_value_error_range(\"a\", a)\n\n # Using `tuple` directly instead of `super()` for performance\n return tuple.__new__(cls, (r, g, b, a))\n\n @property\n def hex(self) -> str:\n \"\"\"Converts the color to its RGBA hexadecimal representation.\n\n Returns:\n The RGBA hex color string, starting with the ``#`` character i.e\n ``#rrggbbaa``.\n\n Each channel is represented by two **lowercase** hex digits ranging from\n ``00`` to ``ff``.\n \"\"\"\n return \"#%02x%02x%02x%02x\" % self\n\n @property\n def rgb(self) -> tuple[int, int, int]:\n \"\"\"Extracts the R, G and B channels of the color.\n\n Returns:\n A 3-tuple containing the red, green and blue channel values.\n \"\"\"\n return self[:3]\n\n @property\n def rgb_hex(self) -> str:\n \"\"\"Converts the color to its RGB hexadecimal representation.\n\n Returns:\n The RGB hex color string, starting with the ``#`` character i.e ``#rrggbb``.\n\n Each channel is represented by two **lowercase** hex digits ranging from\n ``00`` to ``ff``.\n \"\"\"\n return \"#%02x%02x%02x\" % self[:3]\n\n @classmethod\n def from_hex(cls, color: str) -> Self:\n \"\"\"Creates a new instance from a hexadecimal color string.\n\n Args:\n color: A **case-insensitive** RGB or RGBA hex color string, **optionally**\n starting with the ``#`` (pound) character i.e ``[#]rrggbb[aa]``.\n\n Returns:\n A new instance representing the given hex color string.\n\n Raises:\n ValueError: Invalid hex color string.\n\n NOTE:\n For an RGB hex color string, the value of A (the alpha channel) is\n taken to be 255.\n \"\"\"\n if not (match := _RGBA_HEX_RE.fullmatch(color)):\n raise ValueError(f\"Invalid hex color string (got: {color!r})\")\n\n return tuple.__new__(cls, [int(x, 16) for x in match.groups(\"ff\")])\n\n @classmethod\n def _new(cls, r: int, g: int, b: int, a: int = 255) -> Self:\n \"\"\"Alternate constructor for internal use only.\"\"\"\n return tuple.__new__(cls, (r, g, b, a))", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 4255}, "tests/test_image/test_base.py::258": {"resolved_imports": ["src/term_image/__init__.py", "src/term_image/_ctlseqs.py", "src/term_image/exceptions.py", "src/term_image/image/block.py", "src/term_image/image/common.py"], "used_names": ["BlockImage", "pytest", "python_img"], "enclosing_function": "test_n_frames", "extracted_code": "# Source: src/term_image/image/block.py\nclass BlockImage(TextImage):\n \"\"\"A render style using unicode half blocks and direct-color colour escape\n sequences.\n\n See :py:class:`TextImage` for the description of the constructor.\n \"\"\"\n\n @classmethod\n def is_supported(cls):\n if cls._supported is None:\n COLORTERM = os.environ.get(\"COLORTERM\") or \"\"\n TERM = os.environ.get(\"TERM\") or \"\"\n cls._supported = (\n \"truecolor\" in COLORTERM or \"24bit\" in COLORTERM or \"256color\" in TERM\n )\n\n return cls._supported\n\n def _get_render_size(self) -> Tuple[int, int]:\n return tuple(map(mul, self.rendered_size, (1, 2)))\n\n @staticmethod\n def _pixels_cols(\n *, pixels: Optional[int] = None, cols: Optional[int] = None\n ) -> int:\n return pixels if pixels is not None else cols\n\n @staticmethod\n def _pixels_lines(\n *, pixels: Optional[int] = None, lines: Optional[int] = None\n ) -> int:\n return ceil(pixels / 2) if pixels is not None else lines * 2\n\n def _render_image(\n self,\n img: PIL.Image.Image,\n alpha: Union[None, float, str],\n *,\n frame: bool = False,\n split_cells: bool = False,\n ) -> str:\n # NOTE:\n # It's more efficient to write separate strings to the buffer separately\n # than concatenate and write together.\n\n def update_buffer():\n if alpha:\n no_alpha = False\n if a_cluster1 == 0 == a_cluster2:\n buf_write(SGR_DEFAULT)\n buf_write(blank * n)\n elif a_cluster1 == 0: # up is transparent\n buf_write(SGR_DEFAULT)\n buf_write(SGR_FG_DIRECT % cluster2)\n buf_write(lower_pixel * n)\n elif a_cluster2 == 0: # down is transparent\n buf_write(SGR_DEFAULT)\n buf_write(SGR_FG_DIRECT % cluster1)\n buf_write(upper_pixel * n)\n else:\n no_alpha = True\n\n if not alpha or no_alpha:\n r, g, b = cluster2\n # Kitty does not render BG colors equal to the default BG color\n if is_on_kitty and cluster2 == bg_color:\n r += r < 255 or -1\n buf_write(SGR_BG_DIRECT % (r, g, b))\n if cluster1 == cluster2:\n buf_write(blank * n)\n else:\n buf_write(SGR_FG_DIRECT % cluster1)\n buf_write(upper_pixel * n)\n\n buffer = io.StringIO()\n buf_write = buffer.write # Eliminate attribute resolution cost\n\n bg_color = get_fg_bg_colors()[1]\n is_on_kitty = self._is_on_kitty()\n if split_cells:\n blank = \" \\0\"\n lower_pixel = LOWER_PIXEL + \"\\0\"\n upper_pixel = UPPER_PIXEL + \"\\0\"\n else:\n blank = \" \"\n lower_pixel = LOWER_PIXEL\n upper_pixel = UPPER_PIXEL\n end_of_line = SGR_DEFAULT + \"\\n\"\n\n width, height = self._get_render_size()\n frame_img = img if frame else None\n img, rgb, a = self._get_render_data(img, alpha, round_alpha=True, frame=frame)\n alpha = img.mode == \"RGBA\"\n\n # clean up (ImageIterator uses one PIL image throughout)\n if frame_img is not img:\n self._close_image(img)\n\n rgb_pairs = (\n (\n zip(rgb[x : x + width], rgb[x + width : x + width * 2]),\n (rgb[x], rgb[x + width]),\n )\n for x in range(0, len(rgb), width * 2)\n )\n a_pairs = (\n (\n zip(a[x : x + width], a[x + width : x + width * 2]),\n (a[x], a[x + width]),\n )\n for x in range(0, len(a), width * 2)\n )\n\n row_no = 0\n # Two rows of pixels per line\n for (rgb_pair, (cluster1, cluster2)), (a_pair, (a_cluster1, a_cluster2)) in zip(\n rgb_pairs, a_pairs\n ):\n row_no += 2\n n = 0\n for (px1, px2), (a1, a2) in zip(rgb_pair, a_pair):\n # Color-code characters and write to buffer\n # when upper and/or lower pixel color/alpha-level changes\n if not (alpha and a1 == a_cluster1 == 0 == a_cluster2 == a2) and (\n px1 != cluster1\n or px2 != cluster2\n or alpha\n and (\n # From non-transparent to transparent\n a_cluster1 != a1 == 0\n or a_cluster2 != a2 == 0\n # From transparent to non-transparent\n or 0 == a_cluster1 != a1\n or 0 == a_cluster2 != a2\n )\n ):\n update_buffer()\n cluster1 = px1\n cluster2 = px2\n if alpha:\n a_cluster1 = a1\n a_cluster2 = a2\n n = 0\n n += 1\n\n update_buffer() # Rest of the line\n if split_cells:\n # Set the last \"\\0\" to be overwritten by the next byte\n buffer.seek(buffer.tell() - 1)\n if row_no < height: # last line not yet rendered\n buf_write(end_of_line)\n\n buf_write(SGR_DEFAULT) # Reset color after last line\n\n with buffer:\n return buffer.getvalue()", "n_imports_parsed": 16, "n_files_resolved": 5, "n_chars_extracted": 5566}, "tests/test_color.py::43": {"resolved_imports": ["src/term_image/color.py"], "used_names": ["Color"], "enclosing_function": "test_is_tuple", "extracted_code": "# Source: src/term_image/color.py\nclass Color(_DummyColor):\n \"\"\"A color.\n\n Args:\n r: The red channel.\n g: The green channel.\n b: The blue channel.\n a: The alpha channel (opacity).\n\n Raises:\n ValueError: The value of a channel is not within the valid range.\n\n NOTE:\n The valid value range for all channels is 0 to 255, both inclusive.\n\n TIP:\n This class is a :py:class:`~typing.NamedTuple` of four fields.\n\n WARNING:\n In the case of multiple inheritance i.e if subclassing this class along with\n other classes, this class should appear last (i.e to the far right) in the\n base class list.\n \"\"\"\n\n __slots__ = ()\n\n # Overrides these descriptors in order to speed up attribute resolution and to\n # simplify auto documentation.\n r: int = _DummyColor.r\n r.__doc__ = \"\"\"The red channel\"\"\"\n\n g: int = _DummyColor.g\n g.__doc__ = \"\"\"The green channel\"\"\"\n\n b: int = _DummyColor.b\n b.__doc__ = \"\"\"The blue channel\"\"\"\n\n a: int = _DummyColor.a\n a.__doc__ = \"\"\"The alpha channel (opacity)\"\"\"\n\n def __new__(cls, r: int, g: int, b: int, a: int = 255) -> Self:\n # Only the 8 LSb may be set for any value within the range [0, 255].\n # `x & ~255` unsets the 8 LSb. Hence, if the result is non-zero (i.e any\n # of the bits above the lowest 8 is set), it implies `x` is out of range.\n #\n # Actually benchmarked *this* against the \"simpler\" logically-negated chained\n # comparison (i.e `0 <= x <= 255`) and *this* was significantly faster for all\n # cases i.e within, on the boundaries, and outside (on both sides).\n if (r | g | b | a) & ~255: # First test to see if *any* is out of range\n if r & ~255:\n raise arg_value_error_range(\"r\", r)\n if g & ~255:\n raise arg_value_error_range(\"g\", g)\n if b & ~255:\n raise arg_value_error_range(\"b\", b)\n # There's no point checking since at least one is out of range\n raise arg_value_error_range(\"a\", a)\n\n # Using `tuple` directly instead of `super()` for performance\n return tuple.__new__(cls, (r, g, b, a))\n\n @property\n def hex(self) -> str:\n \"\"\"Converts the color to its RGBA hexadecimal representation.\n\n Returns:\n The RGBA hex color string, starting with the ``#`` character i.e\n ``#rrggbbaa``.\n\n Each channel is represented by two **lowercase** hex digits ranging from\n ``00`` to ``ff``.\n \"\"\"\n return \"#%02x%02x%02x%02x\" % self\n\n @property\n def rgb(self) -> tuple[int, int, int]:\n \"\"\"Extracts the R, G and B channels of the color.\n\n Returns:\n A 3-tuple containing the red, green and blue channel values.\n \"\"\"\n return self[:3]\n\n @property\n def rgb_hex(self) -> str:\n \"\"\"Converts the color to its RGB hexadecimal representation.\n\n Returns:\n The RGB hex color string, starting with the ``#`` character i.e ``#rrggbb``.\n\n Each channel is represented by two **lowercase** hex digits ranging from\n ``00`` to ``ff``.\n \"\"\"\n return \"#%02x%02x%02x\" % self[:3]\n\n @classmethod\n def from_hex(cls, color: str) -> Self:\n \"\"\"Creates a new instance from a hexadecimal color string.\n\n Args:\n color: A **case-insensitive** RGB or RGBA hex color string, **optionally**\n starting with the ``#`` (pound) character i.e ``[#]rrggbb[aa]``.\n\n Returns:\n A new instance representing the given hex color string.\n\n Raises:\n ValueError: Invalid hex color string.\n\n NOTE:\n For an RGB hex color string, the value of A (the alpha channel) is\n taken to be 255.\n \"\"\"\n if not (match := _RGBA_HEX_RE.fullmatch(color)):\n raise ValueError(f\"Invalid hex color string (got: {color!r})\")\n\n return tuple.__new__(cls, [int(x, 16) for x in match.groups(\"ff\")])\n\n @classmethod\n def _new(cls, r: int, g: int, b: int, a: int = 255) -> Self:\n \"\"\"Alternate constructor for internal use only.\"\"\"\n return tuple.__new__(cls, (r, g, b, a))", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 4255}, "tests/test_image/test_url.py::39": {"resolved_imports": ["src/term_image/exceptions.py", "src/term_image/image/block.py", "src/term_image/image/common.py", "src/term_image/image/__init__.py"], "used_names": ["BlockImage", "ImageSource", "Size", "URLNotFoundError", "UnidentifiedImageError", "from_url", "os", "pytest"], "enclosing_function": "test_from_url", "extracted_code": "# Source: src/term_image/exceptions.py\nclass URLNotFoundError(TermImageError, FileNotFoundError):\n \"\"\"Raised for 404 errors.\"\"\"\n\n\n# Source: src/term_image/image/block.py\nclass BlockImage(TextImage):\n \"\"\"A render style using unicode half blocks and direct-color colour escape\n sequences.\n\n See :py:class:`TextImage` for the description of the constructor.\n \"\"\"\n\n @classmethod\n def is_supported(cls):\n if cls._supported is None:\n COLORTERM = os.environ.get(\"COLORTERM\") or \"\"\n TERM = os.environ.get(\"TERM\") or \"\"\n cls._supported = (\n \"truecolor\" in COLORTERM or \"24bit\" in COLORTERM or \"256color\" in TERM\n )\n\n return cls._supported\n\n def _get_render_size(self) -> Tuple[int, int]:\n return tuple(map(mul, self.rendered_size, (1, 2)))\n\n @staticmethod\n def _pixels_cols(\n *, pixels: Optional[int] = None, cols: Optional[int] = None\n ) -> int:\n return pixels if pixels is not None else cols\n\n @staticmethod\n def _pixels_lines(\n *, pixels: Optional[int] = None, lines: Optional[int] = None\n ) -> int:\n return ceil(pixels / 2) if pixels is not None else lines * 2\n\n def _render_image(\n self,\n img: PIL.Image.Image,\n alpha: Union[None, float, str],\n *,\n frame: bool = False,\n split_cells: bool = False,\n ) -> str:\n # NOTE:\n # It's more efficient to write separate strings to the buffer separately\n # than concatenate and write together.\n\n def update_buffer():\n if alpha:\n no_alpha = False\n if a_cluster1 == 0 == a_cluster2:\n buf_write(SGR_DEFAULT)\n buf_write(blank * n)\n elif a_cluster1 == 0: # up is transparent\n buf_write(SGR_DEFAULT)\n buf_write(SGR_FG_DIRECT % cluster2)\n buf_write(lower_pixel * n)\n elif a_cluster2 == 0: # down is transparent\n buf_write(SGR_DEFAULT)\n buf_write(SGR_FG_DIRECT % cluster1)\n buf_write(upper_pixel * n)\n else:\n no_alpha = True\n\n if not alpha or no_alpha:\n r, g, b = cluster2\n # Kitty does not render BG colors equal to the default BG color\n if is_on_kitty and cluster2 == bg_color:\n r += r < 255 or -1\n buf_write(SGR_BG_DIRECT % (r, g, b))\n if cluster1 == cluster2:\n buf_write(blank * n)\n else:\n buf_write(SGR_FG_DIRECT % cluster1)\n buf_write(upper_pixel * n)\n\n buffer = io.StringIO()\n buf_write = buffer.write # Eliminate attribute resolution cost\n\n bg_color = get_fg_bg_colors()[1]\n is_on_kitty = self._is_on_kitty()\n if split_cells:\n blank = \" \\0\"\n lower_pixel = LOWER_PIXEL + \"\\0\"\n upper_pixel = UPPER_PIXEL + \"\\0\"\n else:\n blank = \" \"\n lower_pixel = LOWER_PIXEL\n upper_pixel = UPPER_PIXEL\n end_of_line = SGR_DEFAULT + \"\\n\"\n\n width, height = self._get_render_size()\n frame_img = img if frame else None\n img, rgb, a = self._get_render_data(img, alpha, round_alpha=True, frame=frame)\n alpha = img.mode == \"RGBA\"\n\n # clean up (ImageIterator uses one PIL image throughout)\n if frame_img is not img:\n self._close_image(img)\n\n rgb_pairs = (\n (\n zip(rgb[x : x + width], rgb[x + width : x + width * 2]),\n (rgb[x], rgb[x + width]),\n )\n for x in range(0, len(rgb), width * 2)\n )\n a_pairs = (\n (\n zip(a[x : x + width], a[x + width : x + width * 2]),\n (a[x], a[x + width]),\n )\n for x in range(0, len(a), width * 2)\n )\n\n row_no = 0\n # Two rows of pixels per line\n for (rgb_pair, (cluster1, cluster2)), (a_pair, (a_cluster1, a_cluster2)) in zip(\n rgb_pairs, a_pairs\n ):\n row_no += 2\n n = 0\n for (px1, px2), (a1, a2) in zip(rgb_pair, a_pair):\n # Color-code characters and write to buffer\n # when upper and/or lower pixel color/alpha-level changes\n if not (alpha and a1 == a_cluster1 == 0 == a_cluster2 == a2) and (\n px1 != cluster1\n or px2 != cluster2\n or alpha\n and (\n # From non-transparent to transparent\n a_cluster1 != a1 == 0\n or a_cluster2 != a2 == 0\n # From transparent to non-transparent\n or 0 == a_cluster1 != a1\n or 0 == a_cluster2 != a2\n )\n ):\n update_buffer()\n cluster1 = px1\n cluster2 = px2\n if alpha:\n a_cluster1 = a1\n a_cluster2 = a2\n n = 0\n n += 1\n\n update_buffer() # Rest of the line\n if split_cells:\n # Set the last \"\\0\" to be overwritten by the next byte\n buffer.seek(buffer.tell() - 1)\n if row_no < height: # last line not yet rendered\n buf_write(end_of_line)\n\n buf_write(SGR_DEFAULT) # Reset color after last line\n\n with buffer:\n return buffer.getvalue()\n\n\n# Source: src/term_image/image/common.py\nclass ImageSource(Enum):\n \"\"\"Image source type.\"\"\"\n\n #: The instance was derived from a path to a local image file.\n #:\n #: :meta hide-value:\n FILE_PATH = SourceAttr(\"_source\")\n\n #: The instance was derived from a PIL image instance.\n #:\n #: :meta hide-value:\n PIL_IMAGE = SourceAttr(\"_source\")\n\n #: The instance was derived from an image URL.\n #:\n #: :meta hide-value:\n URL = SourceAttr(\"_url\")\n\nclass Size(Enum):\n \"\"\"Enumeration for :term:`automatic sizing`.\"\"\"\n\n #: Equivalent to :py:attr:`ORIGINAL` if it will fit into the\n #: :term:`frame size`, else :py:attr:`FIT`.\n #:\n #: :meta hide-value:\n AUTO = Hidden()\n\n #: The image size is set to fit optimally **within** the :term:`frame size`.\n #:\n #: :meta hide-value:\n FIT = Hidden()\n\n #: The size is set such that the width is exactly the :term:`frame width`,\n #: regardless of the :term:`cell ratio`.\n #:\n #: :meta hide-value:\n FIT_TO_WIDTH = Hidden()\n\n #: The image size is set such that the image is rendered with as many pixels as the\n #: the original image consists of.\n #:\n #: :meta hide-value:\n ORIGINAL = Hidden()\n\n\n# Source: src/term_image/image/__init__.py\ndef from_url(\n url: str,\n **kwargs: Union[None, int],\n) -> BaseImage:\n \"\"\"Creates an image instance from an image URL.\n\n Returns:\n An instance of the automatically selected image render style (as returned by\n :py:func:`auto_image_class`).\n\n Same arguments and raised exceptions as :py:meth:`BaseImage.from_url`.\n \"\"\"\n return auto_image_class().from_url(url, **kwargs)", "n_imports_parsed": 6, "n_files_resolved": 4, "n_chars_extracted": 7364}, "tests/renderable/test_renderable.py::1294": {"resolved_imports": ["src/term_image/_ctlseqs.py", "src/term_image/geometry.py", "src/term_image/padding.py", "src/term_image/renderable/_enum.py", "src/term_image/renderable/_exceptions.py", "src/term_image/renderable/_renderable.py", "src/term_image/renderable/_types.py"], "used_names": ["IndefiniteSeekError", "Seek", "pytest"], "enclosing_function": "test_indefinite", "extracted_code": "# Source: src/term_image/renderable/_enum.py\nclass Seek(IntEnum):\n \"\"\"Relative seek enumeration\n\n TIP:\n * Each member's value is that of the corresponding\n :py:data:`os.SEEK_* ` constant.\n * Every member can be used directly as an integer since\n :py:class:`enum.IntEnum` is a base class.\n\n .. seealso::\n :py:meth:`Renderable.seek`,\n :py:meth:`RenderIterator.seek() `\n \"\"\"\n\n START = SET = os.SEEK_SET\n \"\"\"Start position\"\"\"\n\n CURRENT = CUR = os.SEEK_CUR\n \"\"\"Current position\"\"\"\n\n END = os.SEEK_END\n \"\"\"End position\"\"\"\n\n\n# Source: src/term_image/renderable/_exceptions.py\nclass IndefiniteSeekError(RenderableError):\n \"\"\"Raised when a seek is attempted on a renderable with\n :py:attr:`~term_image.renderable.FrameCount.INDEFINITE` frame count.\n \"\"\"", "n_imports_parsed": 14, "n_files_resolved": 7, "n_chars_extracted": 879}, "tests/test_padding.py::386": {"resolved_imports": ["src/term_image/_ctlseqs.py", "src/term_image/geometry.py", "src/term_image/padding.py"], "used_names": ["ExactPadding"], "enclosing_function": "test_left", "extracted_code": "# Source: src/term_image/padding.py\nclass ExactPadding(Padding):\n \"\"\"Exact :term:`render output` padding.\n\n Args:\n left: Left padding dimension\n top: Top padding dimension.\n right: Right padding dimension\n bottom: Bottom padding dimension\n\n Raises:\n ValueError: A dimension is negative.\n\n Pads a render output on each side by the specified amount of lines or columns.\n\n TIP:\n * Instances are immutable and hashable.\n * Instances with equal fields compare equal.\n \"\"\"\n\n # Class Attributes =========================================================\n\n __slots__ = (\"left\", \"top\", \"right\", \"bottom\")\n\n # Instance Attributes ======================================================\n\n left: int\n \"\"\"Left padding dimension\"\"\"\n\n top: int\n \"\"\"Top padding dimension\"\"\"\n\n right: int\n \"\"\"Right padding dimension\"\"\"\n\n bottom: int\n \"\"\"Bottom padding dimension\"\"\"\n\n fill: str\n\n # Special Methods ==========================================================\n\n def __init__(\n self,\n left: int = 0,\n top: int = 0,\n right: int = 0,\n bottom: int = 0,\n fill: str = \" \",\n ) -> None:\n super().__init__(fill)\n\n _setattr = super().__setattr__\n for name in (\"left\", \"top\", \"right\", \"bottom\"):\n value = locals()[name]\n if value < 0:\n raise arg_value_error_range(name, value)\n _setattr(name, value)\n\n # Properties ===============================================================\n\n @property\n def dimensions(self) -> tuple[int, int, int, int]:\n \"\"\"Padding dimensions\n\n GET:\n Returns the padding dimensions, ``(left, top, right, bottom)``.\n \"\"\"\n return astuple(self)[:4]\n\n # Extension methods ========================================================\n\n @override\n def _get_exact_dimensions_(self, render_size: Size) -> tuple[int, int, int, int]:\n return astuple(self)[:4]", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 2021}, "tests/test_color.py::89": {"resolved_imports": ["src/term_image/color.py"], "used_names": ["Color", "pytest"], "enclosing_function": "test_invalid", "extracted_code": "# Source: src/term_image/color.py\nclass Color(_DummyColor):\n \"\"\"A color.\n\n Args:\n r: The red channel.\n g: The green channel.\n b: The blue channel.\n a: The alpha channel (opacity).\n\n Raises:\n ValueError: The value of a channel is not within the valid range.\n\n NOTE:\n The valid value range for all channels is 0 to 255, both inclusive.\n\n TIP:\n This class is a :py:class:`~typing.NamedTuple` of four fields.\n\n WARNING:\n In the case of multiple inheritance i.e if subclassing this class along with\n other classes, this class should appear last (i.e to the far right) in the\n base class list.\n \"\"\"\n\n __slots__ = ()\n\n # Overrides these descriptors in order to speed up attribute resolution and to\n # simplify auto documentation.\n r: int = _DummyColor.r\n r.__doc__ = \"\"\"The red channel\"\"\"\n\n g: int = _DummyColor.g\n g.__doc__ = \"\"\"The green channel\"\"\"\n\n b: int = _DummyColor.b\n b.__doc__ = \"\"\"The blue channel\"\"\"\n\n a: int = _DummyColor.a\n a.__doc__ = \"\"\"The alpha channel (opacity)\"\"\"\n\n def __new__(cls, r: int, g: int, b: int, a: int = 255) -> Self:\n # Only the 8 LSb may be set for any value within the range [0, 255].\n # `x & ~255` unsets the 8 LSb. Hence, if the result is non-zero (i.e any\n # of the bits above the lowest 8 is set), it implies `x` is out of range.\n #\n # Actually benchmarked *this* against the \"simpler\" logically-negated chained\n # comparison (i.e `0 <= x <= 255`) and *this* was significantly faster for all\n # cases i.e within, on the boundaries, and outside (on both sides).\n if (r | g | b | a) & ~255: # First test to see if *any* is out of range\n if r & ~255:\n raise arg_value_error_range(\"r\", r)\n if g & ~255:\n raise arg_value_error_range(\"g\", g)\n if b & ~255:\n raise arg_value_error_range(\"b\", b)\n # There's no point checking since at least one is out of range\n raise arg_value_error_range(\"a\", a)\n\n # Using `tuple` directly instead of `super()` for performance\n return tuple.__new__(cls, (r, g, b, a))\n\n @property\n def hex(self) -> str:\n \"\"\"Converts the color to its RGBA hexadecimal representation.\n\n Returns:\n The RGBA hex color string, starting with the ``#`` character i.e\n ``#rrggbbaa``.\n\n Each channel is represented by two **lowercase** hex digits ranging from\n ``00`` to ``ff``.\n \"\"\"\n return \"#%02x%02x%02x%02x\" % self\n\n @property\n def rgb(self) -> tuple[int, int, int]:\n \"\"\"Extracts the R, G and B channels of the color.\n\n Returns:\n A 3-tuple containing the red, green and blue channel values.\n \"\"\"\n return self[:3]\n\n @property\n def rgb_hex(self) -> str:\n \"\"\"Converts the color to its RGB hexadecimal representation.\n\n Returns:\n The RGB hex color string, starting with the ``#`` character i.e ``#rrggbb``.\n\n Each channel is represented by two **lowercase** hex digits ranging from\n ``00`` to ``ff``.\n \"\"\"\n return \"#%02x%02x%02x\" % self[:3]\n\n @classmethod\n def from_hex(cls, color: str) -> Self:\n \"\"\"Creates a new instance from a hexadecimal color string.\n\n Args:\n color: A **case-insensitive** RGB or RGBA hex color string, **optionally**\n starting with the ``#`` (pound) character i.e ``[#]rrggbb[aa]``.\n\n Returns:\n A new instance representing the given hex color string.\n\n Raises:\n ValueError: Invalid hex color string.\n\n NOTE:\n For an RGB hex color string, the value of A (the alpha channel) is\n taken to be 255.\n \"\"\"\n if not (match := _RGBA_HEX_RE.fullmatch(color)):\n raise ValueError(f\"Invalid hex color string (got: {color!r})\")\n\n return tuple.__new__(cls, [int(x, 16) for x in match.groups(\"ff\")])\n\n @classmethod\n def _new(cls, r: int, g: int, b: int, a: int = 255) -> Self:\n \"\"\"Alternate constructor for internal use only.\"\"\"\n return tuple.__new__(cls, (r, g, b, a))", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 4255}, "tests/test_top_level.py::120": {"resolved_imports": ["src/term_image/__init__.py", "src/term_image/utils.py", "src/term_image/exceptions.py", "src/term_image/geometry.py"], "used_names": ["pytest", "set_query_timeout", "utils"], "enclosing_function": "test_valid", "extracted_code": "# Source: src/term_image/__init__.py\ndef set_query_timeout(timeout: float) -> None:\n \"\"\"Sets the timeout for :ref:`terminal-queries`.\n\n Args:\n timeout: Time limit for awaiting a response from the terminal, in seconds.\n\n Raises:\n ValueError: *timeout* is less than or equal to zero.\n \"\"\"\n if timeout <= 0.0:\n raise arg_value_error_range(\"timeout\", timeout)\n\n utils._query_timeout = timeout", "n_imports_parsed": 6, "n_files_resolved": 4, "n_chars_extracted": 427}, "tests/test_padding.py::32": {"resolved_imports": ["src/term_image/_ctlseqs.py", "src/term_image/geometry.py", "src/term_image/padding.py"], "used_names": [], "enclosing_function": "test_fill", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/renderable/test_renderable.py::708": {"resolved_imports": ["src/term_image/_ctlseqs.py", "src/term_image/geometry.py", "src/term_image/padding.py", "src/term_image/renderable/_enum.py", "src/term_image/renderable/_exceptions.py", "src/term_image/renderable/_renderable.py", "src/term_image/renderable/_types.py"], "used_names": ["RenderArgs", "Size"], "enclosing_function": "test_animated", "extracted_code": "# Source: src/term_image/geometry.py\nclass Size(RawSize):\n \"\"\"The dimensions of a rectangular region.\n\n Raises:\n ValueError: Either dimension is non-positive.\n\n Same as :py:class:`RawSize`, except that both dimensions must be **positive**.\n\n IMPORTANT:\n In the case of multiple inheritance i.e if subclassing this class along with\n other classes, this class should appear last (i.e to the far right) in the\n base class list.\n \"\"\"\n\n __slots__ = ()\n\n def __new__(cls, width: int, height: int) -> Self:\n if width < 1:\n raise arg_value_error_range(\"width\", width)\n if height < 1:\n raise arg_value_error_range(\"height\", height)\n\n # Using `tuple` directly instead of `super()` for performance\n return tuple.__new__(cls, (width, height))\n\n\n# Source: src/term_image/renderable/_types.py\nclass RenderArgs(RenderArgsData):\n \"\"\"RenderArgs(render_cls, /, *namespaces)\n RenderArgs(render_cls, init_render_args, /, *namespaces)\n\n Render arguments.\n\n Args:\n render_cls: A :term:`render class`.\n init_render_args (RenderArgs | None): A set of render arguments.\n If not ``None``,\n\n * it must be compatible [#ra-com]_ with *render_cls*,\n * it'll be used to initialize the render arguments.\n\n namespaces: Render argument namespaces compatible [#an-com]_ with *render_cls*.\n\n .. note:: If multiple namespaces associated with the same :term:`render\n class` are given, the last of them takes precedence.\n\n Raises:\n IncompatibleRenderArgsError: *init_render_args* is incompatible [#ra-com]_ with\n *render_cls*.\n IncompatibleArgsNamespaceError: Incompatible [#an-com]_ render argument\n namespace.\n\n A set of render arguments (an instance of this class) is basically a container of\n render argument namespaces (instances of\n :py:class:`~term_image.renderable.ArgsNamespace`); one for\n each :term:`render class`, which has render arguments, in the Method Resolution\n Order of its associated [#ra-ass]_ render class.\n\n The namespace for each render class is derived from the following sources, in\n [descending] order of precedence:\n\n * *namespaces*\n * *init_render_args*\n * default render argument namespaces\n\n NOTE:\n Instances are immutable but updated copies can be created via :py:meth:`update`.\n\n .. seealso::\n\n :py:attr:`~term_image.renderable.Renderable.Args`\n Render class-specific render arguments.\n\n .. Completed in /docs/source/api/renderable.rst\n \"\"\"\n\n # Class Attributes =========================================================\n\n __slots__ = ()\n\n _interned: ClassVar[dict[type[Renderable], Self]] = {}\n _namespaces: MappingProxyType[type[Renderable], ArgsNamespace]\n\n # Instance Attributes ======================================================\n\n render_cls: type[Renderable]\n \"\"\"The associated :term:`render class`\"\"\"\n\n # Special Methods ==========================================================\n\n def __new__(\n cls,\n render_cls: type[Renderable],\n init_or_namespace: RenderArgs | ArgsNamespace | None = None,\n *namespaces: ArgsNamespace,\n ) -> Self:\n if init_or_namespace is None:\n init_render_args = None\n elif isinstance(init_or_namespace, RenderArgs):\n init_render_args = init_or_namespace\n else:\n init_render_args = None\n namespaces = (init_or_namespace, *namespaces)\n\n if init_render_args and not issubclass(render_cls, init_render_args.render_cls):\n raise IncompatibleRenderArgsError(\n f\"'init_render_args' (associated with \"\n f\"{init_render_args.render_cls.__name__!r}) is incompatible with \"\n f\"{render_cls.__name__!r} \"\n )\n\n if not namespaces:\n # has default namespaces only\n if (\n not init_render_args\n or init_render_args is BASE_RENDER_ARGS\n or cls._interned.get(init_render_args.render_cls) is init_render_args\n ):\n try:\n return cls._interned[render_cls]\n except KeyError:\n pass\n\n if (\n init_render_args\n and type(init_render_args) is cls\n and init_render_args.render_cls is render_cls\n ):\n return init_render_args\n\n return super().__new__(cls)\n\n def __init__(\n self,\n render_cls: type[Renderable],\n init_or_namespace: RenderArgs | ArgsNamespace | None = None,\n *namespaces: ArgsNamespace,\n ) -> None:\n if init_or_namespace is None:\n init_render_args = None\n elif isinstance(init_or_namespace, RenderArgs):\n init_render_args = init_or_namespace\n else:\n init_render_args = None\n namespaces = (init_or_namespace, *namespaces)\n\n # has default namespaces only\n if not namespaces and (\n not init_render_args\n or init_render_args is BASE_RENDER_ARGS\n or (\n type(self)._interned.get(init_render_args.render_cls)\n is init_render_args\n )\n ):\n if render_cls in type(self)._interned: # has been initialized\n return\n intern = True\n else:\n intern = False\n\n if init_render_args is self:\n return\n\n namespaces_dict = render_cls._ALL_DEFAULT_ARGS.copy()\n\n # if `init_render_args` is non-default\n if init_render_args and BASE_RENDER_ARGS is not init_render_args is not (\n type(self)._interned.get(init_render_args.render_cls)\n ):\n namespaces_dict.update(init_render_args._namespaces)\n\n for index, namespace in enumerate(namespaces):\n if namespace._RENDER_CLS not in namespaces_dict:\n raise IncompatibleArgsNamespaceError(\n f\"'namespaces[{index}]' (associated with \"\n f\"{namespace._RENDER_CLS.__name__!r}) is incompatible with \"\n f\"{render_cls.__name__!r} \"\n )\n namespaces_dict[namespace._RENDER_CLS] = namespace\n\n super().__init__(render_cls, namespaces_dict)\n\n if intern:\n type(self)._interned[render_cls] = self\n\n def __init_subclass__(cls, **kwargs: Any) -> None:\n cls._interned = {}\n super().__init_subclass__(**kwargs)\n\n def __contains__(self, namespace: ArgsNamespace) -> bool:\n \"\"\"Checks if a render argument namespace is contained in this set of render\n arguments.\n\n Args:\n namespace: A render argument namespace.\n\n Returns:\n ``True`` if the given namespace is equal to any of the namespaces\n contained in this set of render arguments. Otherwise, ``False``.\n \"\"\"\n return None is not self._namespaces.get(namespace._RENDER_CLS) == namespace\n\n def __eq__(self, other: object) -> bool:\n \"\"\"Compares this set of render arguments with another.\n\n Args:\n other: Another set of render arguments.\n\n Returns:\n ``True`` if both are associated with the same :term:`render class`\n and have equal argument values. Otherwise, ``False``.\n \"\"\"\n if isinstance(other, RenderArgs):\n return (\n self is other\n or self.render_cls is other.render_cls\n and self._namespaces == other._namespaces\n )\n\n return NotImplemented\n\n def __getitem__(self, render_cls: type[Renderable]) -> Any:\n \"\"\"Returns a constituent namespace.\n\n Args:\n render_cls: A :term:`render class` of which :py:attr:`render_cls` is a\n subclass (which may be :py:attr:`render_cls` itself) and which has\n render arguments.\n\n Returns:\n The constituent namespace associated with *render_cls*.\n\n Raises:\n TypeError: *render_cls* is not a render class.\n ValueError: :py:attr:`render_cls` is not a subclass of *render_cls*.\n NoArgsNamespaceError: *render_cls* has no render arguments.\n\n NOTE:\n The return type hint is :py:class:`~typing.Any` only for compatibility\n with static type checking, as this aspect of the interface seems too\n dynamic to be correctly expressed with the exisiting type system.\n\n Regardless, the return value is guaranteed to always be an instance\n of a render argument namespace class associated with *render_cls*.\n For instance, the following would always be valid for\n :py:class:`~term_image.renderable.Renderable`::\n\n renderable_args: RenderableArgs = render_args[Renderable]\n\n and similar idioms are encouraged to be used for other render classes.\n \"\"\"\n try:\n return self._namespaces[render_cls]\n except TypeError:\n raise arg_type_error(\"render_cls\", render_cls) from None\n except KeyError:\n if not isinstance(render_cls, RenderableMeta):\n raise arg_type_error(\"render_cls\", render_cls) from None\n\n if issubclass(self.render_cls, render_cls):\n raise NoArgsNamespaceError(\n f\"{render_cls.__name__!r} has no render arguments\"\n ) from None\n\n raise ValueError(\n f\"{self.render_cls.__name__!r} is not a subclass of \"\n f\"{render_cls.__name__!r}\"\n ) from None\n\n def __hash__(self) -> int:\n \"\"\"Computes the hash of the render arguments.\n\n Returns:\n The computed hash.\n\n IMPORTANT:\n Like tuples, an instance is hashable if and only if the constituent\n namespaces are hashable.\n \"\"\"\n # Namespaces are always in the same order, wrt their respective associated\n # render classes, for all instances associated with the same render class.\n return hash((self.render_cls, tuple(self._namespaces.values())))\n\n def __iter__(self) -> Iterator[ArgsNamespace]:\n \"\"\"Returns an iterator that yields the constituent namespaces.\n\n Returns:\n An iterator that yields the constituent namespaces.\n\n WARNING:\n The number and order of namespaces is guaranteed to be the same across all\n instances associated [#ra-ass]_ with the same :term:`render class` but\n beyond this, should not be relied upon as the details (such as the\n specific number or order) may change without notice.\n\n The order is an implementation detail of the Renderable API and the number\n should be considered alike with respect to the associated render class.\n \"\"\"\n return iter(self._namespaces.values())\n\n def __repr__(self) -> str:\n return \"\".join(\n (\n f\"{type(self).__name__}({self.render_cls.__name__}\",\n \", \" if self._namespaces else \"\",\n \", \".join(map(repr, self._namespaces.values())),\n \")\",\n )\n )\n\n # Public Methods ===========================================================\n\n def convert(self, render_cls: type[Renderable]) -> RenderArgs:\n \"\"\"Converts the set of render arguments to one for a related render class.\n\n Args:\n render_cls: A :term:`render class` of which :py:attr:`render_cls` is a\n parent or child (which may be :py:attr:`render_cls` itself).\n\n Returns:\n A set of render arguments associated [#ra-ass]_ with *render_cls* and\n initialized with all constituent namespaces (of this set of render\n arguments, *self*) that are compatible [#an-com]_ with *render_cls*.\n\n Raises:\n ValueError: *render_cls* is not a parent or child of :py:attr:`render_cls`.\n \"\"\"\n if render_cls is self.render_cls:\n return self\n\n if issubclass(render_cls, self.render_cls):\n return RenderArgs(render_cls, self)\n\n if issubclass(self.render_cls, render_cls):\n render_cls_args_mro = render_cls._ALL_DEFAULT_ARGS\n return RenderArgs(\n render_cls,\n *[\n namespace\n for cls, namespace in self._namespaces.items()\n if cls in render_cls_args_mro\n ],\n )\n\n raise ValueError(\n f\"{render_cls.__name__!r} is not a parent or child of \"\n f\"{self.render_cls.__name__!r}\"\n )\n\n @overload\n def update(\n self,\n namespace: ArgsNamespace,\n /,\n *namespaces: ArgsNamespace,\n ) -> RenderArgs: ...\n\n @overload\n def update(\n self,\n render_cls: type[Renderable],\n /,\n **fields: Any,\n ) -> RenderArgs: ...\n\n def update(\n self,\n render_cls_or_namespace: type[Renderable] | ArgsNamespace,\n /,\n *namespaces: ArgsNamespace,\n **fields: Any,\n ) -> RenderArgs:\n \"\"\"update(namespace, /, *namespaces) -> RenderArgs\n update(render_cls, /, **fields) -> RenderArgs\n\n Replaces or updates render argument namespaces.\n\n Args:\n namespace (ArgsNamespace): Prepended to *namespaces*.\n namespaces: Render argument namespaces compatible [#an-com]_ with\n :py:attr:`render_cls`.\n\n .. note:: If multiple namespaces associated with the same :term:`render\n class` are given, the last of them takes precedence.\n\n render_cls (type[Renderable]): A :term:`render class` of which\n :py:attr:`render_cls` is a subclass (which may be :py:attr:`render_cls`\n itself) and which has render arguments.\n fields: Render argument fields.\n\n The keywords must be names of render argument fields for *render_cls*.\n\n Returns:\n For the **first** form, an instance with the namespaces for the respective\n associated :term:`render classes` of the given namespaces replaced.\n\n For the **second** form, an instance with the given render argument fields\n for *render_cls* updated, if any.\n\n Raises:\n TypeError: The arguments given do not conform to any of the expected forms.\n\n Propagates exceptions raised by:\n\n * the class constructor, for the **first** form.\n * :py:meth:`__getitem__` and :py:meth:`ArgsNamespace.update()\n `, for the **second** form.\n \"\"\"\n if isinstance(render_cls_or_namespace, RenderableMeta):\n if namespaces:\n raise TypeError(\n \"No other positional argument is expected when the first argument \"\n \"is a render class\"\n )\n render_cls = render_cls_or_namespace\n else:\n if fields:\n raise TypeError(\n \"No keyword argument is expected when the first argument is \"\n \"a render argument namespace\"\n )\n render_cls = None\n namespaces = (render_cls_or_namespace, *namespaces)\n\n return RenderArgs(\n self.render_cls,\n self,\n *((self[render_cls].update(**fields),) if render_cls else namespaces),\n )", "n_imports_parsed": 14, "n_files_resolved": 7, "n_chars_extracted": 15637}, "tests/render/test_iterator.py::748": {"resolved_imports": ["src/term_image/geometry.py", "src/term_image/padding.py", "src/term_image/render/_iterator.py", "src/term_image/renderable/_enum.py", "src/term_image/renderable/_renderable.py", "src/term_image/renderable/_types.py"], "used_names": ["FrameDuration", "RenderIterator"], "enclosing_function": "test_iteration", "extracted_code": "# Source: src/term_image/render/_iterator.py\nclass RenderIterator:\n \"\"\"An iterator for efficient iteration over :term:`rendered` frames of an\n :term:`animated` renderable.\n\n Args:\n renderable: An animated renderable.\n render_args: Render arguments.\n padding: :term:`Render output` padding.\n loops: The number of times to go over all frames.\n\n * ``< 0`` -> loop infinitely.\n * ``0`` -> invalid.\n * ``> 0`` -> loop the given number of times.\n\n .. note::\n The value is ignored and taken to be ``1`` (one), if *renderable* has\n :py:class:`~term_image.renderable.FrameCount.INDEFINITE` frame count.\n\n cache: Determines if :term:`rendered` frames are cached.\n\n If the value is ``True`` or a positive integer greater than or equal to the\n frame count of *renderable*, caching is enabled. Otherwise i.e ``False`` or\n a positive integer less than the frame count, caching is disabled.\n\n .. note::\n The value is ignored and taken to be ``False``, if *renderable* has\n :py:class:`~term_image.renderable.FrameCount.INDEFINITE` frame count.\n\n Raises:\n ValueError: An argument has an invalid value.\n IncompatibleRenderArgsError: Incompatible render arguments.\n\n The iterator yields a :py:class:`~term_image.renderable.Frame` instance on every\n iteration.\n\n NOTE:\n * Seeking the underlying renderable\n (via :py:meth:`Renderable.seek() `)\n does not affect an iterator, use :py:meth:`RenderIterator.seek` instead.\n Likewise, the iterator does not modify the underlying renderable's current\n frame number.\n * Changes to the underlying renderable's :term:`render size` does not affect\n an iterator's :term:`render outputs`, use :py:meth:`set_render_size` instead.\n * Changes to the underlying renderable's\n :py:attr:`~term_image.renderable.Renderable.frame_duration` does not affect\n the value yiedled by an iterator, the value when initializing the iterator\n is what it will use.\n * :py:exc:`StopDefiniteIterationError` is raised when a renderable with\n *definite* frame count raises :py:exc:`StopIteration` when rendering a frame.\n\n .. seealso::\n\n :py:meth:`Renderable.__iter__() `\n Renderables are iterable\n\n :ref:`render-iterator-ext-api`\n :py:class:`RenderIterator`\\\\ 's Extension API\n \"\"\"\n\n # Instance Attributes ======================================================\n\n loop: int\n \"\"\"Iteration loop countdown\n\n * A negative integer, if iteration is infinite.\n * Otherwise, the current iteration loop countdown value.\n\n * Starts from the value of the *loops* constructor argument,\n * decreases by one upon rendering the first frame of every loop after the\n first,\n * and ends at zero after the iterator is exhausted.\n\n NOTE:\n Modifying this doesn't affect the iterator.\n \"\"\"\n\n _cached: bool\n _closed: bool\n _finalize_data: bool\n _iterator: Generator[Frame, None, None]\n _loops: int\n _padding: Padding\n _padded_size: Size\n _render_args: RenderArgs\n _render_data: RenderData\n _renderable: Renderable\n _renderable_data: RenderableData\n\n # Special Methods ==========================================================\n\n def __init__(\n self,\n renderable: Renderable,\n render_args: RenderArgs | None = None,\n padding: Padding = ExactPadding(),\n loops: int = 1,\n cache: bool | int = 100,\n ) -> None:\n self._init(renderable, render_args, padding, loops, cache)\n self._iterator, self._padding = renderable._init_render_(\n self._iterate, render_args, padding, iteration=True, finalize=False\n )\n self._finalize_data = True\n next(self._iterator)\n\n def __del__(self) -> None:\n try:\n self.close()\n except AttributeError:\n pass\n\n def __iter__(self) -> Self:\n return self\n\n def __next__(self) -> Frame:\n try:\n return next(self._iterator)\n except StopIteration:\n self.close()\n raise StopIteration(\"Iteration has ended\") from None\n except AttributeError:\n if self._closed:\n raise StopIteration(\"This iterator has been finalized\") from None\n else:\n self.close()\n raise\n except Exception:\n self.close()\n raise\n\n def __repr__(self) -> str:\n return (\n f\"<{type(self).__name__}: \"\n f\"type(renderable)={type(self._renderable).__name__}, \"\n f\"frame_count={self._renderable.frame_count}, loops={self._loops}, \"\n f\"loop={self.loop}, cached={self._cached}>\"\n )\n\n # Public Methods ===========================================================\n\n def close(self) -> None:\n \"\"\"Finalizes the iterator and releases resources used.\n\n NOTE:\n This method is automatically called when the iterator is exhausted or\n garbage-collected but it's recommended to call it manually if iteration\n is ended prematurely (i.e before the iterator itself is exhausted),\n especially if frames are cached.\n\n This method is safe for multiple invocations.\n \"\"\"\n if not self._closed:\n self._iterator.close()\n del self._iterator\n if self._finalize_data:\n self._render_data.finalize()\n del self._render_data\n self._closed = True\n\n def seek(self, offset: int, whence: Seek = Seek.START) -> None:\n \"\"\"Sets the frame to be rendered on the next iteration, without affecting\n the loop count.\n\n Args:\n offset: Frame offset (relative to *whence*).\n whence: Reference position for *offset*.\n\n Raises:\n FinalizedIteratorError: The iterator has been finalized.\n ValueError: *offset* is out of range.\n\n The value range for *offset* depends on the\n :py:attr:`~term_image.renderable.Renderable.frame_count` of the underlying\n renderable and *whence*:\n\n .. list-table:: *definite* frame count\n :align: left\n :header-rows: 1\n :width: 90%\n :widths: auto\n\n * - *whence*\n - Valid value range for *offset*\n\n * - :py:attr:`~term_image.renderable.Seek.START`\n - ``0`` <= *offset*\n < :py:attr:`~term_image.renderable.Renderable.frame_count`\n * - :py:attr:`~term_image.renderable.Seek.CURRENT`\n - -*next_frame_number* [#ri-nf]_ <= *offset*\n < :py:attr:`~term_image.renderable.Renderable.frame_count`\n - *next_frame_number*\n * - :py:attr:`~term_image.renderable.Seek.END`\n - -:py:attr:`~term_image.renderable.Renderable.frame_count` < *offset*\n <= ``0``\n\n .. list-table:: :py:attr:`~term_image.renderable.FrameCount.INDEFINITE` frame\n count\n :align: left\n :header-rows: 1\n :width: 90%\n :widths: auto\n\n * - *whence*\n - Valid value range for *offset*\n\n * - :py:attr:`~term_image.renderable.Seek.START`\n - ``0`` <= *offset*\n * - :py:attr:`~term_image.renderable.Seek.CURRENT`\n - *any value*\n * - :py:attr:`~term_image.renderable.Seek.END`\n - *offset* <= ``0``\n\n NOTE:\n If the underlying renderable has *definite* frame count, seek operations\n have **immeditate** effect. Hence, multiple consecutive seek operations,\n starting with any kind and followed by one or more with *whence* =\n :py:attr:`~term_image.renderable.Seek.CURRENT`, between any two\n consecutive renders have a **cumulative** effect. In particular, any seek\n operation with *whence* = :py:attr:`~term_image.renderable.Seek.CURRENT`\n is relative to the frame to be rendered next [#ri-nf]_.\n\n .. collapse:: Example\n\n >>> animated_renderable.frame_count\n 10\n >>> render_iter = RenderIterator(animated_renderable) # next = 0\n >>> render_iter.seek(5) # next = 5\n >>> next(render_iter).number # next = 5 + 1 = 6\n 5\n >>> # cumulative\n >>> render_iter.seek(2, Seek.CURRENT) # next = 6 + 2 = 8\n >>> render_iter.seek(-4, Seek.CURRENT) # next = 8 - 4 = 4\n >>> next(render_iter).number # next = 4 + 1 = 5\n 4\n >>> # cumulative\n >>> render_iter.seek(7) # next = 7\n >>> render_iter.seek(1, Seek.CURRENT) # next = 7 + 1 = 8\n >>> render_iter.seek(-5, Seek.CURRENT) # next = 8 - 5 = 3\n >>> next(render_iter).number # next = 3 + 1 = 4\n 3\n >>> # NOT cumulative\n >>> render_iter.seek(3, Seek.CURRENT) # next = 4 + 3 = 7\n >>> render_iter.seek(2) # next = 2\n >>> next(render_iter).number # next = 2 + 1 = 3\n 2\n\n On the other hand, if the underlying renderable has\n :py:attr:`~term_image.renderable.FrameCount.INDEFINITE` frame count, seek\n operations don't take effect **until the next render**. Hence, multiple\n consecutive seek operations between any two consecutive renders do **not**\n have a **cumulative** effect; rather, only **the last one** takes effect.\n In particular, any seek operation with *whence* =\n :py:attr:`~term_image.renderable.Seek.CURRENT` is relative to the frame\n after that which was rendered last.\n\n .. collapse:: Example\n\n >>> animated_renderable.frame_count is FrameCount.INDEFINITE\n True\n >>> # iterating normally without seeking\n >>> [frame.render_output for frame in animated_renderable]\n ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', ...]\n >>>\n >>> # Assuming the renderable implements all kinds of seek operations\n >>> render_iter = RenderIterator(animated_renderable) # next = 0\n >>> render_iter.seek(5) # next = 5\n >>> next(render_iter).render_output # next = 5 + 1 = 6\n '5'\n >>> render_iter.seek(2, Seek.CURRENT) # next = 6 + 2 = 8\n >>> render_iter.seek(-4, Seek.CURRENT) # next = 6 - 4 = 2\n >>> next(render_iter).render_output # next = 2 + 1 = 3\n '2'\n >>> render_iter.seek(7) # next = 7\n >>> render_iter.seek(3, Seek.CURRENT) # next = 3 + 3 = 6\n >>> next(render_iter).render_output # next = 6 + 1 = 7\n '6'\n\n A renderable with :py:attr:`~term_image.renderable.FrameCount.INDEFINITE`\n frame count may not support/implement all kinds of seek operations or any\n at all. If the underlying renderable doesn't support/implement a given\n seek operation, the seek operation should simply have no effect on\n iteration i.e the next frame should be the one after that which was\n rendered last. See each :term:`render class` that implements\n :py:attr:`~term_image.renderable.FrameCount.INDEFINITE` frame count for\n the seek operations it supports and any other specific related details.\n \"\"\"\n if self._closed:\n raise FinalizedIteratorError(\"This iterator has been finalized\") from None\n\n frame_count = self._renderable.frame_count\n renderable_data = self._renderable_data\n if frame_count is FrameCount.INDEFINITE:\n if whence is Seek.START and offset < 0 or whence is Seek.END and offset > 0:\n raise arg_value_error_range(\"offset\", offset, f\"whence={whence.name}\")\n renderable_data.update(frame_offset=offset, seek_whence=whence)\n else:\n frame = (\n offset\n if whence is Seek.START\n else (\n renderable_data.frame_offset + offset\n if whence is Seek.CURRENT\n else frame_count + offset - 1\n )\n )\n if not 0 <= frame < frame_count:\n raise arg_value_error_range(\n \"offset\",\n offset,\n (\n f\"whence={whence.name}, frame_count={frame_count}\"\n + (\n f\", next={renderable_data.frame_offset}\"\n if whence is Seek.CURRENT\n else \"\"\n )\n ),\n )\n renderable_data.update(frame_offset=frame, seek_whence=Seek.START)\n\n def set_frame_duration(self, duration: int | FrameDuration) -> None:\n \"\"\"Sets the frame duration.\n\n Args:\n duration: Frame duration (see\n :py:attr:`~term_image.renderable.Renderable.frame_duration`).\n\n Raises:\n FinalizedIteratorError: The iterator has been finalized.\n ValueError: *duration* is out of range.\n\n NOTE:\n Takes effect from the next [#ri-nf]_ rendered frame.\n \"\"\"\n if self._closed:\n raise FinalizedIteratorError(\"This iterator has been finalized\") from None\n\n if isinstance(duration, int) and duration <= 0:\n raise arg_value_error_range(\"duration\", duration)\n\n self._renderable_data.duration = duration\n\n def set_padding(self, padding: Padding) -> None:\n \"\"\"Sets the :term:`render output` padding.\n\n Args:\n padding: Render output padding.\n\n Raises:\n FinalizedIteratorError: The iterator has been finalized.\n\n NOTE:\n Takes effect from the next [#ri-nf]_ rendered frame.\n \"\"\"\n if self._closed:\n raise FinalizedIteratorError(\"This iterator has been finalized\") from None\n\n self._padding = (\n padding.resolve(get_terminal_size())\n if isinstance(padding, AlignedPadding) and padding.relative\n else padding\n )\n self._padded_size = padding.get_padded_size(self._renderable_data.size)\n\n def set_render_args(self, render_args: RenderArgs) -> None:\n \"\"\"Sets the render arguments.\n\n Args:\n render_args: Render arguments.\n\n Raises:\n FinalizedIteratorError: The iterator has been finalized.\n IncompatibleRenderArgsError: Incompatible render arguments.\n\n NOTE:\n Takes effect from the next [#ri-nf]_ rendered frame.\n \"\"\"\n if self._closed:\n raise FinalizedIteratorError(\"This iterator has been finalized\") from None\n\n render_cls = type(self._renderable)\n self._render_args = (\n render_args\n if render_args.render_cls is render_cls\n # Validate compatibility (and convert, if compatible)\n else RenderArgs(render_cls, render_args)\n )\n\n def set_render_size(self, render_size: Size) -> None:\n \"\"\"Sets the :term:`render size`.\n\n Args:\n render_size: Render size.\n\n Raises:\n FinalizedIteratorError: The iterator has been finalized.\n\n NOTE:\n Takes effect from the next [#ri-nf]_ rendered frame.\n \"\"\"\n if self._closed:\n raise FinalizedIteratorError(\"This iterator has been finalized\") from None\n\n self._renderable_data.size = render_size\n self._padded_size = self._padding.get_padded_size(render_size)\n\n # Extension methods ========================================================\n\n @classmethod\n def _from_render_data_(\n cls,\n renderable: Renderable,\n render_data: RenderData,\n render_args: RenderArgs | None = None,\n padding: Padding = ExactPadding(),\n *args: Any,\n finalize: bool = True,\n **kwargs: Any,\n ) -> Self:\n \"\"\"Constructs an iterator with pre-generated render data.\n\n Args:\n renderable: An animated renderable.\n render_data: Render data.\n render_args: Render arguments.\n args: Other positional arguments accepted by the class constructor.\n finalize: Whether *render_data* is finalized along with the iterator.\n kwargs: Other keyword arguments accepted by the class constructor.\n\n Returns:\n A new iterator instance.\n\n Raises the same exceptions as the class constructor.\n\n NOTE:\n *render_data* may be modified by the iterator or the underlying renderable.\n \"\"\"\n new = cls.__new__(cls)\n new._init(renderable, render_args, padding, *args, **kwargs)\n\n if render_data.render_cls is not type(renderable):\n raise arg_value_error_msg(\n \"Invalid render data for renderable of type \"\n f\"{type(renderable).__name__!r}\",\n render_data,\n )\n if render_data.finalized:\n raise ValueError(\"The render data has been finalized\")\n if not render_data[Renderable].iteration:\n raise arg_value_error_msg(\"Invalid render data for iteration\", render_data)\n\n if not (render_args and render_args.render_cls is type(renderable)):\n # Validate compatibility (and convert, if compatible)\n render_args = RenderArgs(type(renderable), render_args)\n\n new._padding = (\n padding.resolve(get_terminal_size())\n if isinstance(padding, AlignedPadding) and padding.relative\n else padding\n )\n new._iterator = new._iterate(render_data, render_args)\n new._finalize_data = finalize\n next(new._iterator)\n\n return new\n\n # Private Methods ==========================================================\n\n def _init(\n self,\n renderable: Renderable,\n render_args: RenderArgs | None = None,\n padding: Padding = ExactPadding(),\n loops: int = 1,\n cache: bool | int = 100,\n ) -> None:\n \"\"\"Partially initializes an instance.\n\n Performs the part of the initialization common to all constructors.\n \"\"\"\n if not renderable.animated:\n raise arg_value_error_msg(\"'renderable' is not animated\", renderable)\n if not loops:\n raise arg_value_error(\"loops\", loops)\n if False is not cache <= 0:\n raise arg_value_error_range(\"cache\", cache)\n\n indefinite = renderable.frame_count is FrameCount.INDEFINITE\n self._closed = False\n self._renderable = renderable\n self.loop = self._loops = 1 if indefinite else loops\n self._cached = (\n False\n if indefinite\n else (\n cache\n # `isinstance` is much costlier on failure and `bool` cannot be\n # subclassed\n if type(cache) is bool\n else renderable.frame_count <= cache # type: ignore[operator]\n )\n )\n\n def _iterate(\n self,\n render_data: RenderData,\n render_args: RenderArgs,\n ) -> Generator[Frame, None, None]:\n \"\"\"Performs the actual render iteration operation.\"\"\"\n # Instance init completion\n self._render_data = render_data\n self._render_args = render_args\n renderable_data: RenderableData\n self._renderable_data = renderable_data = render_data[Renderable]\n self._padded_size = self._padding.get_padded_size(renderable_data.size)\n\n # Setup\n renderable = self._renderable\n frame_count = renderable.frame_count\n if frame_count is FrameCount.INDEFINITE:\n frame_count = 1\n definite = frame_count > 1\n loop = self.loop\n CURRENT = Seek.CURRENT\n renderable_data.frame_offset = 0\n cache: list[tuple[Frame | None, Size, int | FrameDuration, RenderArgs]] | None\n cache = (\n [(None,) * 4] * frame_count # type: ignore[list-item]\n if self._cached\n else None\n )\n\n # Initial dummy frame, yielded but unused by initializers.\n # Acts as a breakpoint between completion of instance init + iteration setup\n # and render iteration.\n yield DUMMY_FRAME\n\n # Render iteration\n frame_no = renderable_data.frame_offset * definite\n while loop:\n while frame_no < frame_count:\n if cache:\n frame = (cache_entry := cache[frame_no])[0]\n frame_details = cache_entry[1:]\n else:\n frame = None\n\n if not frame or frame_details != (\n renderable_data.size,\n renderable_data.duration,\n self._render_args,\n ):\n # NOTE: Re-render is required even when only `duration` changes\n # and the new value is *static* because frame duration may affect\n # the render output of some renderables.\n try:\n frame = renderable._render_(render_data, self._render_args)\n except StopIteration as exc:\n if definite:\n raise StopDefiniteIterationError(\n f\"{renderable!r} with definite frame count raised \"\n \"`StopIteration` when rendering a frame\"\n ) from exc\n self.loop = 0\n return\n\n if cache:\n cache[frame_no] = (\n frame,\n renderable_data.size,\n renderable_data.duration,\n self._render_args,\n )\n\n if self._padded_size != frame.render_size:\n frame = Frame(\n frame.number,\n frame.duration,\n self._padded_size,\n self._padding.pad(frame.render_output, frame.render_size),\n )\n\n if definite:\n renderable_data.frame_offset += 1\n elif (\n renderable_data.frame_offset\n or renderable_data.seek_whence != CURRENT\n ): # was seeked\n renderable_data.update(frame_offset=0, seek_whence=CURRENT)\n\n yield frame\n\n if definite:\n frame_no = renderable_data.frame_offset\n\n # INDEFINITE can never reach here\n frame_no = renderable_data.frame_offset = 0\n if loop > 0: # Avoid infinitely large negative numbers\n self.loop = loop = loop - 1\n\n\n# Source: src/term_image/renderable/_enum.py\nclass FrameDuration(Enum):\n \"\"\"Frame duration enumeration\n\n .. seealso:: :py:attr:`~term_image.renderable.Renderable.frame_duration`.\n \"\"\"\n\n DYNAMIC = auto()\n \"\"\"Dynamic frame duration\n\n The duration of each frame is determined at render-time.\n\n :meta hide-value:\n \"\"\"", "n_imports_parsed": 9, "n_files_resolved": 6, "n_chars_extracted": 23690}, "tests/test_color.py::47": {"resolved_imports": ["src/term_image/color.py"], "used_names": ["Color"], "enclosing_function": "test_is_tuple", "extracted_code": "# Source: src/term_image/color.py\nclass Color(_DummyColor):\n \"\"\"A color.\n\n Args:\n r: The red channel.\n g: The green channel.\n b: The blue channel.\n a: The alpha channel (opacity).\n\n Raises:\n ValueError: The value of a channel is not within the valid range.\n\n NOTE:\n The valid value range for all channels is 0 to 255, both inclusive.\n\n TIP:\n This class is a :py:class:`~typing.NamedTuple` of four fields.\n\n WARNING:\n In the case of multiple inheritance i.e if subclassing this class along with\n other classes, this class should appear last (i.e to the far right) in the\n base class list.\n \"\"\"\n\n __slots__ = ()\n\n # Overrides these descriptors in order to speed up attribute resolution and to\n # simplify auto documentation.\n r: int = _DummyColor.r\n r.__doc__ = \"\"\"The red channel\"\"\"\n\n g: int = _DummyColor.g\n g.__doc__ = \"\"\"The green channel\"\"\"\n\n b: int = _DummyColor.b\n b.__doc__ = \"\"\"The blue channel\"\"\"\n\n a: int = _DummyColor.a\n a.__doc__ = \"\"\"The alpha channel (opacity)\"\"\"\n\n def __new__(cls, r: int, g: int, b: int, a: int = 255) -> Self:\n # Only the 8 LSb may be set for any value within the range [0, 255].\n # `x & ~255` unsets the 8 LSb. Hence, if the result is non-zero (i.e any\n # of the bits above the lowest 8 is set), it implies `x` is out of range.\n #\n # Actually benchmarked *this* against the \"simpler\" logically-negated chained\n # comparison (i.e `0 <= x <= 255`) and *this* was significantly faster for all\n # cases i.e within, on the boundaries, and outside (on both sides).\n if (r | g | b | a) & ~255: # First test to see if *any* is out of range\n if r & ~255:\n raise arg_value_error_range(\"r\", r)\n if g & ~255:\n raise arg_value_error_range(\"g\", g)\n if b & ~255:\n raise arg_value_error_range(\"b\", b)\n # There's no point checking since at least one is out of range\n raise arg_value_error_range(\"a\", a)\n\n # Using `tuple` directly instead of `super()` for performance\n return tuple.__new__(cls, (r, g, b, a))\n\n @property\n def hex(self) -> str:\n \"\"\"Converts the color to its RGBA hexadecimal representation.\n\n Returns:\n The RGBA hex color string, starting with the ``#`` character i.e\n ``#rrggbbaa``.\n\n Each channel is represented by two **lowercase** hex digits ranging from\n ``00`` to ``ff``.\n \"\"\"\n return \"#%02x%02x%02x%02x\" % self\n\n @property\n def rgb(self) -> tuple[int, int, int]:\n \"\"\"Extracts the R, G and B channels of the color.\n\n Returns:\n A 3-tuple containing the red, green and blue channel values.\n \"\"\"\n return self[:3]\n\n @property\n def rgb_hex(self) -> str:\n \"\"\"Converts the color to its RGB hexadecimal representation.\n\n Returns:\n The RGB hex color string, starting with the ``#`` character i.e ``#rrggbb``.\n\n Each channel is represented by two **lowercase** hex digits ranging from\n ``00`` to ``ff``.\n \"\"\"\n return \"#%02x%02x%02x\" % self[:3]\n\n @classmethod\n def from_hex(cls, color: str) -> Self:\n \"\"\"Creates a new instance from a hexadecimal color string.\n\n Args:\n color: A **case-insensitive** RGB or RGBA hex color string, **optionally**\n starting with the ``#`` (pound) character i.e ``[#]rrggbb[aa]``.\n\n Returns:\n A new instance representing the given hex color string.\n\n Raises:\n ValueError: Invalid hex color string.\n\n NOTE:\n For an RGB hex color string, the value of A (the alpha channel) is\n taken to be 255.\n \"\"\"\n if not (match := _RGBA_HEX_RE.fullmatch(color)):\n raise ValueError(f\"Invalid hex color string (got: {color!r})\")\n\n return tuple.__new__(cls, [int(x, 16) for x in match.groups(\"ff\")])\n\n @classmethod\n def _new(cls, r: int, g: int, b: int, a: int = 255) -> Self:\n \"\"\"Alternate constructor for internal use only.\"\"\"\n return tuple.__new__(cls, (r, g, b, a))", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 4255}, "tests/test_image/test_base.py::93": {"resolved_imports": ["src/term_image/__init__.py", "src/term_image/_ctlseqs.py", "src/term_image/exceptions.py", "src/term_image/image/block.py", "src/term_image/image/common.py"], "used_names": ["BlockImage"], "enclosing_function": "test_init_animated", "extracted_code": "# Source: src/term_image/image/block.py\nclass BlockImage(TextImage):\n \"\"\"A render style using unicode half blocks and direct-color colour escape\n sequences.\n\n See :py:class:`TextImage` for the description of the constructor.\n \"\"\"\n\n @classmethod\n def is_supported(cls):\n if cls._supported is None:\n COLORTERM = os.environ.get(\"COLORTERM\") or \"\"\n TERM = os.environ.get(\"TERM\") or \"\"\n cls._supported = (\n \"truecolor\" in COLORTERM or \"24bit\" in COLORTERM or \"256color\" in TERM\n )\n\n return cls._supported\n\n def _get_render_size(self) -> Tuple[int, int]:\n return tuple(map(mul, self.rendered_size, (1, 2)))\n\n @staticmethod\n def _pixels_cols(\n *, pixels: Optional[int] = None, cols: Optional[int] = None\n ) -> int:\n return pixels if pixels is not None else cols\n\n @staticmethod\n def _pixels_lines(\n *, pixels: Optional[int] = None, lines: Optional[int] = None\n ) -> int:\n return ceil(pixels / 2) if pixels is not None else lines * 2\n\n def _render_image(\n self,\n img: PIL.Image.Image,\n alpha: Union[None, float, str],\n *,\n frame: bool = False,\n split_cells: bool = False,\n ) -> str:\n # NOTE:\n # It's more efficient to write separate strings to the buffer separately\n # than concatenate and write together.\n\n def update_buffer():\n if alpha:\n no_alpha = False\n if a_cluster1 == 0 == a_cluster2:\n buf_write(SGR_DEFAULT)\n buf_write(blank * n)\n elif a_cluster1 == 0: # up is transparent\n buf_write(SGR_DEFAULT)\n buf_write(SGR_FG_DIRECT % cluster2)\n buf_write(lower_pixel * n)\n elif a_cluster2 == 0: # down is transparent\n buf_write(SGR_DEFAULT)\n buf_write(SGR_FG_DIRECT % cluster1)\n buf_write(upper_pixel * n)\n else:\n no_alpha = True\n\n if not alpha or no_alpha:\n r, g, b = cluster2\n # Kitty does not render BG colors equal to the default BG color\n if is_on_kitty and cluster2 == bg_color:\n r += r < 255 or -1\n buf_write(SGR_BG_DIRECT % (r, g, b))\n if cluster1 == cluster2:\n buf_write(blank * n)\n else:\n buf_write(SGR_FG_DIRECT % cluster1)\n buf_write(upper_pixel * n)\n\n buffer = io.StringIO()\n buf_write = buffer.write # Eliminate attribute resolution cost\n\n bg_color = get_fg_bg_colors()[1]\n is_on_kitty = self._is_on_kitty()\n if split_cells:\n blank = \" \\0\"\n lower_pixel = LOWER_PIXEL + \"\\0\"\n upper_pixel = UPPER_PIXEL + \"\\0\"\n else:\n blank = \" \"\n lower_pixel = LOWER_PIXEL\n upper_pixel = UPPER_PIXEL\n end_of_line = SGR_DEFAULT + \"\\n\"\n\n width, height = self._get_render_size()\n frame_img = img if frame else None\n img, rgb, a = self._get_render_data(img, alpha, round_alpha=True, frame=frame)\n alpha = img.mode == \"RGBA\"\n\n # clean up (ImageIterator uses one PIL image throughout)\n if frame_img is not img:\n self._close_image(img)\n\n rgb_pairs = (\n (\n zip(rgb[x : x + width], rgb[x + width : x + width * 2]),\n (rgb[x], rgb[x + width]),\n )\n for x in range(0, len(rgb), width * 2)\n )\n a_pairs = (\n (\n zip(a[x : x + width], a[x + width : x + width * 2]),\n (a[x], a[x + width]),\n )\n for x in range(0, len(a), width * 2)\n )\n\n row_no = 0\n # Two rows of pixels per line\n for (rgb_pair, (cluster1, cluster2)), (a_pair, (a_cluster1, a_cluster2)) in zip(\n rgb_pairs, a_pairs\n ):\n row_no += 2\n n = 0\n for (px1, px2), (a1, a2) in zip(rgb_pair, a_pair):\n # Color-code characters and write to buffer\n # when upper and/or lower pixel color/alpha-level changes\n if not (alpha and a1 == a_cluster1 == 0 == a_cluster2 == a2) and (\n px1 != cluster1\n or px2 != cluster2\n or alpha\n and (\n # From non-transparent to transparent\n a_cluster1 != a1 == 0\n or a_cluster2 != a2 == 0\n # From transparent to non-transparent\n or 0 == a_cluster1 != a1\n or 0 == a_cluster2 != a2\n )\n ):\n update_buffer()\n cluster1 = px1\n cluster2 = px2\n if alpha:\n a_cluster1 = a1\n a_cluster2 = a2\n n = 0\n n += 1\n\n update_buffer() # Rest of the line\n if split_cells:\n # Set the last \"\\0\" to be overwritten by the next byte\n buffer.seek(buffer.tell() - 1)\n if row_no < height: # last line not yet rendered\n buf_write(end_of_line)\n\n buf_write(SGR_DEFAULT) # Reset color after last line\n\n with buffer:\n return buffer.getvalue()", "n_imports_parsed": 16, "n_files_resolved": 5, "n_chars_extracted": 5566}, "tests/renderable/test_renderable.py::1461": {"resolved_imports": ["src/term_image/_ctlseqs.py", "src/term_image/geometry.py", "src/term_image/padding.py", "src/term_image/renderable/_enum.py", "src/term_image/renderable/_exceptions.py", "src/term_image/renderable/_renderable.py", "src/term_image/renderable/_types.py"], "used_names": ["Renderable"], "enclosing_function": "test_zero_frames", "extracted_code": "# Source: src/term_image/renderable/_renderable.py\nclass Renderable(metaclass=RenderableMeta, _base=True):\n \"\"\"A renderable.\n\n Args:\n frame_count: Number of frames. If it's a\n\n * positive integer, the number of frames is as given.\n * :py:class:`~term_image.renderable.FrameCount` enum member, see the\n member's description.\n\n If equal to 1 (one), the renderable is non-animated.\n Otherwise, it is animated.\n\n frame_duration: The duration of a frame. If it's a\n\n * positive integer, it implies a static duration (in **milliseconds**)\n i.e the same duration applies to every frame.\n * :py:class:`~term_image.renderable.FrameDuration` enum member, see the\n member's description.\n\n This argument is ignored if *frame_count* equals 1 (one)\n i.e the renderable is non-animated.\n\n Raises:\n ValueError: An argument has an invalid value.\n\n ATTENTION:\n This is an abstract base class. Hence, only **concrete** subclasses can be\n instantiated.\n\n .. seealso::\n\n :ref:`renderable-ext-api`\n :py:class:`Renderable`\\\\ 's Extension API\n \"\"\"\n\n # Class Attributes =========================================================\n\n # Initialized by `RenderableMeta` and may be updated by `ArgsNamespaceMeta`\n Args: ClassVar[type[ArgsNamespace] | None]\n \"\"\":term:`Render class`\\\\ -specific render arguments.\n\n This is either:\n\n - a render argument namespace class (subclass of :py:class:`ArgsNamespace`)\n associated [#an-ass]_ with the render class, or\n - :py:data:`None`, if the render class has no render arguments.\n\n If this is a class, an instance of it (or a subclass thereof) is contained within\n any :py:class:`RenderArgs` instance associated [#ra-ass]_ with the render class or\n any of its subclasses. Also, an instance of this class (or a subclass of it) is\n returned by :py:meth:`render_args[render_cls]\n `; where *render_args* is\n an instance of :py:class:`~term_image.renderable.RenderArgs` as previously\n described and *render_cls* is the render class with which this namespace class\n is associated [#an-ass]_.\n\n .. collapse:: Example\n\n >>> class Foo(Renderable):\n ... pass\n ...\n ... class FooArgs(ArgsNamespace, render_cls=Foo):\n ... foo: str | None = None\n ...\n >>> Foo.Args is FooArgs\n True\n >>>\n >>> # default\n >>> foo_args = Foo.Args()\n >>> foo_args\n FooArgs(foo=None)\n >>> foo_args.foo is None\n True\n >>>\n >>> render_args = RenderArgs(Foo)\n >>> render_args[Foo]\n FooArgs(foo=None)\n >>>\n >>> # non-default\n >>> foo_args = Foo.Args(\"FOO\")\n >>> foo_args\n FooArgs(foo='FOO')\n >>> foo_args.foo\n 'FOO'\n >>>\n >>> render_args = RenderArgs(Foo, foo_args.update(foo=\"bar\"))\n >>> render_args[Foo]\n FooArgs(foo='bar')\n\n On the other hand, if this is :py:data:`None`, it implies the render class has no\n render arguments.\n\n .. collapse:: Example\n\n >>> class Bar(Renderable):\n ... pass\n ...\n >>> Bar.Args is None\n True\n >>> render_args = RenderArgs(Bar)\n >>> render_args[Bar]\n Traceback (most recent call last):\n ...\n NoArgsNamespaceError: 'Bar' has no render arguments\n \"\"\"\n\n # Initialized by `RenderableMeta` and may be updated by `DataNamespaceMeta`\n _Data_: ClassVar[type[DataNamespace] | None]\n \"\"\":term:`Render class`\\\\ -specific render data.\n\n This is either:\n\n - a render data namespace class (subclass of :py:class:`DataNamespace`)\n associated [#dn-ass]_ with the render class, or\n - :py:data:`None`, if the render class has no render data.\n\n If this is a class, an instance of it (or a subclass thereof) is contained within\n any :py:class:`RenderData` instance associated [#rd-ass]_ with the render class or\n any of its subclasses. Also, an instance of this class (or a subclass of it) is\n returned by :py:meth:`render_data[render_cls]\n `; where *render_data* is\n an instance of :py:class:`~term_image.renderable.RenderData` as previously\n described and *render_cls* is the render class with which this namespace class\n is associated [#dn-ass]_.\n\n .. collapse:: Example\n\n >>> class Foo(Renderable):\n ... pass\n ...\n ... class _Data_(DataNamespace, render_cls=Foo):\n ... foo: str | None\n ...\n >>> Foo._Data_ is FooData\n True\n >>>\n >>> foo_data = Foo._Data_()\n >>> foo_data\n >\n >>> foo_data.foo\n Traceback (most recent call last):\n ...\n UninitializedDataFieldError: The render data field 'foo' of 'Foo' has not \\\nbeen initialized\n >>>\n >>> foo_data.foo = \"FOO\"\n >>> foo_data\n \n >>> foo_data.foo\n 'FOO'\n >>>\n >>> render_data = RenderData(Foo)\n >>> render_data[Foo]\n >\n >>>\n >>> render_data[Foo].foo = \"bar\"\n >>> render_data[Foo]\n \n\n On the other hand, if this is :py:data:`None`, it implies the render class has no\n render data.\n\n .. collapse:: Example\n\n >>> class Bar(Renderable):\n ... pass\n ...\n >>> Bar._Data_ is None\n True\n >>>\n >>> render_data = RenderData(Bar)\n >>> render_data[Bar]\n Traceback (most recent call last):\n ...\n NoDataNamespaceError: 'Bar' has no render data\n\n .. seealso::\n\n :py:class:`~term_image.renderable.RenderableData`\n Render data for :py:class:`~term_image.renderable.Renderable`.\n \"\"\"\n\n _EXPORTED_ATTRS_: ClassVar[tuple[str, ...]]\n \"\"\"Exported attributes.\n\n This specifies class attributes defined by the class (not a parent) on itself\n **but not** its subclasses which should be exported to definitions of the class\n in subprocesses.\n\n These attributes are typically assigned using ``__class__.*`` within methods.\n\n NOTE:\n * Defining this is optional.\n * The attributes are exported for a class if and only if they are defined\n on that class when starting a subprocess.\n * The attributes are exported only for subprocesses started via\n :py:class:`multiprocessing.Process`.\n\n TIP:\n This can be used to export \"private\" attributes of the class across\n subprocesses.\n \"\"\"\n\n _EXPORTED_DESCENDANT_ATTRS_: ClassVar[tuple[str, ...]]\n \"\"\"Exported :term:`descendant` attributes.\n\n This specifies class attributes defined by the class (not a parent) on itself\n **and** its subclasses (i.e :term:`descendant` attributes) which should be exported\n to definitions of the class and its subclasses in subprocesses.\n\n These attributes are typically assigned using ``cls.*`` within class methods.\n\n This extends the exported descendant attributes of parent classes i.e all\n exported descendant attributes of a class are also exported for its subclasses.\n\n NOTE:\n * Defining this is optional.\n * The attributes are exported for a class if and only if they are defined\n on that class when starting a subprocess.\n * The attributes are exported only for subprocesses started via\n :py:class:`multiprocessing.Process`.\n\n TIP:\n This can be used to export \"private\" :term:`descendant` attributes of the\n class across subprocesses.\n \"\"\"\n\n _ALL_DEFAULT_ARGS: ClassVar[MappingProxyType[type[Renderable], ArgsNamespace]]\n _RENDER_DATA_MRO: ClassVar[MappingProxyType[type[Renderable], type[DataNamespace]]]\n _ALL_EXPORTED_ATTRS: ClassVar[tuple[str, ...]]\n\n # Instance Attributes ======================================================\n\n animated: bool\n \"\"\"``True`` if the renderable is :term:`animated`. Otherwise, ``False``.\"\"\"\n\n _frame: int\n _frame_count: int | FrameCount\n _frame_duration: int | FrameDuration\n\n # Special Methods ==========================================================\n\n def __init__(\n self,\n frame_count: int | FrameCount,\n frame_duration: int | FrameDuration,\n ) -> None:\n if isinstance(frame_count, int) and frame_count < 1:\n raise arg_value_error_range(\"frame_count\", frame_count)\n\n if frame_count != 1:\n if isinstance(frame_duration, int) and frame_duration <= 0:\n raise arg_value_error_range(\"frame_duration\", frame_duration)\n self._frame_duration = frame_duration\n\n self.animated = frame_count != 1\n self._frame_count = frame_count\n self._frame = 0\n\n def __iter__(self) -> term_image.render.RenderIterator:\n \"\"\"Returns a render iterator.\n\n Returns:\n A render iterator (with frame caching disabled and all other optional\n arguments to :py:class:`~term_image.render.RenderIterator` being the\n default values).\n\n Raises:\n NonAnimatedRenderableError: The renderable is non-animated.\n\n :term:`Animated` renderables are iterable i.e they can be used with various\n means of iteration such as the ``for`` statement and iterable unpacking.\n \"\"\"\n from term_image.render import RenderIterator\n\n try:\n return RenderIterator(self, cache=False)\n except ValueError:\n raise NonAnimatedRenderableError(\n \"Non-animated renderables are not iterable\"\n ) from None\n\n def __repr__(self) -> str:\n return f\"<{type(self).__name__}: frame_count={self._frame_count}>\"\n\n def __str__(self) -> str:\n \"\"\":term:`Renders` the current frame with default arguments and no padding.\n\n Returns:\n The frame :term:`render output`.\n\n Raises:\n RenderError: An error occurred during :term:`rendering`.\n \"\"\"\n return self._init_render_(self._render_)[0].render_output\n\n # Properties ===============================================================\n\n @property\n def frame_count(self) -> int | Literal[FrameCount.INDEFINITE]:\n \"\"\"Frame count\n\n GET:\n Returns either\n\n * the number of frames the renderable has, or\n * :py:attr:`~term_image.renderable.FrameCount.INDEFINITE`.\n \"\"\"\n if self._frame_count is FrameCount.POSTPONED:\n self._frame_count = self._get_frame_count_()\n\n return self._frame_count\n\n @property\n def frame_duration(self) -> int | FrameDuration:\n \"\"\"Frame duration\n\n GET:\n Returns\n\n * a positive integer, a static duration (in **milliseconds**) i.e the\n same duration applies to every frame; or\n * :py:attr:`~term_image.renderable.FrameDuration.DYNAMIC`.\n\n SET:\n If the value is\n\n * a positive integer, it implies a static duration (in **milliseconds**)\n i.e the same duration applies to every frame.\n * :py:attr:`~term_image.renderable.FrameDuration.DYNAMIC`, see the\n enum member's description.\n\n Raises:\n NonAnimatedRenderableError: The renderable is non-animated.\n \"\"\"\n try:\n return self._frame_duration\n except AttributeError:\n if not self.animated:\n raise NonAnimatedRenderableError(\n \"Non-animated renderables have no frame duration\"\n ) from None\n raise\n\n @frame_duration.setter\n def frame_duration(self, duration: int | FrameDuration) -> None:\n if not self.animated:\n raise NonAnimatedRenderableError(\n \"Cannot set frame duration for a non-animated renderable\"\n )\n\n if isinstance(duration, int) and duration <= 0:\n raise arg_value_error_range(\"frame_duration\", duration)\n\n self._frame_duration = duration\n\n @property\n def render_size(self) -> geometry.Size:\n \"\"\":term:`Render size`\n\n GET:\n Returns the size of the renderable's :term:`render output`.\n \"\"\"\n return self._get_render_size_()\n\n # Public Methods ===========================================================\n\n def draw(\n self,\n render_args: RenderArgs | None = None,\n padding: Padding = AlignedPadding(0, -2),\n *,\n animate: bool = True,\n loops: int = -1,\n cache: bool | int = 100,\n check_size: bool = True,\n allow_scroll: bool = False,\n hide_cursor: bool = True,\n echo_input: bool = False,\n ) -> None:\n \"\"\"Draws the current frame or an animation to standard output.\n\n Args:\n render_args: Render arguments.\n padding: :term:`Render output` padding.\n animate: Whether to enable animation for :term:`animated` renderables.\n If disabled, only the current frame is drawn.\n loops: See :py:class:`~term_image.render.RenderIterator`\n (applies to **animations only**).\n cache: See :py:class:`~term_image.render.RenderIterator`.\n (applies to **animations only**).\n check_size: Whether to validate the padded :term:`render size` of\n **non-animations**.\n allow_scroll: Whether to validate the padded :term:`render height` of\n **non-animations**. Ignored if *check_size* is ``False``.\n hide_cursor: Whether to hide the cursor **while drawing**.\n echo_input: Whether to display input **while drawing** (applies on **Unix\n only**).\n\n .. note::\n * If disabled (default), input is not read/consumed, it's just not\n displayed.\n * If enabled, echoed input may affect cursor positioning and\n therefore, the output (especially for animations).\n\n Raises:\n RenderSizeOutofRangeError: The padded :term:`render size` can not fit into\n the :term:`terminal size`.\n IncompatibleRenderArgsError: Incompatible render arguments.\n RenderError: An error occurred during :term:`rendering`.\n\n If *check_size* is ``True`` (or it's an animation),\n\n * the padded :term:`render width` must not be greater than the\n :term:`terminal width`.\n * and *allow_scroll* is ``False`` (or it's an animation), the padded\n :term:`render height` must not be greater than the :term:`terminal height`.\n\n NOTE:\n * *hide_cursor* and *echo_input* apply if and only if the output stream\n is connected to a terminal.\n * For animations (i.e animated renderables with *animate* = ``True``),\n the padded :term:`render size` is always validated.\n * Animations with **definite** frame count, **by default**, are infinitely\n looped but can be terminated with :py:data:`~signal.SIGINT`\n (``CTRL + C``), **without** raising :py:class:`KeyboardInterrupt`.\n \"\"\"\n animation = self.animated and animate\n output = sys.stdout\n not_echo_input = OS_IS_UNIX and not echo_input and output.isatty()\n hide_cursor = hide_cursor and output.isatty()\n\n # Validate size and get render data and args\n render_data: RenderData\n real_render_args: RenderArgs\n (render_data, real_render_args), padding = self._init_render_(\n lambda *args: args,\n render_args,\n padding,\n iteration=animation,\n finalize=False,\n check_size=animation or check_size,\n allow_scroll=not animation and allow_scroll,\n )\n\n if not_echo_input:\n output_fd = output.fileno()\n old_attr = termios.tcgetattr(output_fd)\n new_attr = termios.tcgetattr(output_fd)\n new_attr[3] &= ~termios.ECHO\n try:\n if hide_cursor:\n output.write(HIDE_CURSOR)\n if not_echo_input:\n termios.tcsetattr(output_fd, termios.TCSAFLUSH, new_attr)\n\n if animation:\n self._animate_(\n render_data, real_render_args, padding, loops, cache, output\n )\n else:\n frame = self._render_(render_data, real_render_args)\n padded_size = padding.get_padded_size(frame.render_size)\n render = (\n frame.render_output\n if frame.render_size == padded_size\n else padding.pad(frame.render_output, frame.render_size)\n )\n try:\n output.write(render)\n output.flush()\n except KeyboardInterrupt:\n self._handle_interrupted_draw_(\n render_data, real_render_args, output\n )\n raise\n finally:\n output.write(\"\\n\")\n if hide_cursor:\n output.write(SHOW_CURSOR)\n output.flush()\n if not_echo_input:\n termios.tcsetattr(output_fd, termios.TCSANOW, old_attr)\n render_data.finalize()\n\n def render(\n self,\n render_args: RenderArgs | None = None,\n padding: Padding = NO_PADDING,\n ) -> Frame:\n \"\"\":term:`Renders` the current frame.\n\n Args:\n render_args: Render arguments.\n padding: :term:`Render output` padding.\n\n Returns:\n The rendered frame.\n\n Raises:\n IncompatibleRenderArgsError: Incompatible render arguments.\n RenderError: An error occurred during :term:`rendering`.\n \"\"\"\n frame, padding = self._init_render_(self._render_, render_args, padding)\n padded_size = padding.get_padded_size(frame.render_size)\n\n return (\n frame\n if frame.render_size == padded_size\n else Frame(\n frame.number,\n frame.duration,\n padded_size,\n padding.pad(frame.render_output, frame.render_size),\n )\n )\n\n def seek(self, offset: int, whence: Seek = Seek.START) -> int:\n \"\"\"Sets the current frame number.\n\n Args:\n offset: Frame offset (relative to *whence*).\n whence: Reference position for *offset*.\n\n Returns:\n The new current frame number.\n\n Raises:\n IndefiniteSeekError: The renderable has\n :py:attr:`~term_image.renderable.FrameCount.INDEFINITE` frame count.\n ValueError: *offset* is out of range.\n\n The value range for *offset* depends on *whence*:\n\n .. list-table::\n :align: left\n :header-rows: 1\n :widths: auto\n\n * - *whence*\n - Valid value range for *offset*\n\n * - :py:attr:`~term_image.renderable.Seek.START`\n - ``0`` <= *offset* < :py:attr:`frame_count`\n * - :py:attr:`~term_image.renderable.Seek.CURRENT`\n - -:py:meth:`tell` <= *offset* < :py:attr:`frame_count` - :py:meth:`tell`\n * - :py:attr:`~term_image.renderable.Seek.END`\n - -:py:attr:`frame_count` < *offset* <= ``0``\n \"\"\"\n frame_count = self.frame_count\n\n if frame_count is FrameCount.INDEFINITE:\n raise IndefiniteSeekError(\n \"Cannot seek a renderable with INDEFINITE frame count\"\n )\n\n frame = (\n offset\n if whence is Seek.START\n else (\n self._frame + offset\n if whence is Seek.CURRENT\n else frame_count + offset - 1\n )\n )\n if not 0 <= frame < frame_count:\n raise arg_value_error_range(\n \"offset\",\n offset,\n (\n f\"whence={whence.name}, frame_count={frame_count}\"\n + (f\", current={self._frame}\" if whence is Seek.CURRENT else \"\")\n ),\n )\n self._frame = frame\n\n return frame\n\n def tell(self) -> int:\n \"\"\"Returns the current frame number.\n\n Returns:\n Zero, if the renderable is non-animated or has\n :py:attr:`~term_image.renderable.FrameCount.INDEFINITE` frame count.\n Otherwise, the current frame number.\n \"\"\"\n return self._frame\n\n # Extension methods ========================================================\n\n def _animate_(\n self,\n render_data: RenderData,\n render_args: RenderArgs,\n padding: Padding,\n loops: int,\n cache: bool | int,\n output: TextIO,\n ) -> None:\n \"\"\"Animates frames of a renderable.\n\n Args:\n render_data: Render data.\n render_args: Render arguments associated with the renderable's class.\n output: The text I/O stream to which rendered frames will be written.\n\n All other parameters are the same as for :py:meth:`draw`, except that\n *padding* must have **absolute** dimensions if it's an instance of\n :py:class:`~term_image.padding.AlignedPadding`.\n\n This is called by :py:meth:`draw` for animations.\n\n NOTE:\n * The base implementation does not finalize *render_data*.\n * :term:`Render size` validation is expected to have been performed by\n the caller.\n * When called by :py:meth:`draw` (at least, the base implementation),\n *loops* and *cache* wouldn't have been validated.\n \"\"\"\n from term_image.render import RenderIterator\n\n render_size: Size = render_data[Renderable].size\n height = render_size.height\n pad_left, _, _, pad_bottom = padding._get_exact_dimensions_(render_size)\n render_iter = RenderIterator._from_render_data_(\n self,\n render_data,\n render_args,\n padding,\n loops,\n False if loops == 1 else cache,\n finalize=False,\n )\n cursor_to_next_render_line = f\"\\n{cursor_forward(pad_left)}\"\n cursor_to_render_top_left = (\n f\"\\r{cursor_up(height - 1)}{cursor_forward(pad_left)}\"\n )\n write = output.write\n flush = output.flush\n first_frame_written = False\n\n try:\n # first frame\n try:\n frame = next(render_iter)\n except StopIteration: # `INDEFINITE` frame count\n return\n\n try:\n write(frame.render_output)\n flush()\n except KeyboardInterrupt:\n self._handle_interrupted_draw_(render_data, render_args, output)\n return\n else:\n # Move the cursor to the top-left cell of the region occupied by the\n # render output\n write(\n f\"\\r{cursor_up(height + pad_bottom - 1)}{cursor_forward(pad_left)}\"\n )\n flush()\n\n first_frame_written = True\n\n # Padding has been drawn with the first frame, only the actual render is\n # needed henceforth.\n render_iter.set_padding(NO_PADDING)\n\n # render next frame during previous frame's duration\n duration_ms = frame.duration\n start_ns = perf_counter_ns()\n\n for frame in render_iter: # Render next frame\n # left-over of previous frame's duration\n sleep(\n max(0, duration_ms * 10**6 - (perf_counter_ns() - start_ns)) / 10**9\n )\n\n # clear previous frame, if necessary\n self._clear_frame_(render_data, render_args, pad_left + 1, output)\n\n # draw next frame\n try:\n write(frame.render_output.replace(\"\\n\", cursor_to_next_render_line))\n flush()\n except KeyboardInterrupt:\n self._handle_interrupted_draw_(render_data, render_args, output)\n return\n\n write(cursor_to_render_top_left)\n flush()\n\n # render next frame during previous frame's duration\n start_ns = perf_counter_ns()\n duration_ms = frame.duration\n\n # left-over of last frame's duration\n sleep(max(0, duration_ms * 10**6 - (perf_counter_ns() - start_ns)) / 10**9)\n except KeyboardInterrupt:\n pass\n finally:\n render_iter.close()\n if first_frame_written:\n # Move the cursor to the last line to prevent \"overlaid\" output\n write(cursor_down(height + pad_bottom - 1))\n flush()\n\n def _clear_frame_(\n self,\n render_data: RenderData,\n render_args: RenderArgs,\n cursor_x: int,\n output: TextIO,\n ) -> None:\n \"\"\"Clears the previous frame of an animation, if necessary.\n\n Args:\n render_data: Render data.\n render_args: Render arguments.\n cursor_x: Column/horizontal position of the cursor at the point of calling\n this method.\n\n .. note:: The position is **1-based** i.e the leftmost column on the\n screen is at position 1 (one).\n\n output: The text I/O stream to which frames of the animation are being\n written.\n\n Called by the base implementation of :py:meth:`_animate_` just before drawing\n the next frame of an animation.\n\n Upon calling this method, the cursor should be positioned at the top-left-most\n cell of the region occupied by the frame render output on the terminal screen.\n\n Upon return, ensure the cursor is at the same position it was at the point of\n calling this method (at least logically, since *output* shouldn't be flushed\n yet).\n\n The base implementation does nothing.\n\n NOTE:\n * This is required only if drawing the next frame doesn't inherently\n overwrite the previous frame.\n * This is only meant (and should only be used) as a last resort since\n clearing the previous frame before drawing the next may result in\n visible flicker.\n * Ensure whatever this method does doesn't result in the screen being\n scrolled.\n\n TIP:\n To reduce flicker, it's advisable to **not** flush *output*. It will be\n flushed after writing the next frame.\n \"\"\"\n\n @classmethod\n def _finalize_render_data_(cls, render_data: RenderData) -> None:\n \"\"\"Finalizes render data.\n\n Args:\n render_data: Render data.\n\n Typically, an overriding method should\n\n * finalize the data generated by :py:meth:`_get_render_data_` of the\n **same class**, if necessary,\n * call the overridden method, passing on *render_data*.\n\n NOTE:\n * It's recommended to call :py:meth:`RenderData.finalize()\n `\n instead as that assures a single invocation of this method.\n * Any definition of this method should be safe for multiple invocations on\n the same :py:class:`~term_image.renderable.RenderData` instance, just in\n case.\n\n .. seealso::\n :py:meth:`_get_render_data_`,\n :py:meth:`RenderData.finalize()\n `,\n the *finalize* parameter of :py:meth:`_init_render_`.\n \"\"\"\n\n def _get_frame_count_(self) -> int | Literal[FrameCount.INDEFINITE]:\n \"\"\"Implements :py:attr:`~term_image.renderable.FrameCount.POSTPONED` frame\n count evaluation.\n\n Returns:\n The frame count of the renderable. See :py:attr:`frame_count`.\n\n .. note::\n Returning :py:attr:`~term_image.renderable.FrameCount.POSTPONED` or\n ``1`` (one) is invalid and may result in unexpected/undefined behaviour\n across various interfaces defined by this library (and those derived\n from them), since re-postponing evaluation is unsupported and the\n renderable would have been taken to be animated.\n\n The base implementation raises :py:class:`NotImplementedError`.\n \"\"\"\n raise NotImplementedError(\"POSTPONED frame count evaluation isn't implemented\")\n\n def _get_render_data_(self, *, iteration: bool) -> RenderData:\n \"\"\"Generates data required for rendering that's based on internal or\n external state.\n\n Args:\n iteration: Whether the render operation requiring the data involves a\n sequence of :term:`renders` (most likely of different frames), or it's\n a one-off render.\n\n Returns:\n The generated render data.\n\n The render data should include **copies** of any **variable/mutable**\n internal/external state required for rendering and other data generated from\n constant state but which should **persist** throughout a render operation\n (which may involve consecutive/repeated renders of one or more frames).\n\n May also be used to \"allocate\" and initialize storage for mutable/variable\n data specific to a render operation.\n\n Typically, an overriding method should\n\n * call the overridden method,\n * update the namespace for its defining class (i.e\n :py:meth:`render_data[__class__]\n `) within the\n :py:class:`~term_image.renderable.RenderData` instance returned by the\n overridden method,\n * return the same :py:class:`~term_image.renderable.RenderData` instance.\n\n IMPORTANT:\n The :py:class:`~term_image.renderable.RenderData` instance returned must be\n associated [#rd-ass]_ with the type of the renderable on which this method\n is called i.e ``type(self)``. This is always the case for the base\n implementation of this method.\n\n NOTE:\n This method being called doesn't mean the data generated will be used\n immediately.\n\n .. seealso::\n :py:class:`~term_image.renderable.RenderData`,\n :py:meth:`_finalize_render_data_`,\n :py:meth:`~term_image.renderable.Renderable._init_render_`.\n \"\"\"\n render_data = RenderData(type(self))\n renderable_data: RenderableData = render_data[Renderable]\n renderable_data.update(\n size=self._get_render_size_(),\n frame_offset=self._frame,\n seek_whence=Seek.START,\n iteration=iteration,\n )\n if self.animated:\n renderable_data.duration = self._frame_duration\n\n return render_data\n\n @abstractmethod\n def _get_render_size_(self) -> geometry.Size:\n \"\"\"Returns the renderable's :term:`render size`.\n\n Returns:\n The size of the renderable's :term:`render output`.\n\n The base implementation raises :py:class:`NotImplementedError`.\n\n NOTE:\n Both dimensions are expected to be positive.\n\n .. seealso:: :py:attr:`render_size`\n \"\"\"\n raise NotImplementedError\n\n def _handle_interrupted_draw_(\n self, render_data: RenderData, render_args: RenderArgs, output: TextIO\n ) -> None:\n \"\"\"Performs any special handling necessary when an interruption occurs while\n writing a :term:`render output` to a stream.\n\n Args:\n render_data: Render data.\n render_args: Render arguments.\n output: The text I/O stream to which the render output was being written.\n\n Called by the base implementations of :py:meth:`draw` (for non-animations)\n and :py:meth:`_animate_` when :py:class:`KeyboardInterrupt` is raised while\n writing a render output.\n\n The base implementation does nothing.\n\n NOTE:\n *output* should be flushed by this method.\n\n HINT:\n For a renderable that uses SGR sequences in its render output, this method\n may write ``CSI 0 m`` to *output*.\n \"\"\"\n\n # *render_args*, no *padding*; or neither\n @overload\n def _init_render_(\n self,\n renderer: Callable[[RenderData, RenderArgs], T],\n render_args: RenderArgs | None = None,\n *,\n iteration: bool = False,\n finalize: bool = True,\n check_size: bool = False,\n allow_scroll: bool = False,\n ) -> tuple[T, None]: ...\n\n # both *render_args* and *padding*\n @overload\n def _init_render_(\n self,\n renderer: Callable[[RenderData, RenderArgs], T],\n render_args: RenderArgs | None,\n padding: OptionalPaddingT,\n *,\n iteration: bool = False,\n finalize: bool = True,\n check_size: bool = False,\n allow_scroll: bool = False,\n ) -> tuple[T, OptionalPaddingT]: ...\n\n # *padding*, no *render_args*\n @overload\n def _init_render_(\n self,\n renderer: Callable[[RenderData, RenderArgs], T],\n *,\n padding: OptionalPaddingT,\n iteration: bool = False,\n finalize: bool = True,\n check_size: bool = False,\n allow_scroll: bool = False,\n ) -> tuple[T, OptionalPaddingT]: ...\n\n def _init_render_(\n self,\n renderer: Callable[[RenderData, RenderArgs], T],\n render_args: RenderArgs | None = None,\n padding: Padding | None = None,\n *,\n iteration: bool = False,\n finalize: bool = True,\n check_size: bool = False,\n allow_scroll: bool = False,\n ) -> tuple[T, Padding | None]:\n \"\"\"Initiates a render operation.\n\n Args:\n renderer: Performs a render operation or extracts render data and arguments\n for a render operation to be performed later on.\n render_args: Render arguments.\n padding (:py:data:`OptionalPaddingT`): :term:`Render output` padding.\n iteration: Whether the render operation involves a sequence of renders\n (most likely of different frames), or it's a one-off render.\n finalize: Whether to finalize the render data passed to *renderer*\n immediately *renderer* returns.\n check_size: Whether to validate the [padded] :term:`render size` of\n **non-animations**.\n allow_scroll: Whether to validate the [padded] :term:`render height` of\n **non-animations**. Ignored if *check_size* is ``False``.\n\n Returns:\n A tuple containing\n\n * The return value of *renderer*.\n * *padding* (with equivalent **absolute** dimensions if it's an instance of\n :py:class:`~term_image.padding.AlignedPadding`).\n\n Raises:\n IncompatibleRenderArgsError: Incompatible render arguments.\n RenderSizeOutofRangeError: *check_size* is ``True`` and the [padded]\n :term:`render size` cannot fit into the :term:`terminal size`.\n\n :rtype: tuple[T, :py:data:`OptionalPaddingT`]\n\n After preparing render data and processing arguments, *renderer* is called with\n the following positional arguments:\n\n 1. Render data associated with **the renderable's class**\n 2. Render arguments associated with **the renderable's class** and initialized\n with *render_args*\n\n Any exception raised by *renderer* is propagated.\n\n IMPORTANT:\n Beyond this method (i.e any context from *renderer* onwards), use of any\n variable state (internal or external) should be avoided if possible.\n Any variable state (internal or external) required for rendering should\n be provided via :py:meth:`_get_render_data_`.\n\n If at all any variable state has to be used and is not\n reasonable/practicable to be provided via :py:meth:`_get_render_data_`,\n it should be read only once during a single render and passed to any\n nested/subsequent calls that require the value of that state during the\n same render.\n\n This is to prevent inconsistency in data used for the same render which may\n result in unexpected output.\n \"\"\"\n if not (render_args and render_args.render_cls is type(self)):\n # Validate compatibility (and convert, if compatible)\n render_args = RenderArgs(type(self), render_args)\n terminal_size = get_terminal_size()\n render_data = self._get_render_data_(iteration=iteration)\n try:\n if padding and isinstance(padding, AlignedPadding) and padding.relative:\n padding = padding.resolve(terminal_size)\n\n if check_size:\n render_size: Size = render_data[Renderable].size\n width, height = (\n padding.get_padded_size(render_size) if padding else render_size\n )\n terminal_width, terminal_height = terminal_size\n\n if width > terminal_width:\n raise RenderSizeOutofRangeError(\n f\"{'Padded render' if padding else 'Render'} width out of \"\n f\"range (got: {width}; terminal_width={terminal_width})\"\n )\n if not allow_scroll and height > terminal_height:\n raise RenderSizeOutofRangeError(\n f\"{'Padded render' if padding else 'Render'} height out of \"\n f\"range (got: {height}; terminal_height={terminal_height})\"\n )\n\n return renderer(render_data, render_args), padding\n finally:\n if finalize:\n render_data.finalize()\n\n @abstractmethod\n def _render_(self, render_data: RenderData, render_args: RenderArgs) -> Frame:\n \"\"\":term:`Renders` a frame.\n\n Args:\n render_data: Render data.\n render_args: Render arguments.\n\n Returns:\n The rendered frame.\n\n * The :py:attr:`~term_image.renderable.Frame.render_size` field =\n :py:attr:`render_data[Renderable].size\n `.\n * The :py:attr:`~term_image.renderable.Frame.render_output` field holds the\n :term:`render output`. This string should:\n\n * contain as many lines as ``render_size.height`` i.e exactly\n ``render_size.height - 1`` occurrences of ``\\\\n`` (the newline\n sequence).\n * occupy exactly ``render_size.height`` lines and ``render_size.width``\n columns on each line when drawn onto a terminal screen, **at least**\n when the render **size** it not greater than the terminal size on\n either axis.\n\n .. tip::\n If for any reason, the output behaves differently when the render\n **height** is greater than the terminal height, the behaviour, along\n with any possible alternatives or workarounds, should be duely noted.\n This doesn't apply to the **width**.\n\n * **not** end with ``\\\\n`` (the newline sequence).\n\n * As for the :py:attr:`~term_image.renderable.Frame.duration` field, if\n the renderable is:\n\n * **animated**; the value should be determined from the frame data\n source (or a default/fallback value, if undeterminable), if\n :py:attr:`render_data[Renderable].duration\n ` is\n :py:attr:`~term_image.renderable.FrameDuration.DYNAMIC`.\n Otherwise, it should be equal to\n :py:attr:`render_data[Renderable].duration\n `.\n * **non-animated**; the value range is unspecified i.e it may be given\n any value.\n\n Raises:\n StopIteration: End of iteration for an animated renderable with\n :py:attr:`~term_image.renderable.FrameCount.INDEFINITE` frame count.\n RenderError: An error occurred while rendering.\n\n NOTE:\n :py:class:`StopIteration` may be raised if and only if\n :py:attr:`render_data[Renderable].iteration\n ` is ``True``.\n Otherwise, it would be out of place.\n\n .. seealso:: :py:class:`~term_image.renderable.RenderableData`.\n \"\"\"\n raise NotImplementedError", "n_imports_parsed": 14, "n_files_resolved": 7, "n_chars_extracted": 41124}, "tests/test_image/test_iterm2.py::64": {"resolved_imports": ["src/term_image/__init__.py", "src/term_image/_ctlseqs.py", "src/term_image/exceptions.py", "src/term_image/image/__init__.py", "src/term_image/image/iterm2.py"], "used_names": ["ITerm2Image"], "enclosing_function": "test_descendant", "extracted_code": "", "n_imports_parsed": 15, "n_files_resolved": 5, "n_chars_extracted": 0}, "tests/renderable/test_types.py::1477": {"resolved_imports": ["src/term_image/geometry.py", "src/term_image/renderable/_renderable.py", "src/term_image/renderable/_types.py"], "used_names": ["RenderData"], "enclosing_function": "test_finalized", "extracted_code": "# Source: src/term_image/renderable/_types.py\nclass RenderData(RenderArgsData):\n \"\"\"Render data.\n\n Args:\n render_cls: A :term:`render class`.\n\n An instance of this class is basically a container of render data namespaces\n (instances of :py:class:`~term_image.renderable.DataNamespace`); one for each\n :term:`render class`, which has render data, in the Method Resolution Order\n of its associated [#rd-ass]_ render class.\n\n NOTE:\n * Instances are immutable but the constituent namespaces are mutable.\n * Instances and their contents shouldn't be copied by any means because\n finalizing an instance may invalidate all other copies.\n * Instances should always be explicitly finalized as soon as they're no longer\n needed.\n\n .. seealso::\n\n :py:attr:`~term_image.renderable.Renderable._Data_`\n Render class-specific render data.\n \"\"\"\n\n # Class Attributes =========================================================\n\n __slots__ = (\"finalized\",)\n\n # Instance Attributes ======================================================\n\n finalized: bool\n \"\"\"Finalization status\"\"\"\n\n render_cls: type[Renderable]\n \"\"\"The associated :term:`render class`\"\"\"\n\n _namespaces: MappingProxyType[type[Renderable], DataNamespace]\n\n # Special Methods ==========================================================\n\n def __init__(self, render_cls: type[Renderable]) -> None:\n super().__init__(\n render_cls,\n {cls: data_cls() for cls, data_cls in render_cls._RENDER_DATA_MRO.items()},\n )\n self.finalized = False\n\n def __del__(self) -> None:\n try:\n self.finalize()\n except AttributeError: # Unsuccessful initialization\n pass\n\n def __getitem__(self, render_cls: type[Renderable]) -> Any:\n \"\"\"Returns a constituent namespace.\n\n Args:\n render_cls: A :term:`render class` of which :py:attr:`render_cls` is a\n subclass (which may be :py:attr:`render_cls` itself) and which has\n render data.\n\n Returns:\n The constituent namespace associated with *render_cls*.\n\n Raises:\n TypeError: *render_cls* is not a render class.\n ValueError: :py:attr:`render_cls` is not a subclass of *render_cls*.\n NoDataNamespaceError: *render_cls* has no render data.\n\n NOTE:\n The return type hint is :py:class:`~typing.Any` only for compatibility\n with static type checking, as this aspect of the interface seems too\n dynamic to be correctly expressed with the exisiting type system.\n\n Regardless, the return value is guaranteed to always be an instance\n of a render data namespace class associated with *render_cls*.\n For instance, the following would always be valid for\n :py:class:`~term_image.renderable.Renderable`::\n\n renderable_data: RenderableData = render_data[Renderable]\n\n and similar idioms are encouraged to be used for other render classes.\n \"\"\"\n try:\n return self._namespaces[render_cls]\n except TypeError:\n raise arg_type_error(\"render_cls\", render_cls) from None\n except KeyError:\n if not isinstance(render_cls, RenderableMeta):\n raise arg_type_error(\"render_cls\", render_cls) from None\n\n if issubclass(self.render_cls, render_cls):\n raise NoDataNamespaceError(\n f\"{render_cls.__name__!r} has no render data\"\n ) from None\n\n raise ValueError(\n f\"{self.render_cls.__name__!r} is not a subclass of \"\n f\"{render_cls.__name__!r}\"\n ) from None\n\n def __iter__(self) -> Iterator[DataNamespace]:\n \"\"\"Returns an iterator that yields the constituent namespaces.\n\n Returns:\n An iterator that yields the constituent namespaces.\n\n WARNING:\n The number and order of namespaces is guaranteed to be the same across all\n instances associated [#rd-ass]_ with the same :term:`render class` but\n beyond this, should not be relied upon as the details (such as the\n specific number or order) may change without notice.\n\n The order is an implementation detail of the Renderable API and the number\n should be considered alike with respect to the associated render class.\n \"\"\"\n return iter(self._namespaces.values())\n\n def __repr__(self) -> str:\n return \"\".join(\n (\n f\"<{type(self).__name__}({self.render_cls.__name__})\",\n \": \" if self._namespaces else \"\",\n \", \".join(map(repr, self._namespaces.values())),\n \">\",\n )\n )\n\n # Public Methods ===========================================================\n\n def finalize(self) -> None:\n \"\"\"Finalizes the render data.\n\n Calls :py:meth:`~term_image.renderable.Renderable._finalize_render_data_`\n of :py:attr:`render_cls`.\n\n NOTE:\n This method is safe for multiple invocations on the same instance.\n \"\"\"\n if not self.finalized:\n try:\n self.render_cls._finalize_render_data_(self)\n finally:\n self.finalized = True", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 5410}, "tests/test_image/test_url.py::48": {"resolved_imports": ["src/term_image/exceptions.py", "src/term_image/image/block.py", "src/term_image/image/common.py", "src/term_image/image/__init__.py"], "used_names": ["BlockImage", "ImageSource", "from_url"], "enclosing_function": "test_source", "extracted_code": "# Source: src/term_image/image/block.py\nclass BlockImage(TextImage):\n \"\"\"A render style using unicode half blocks and direct-color colour escape\n sequences.\n\n See :py:class:`TextImage` for the description of the constructor.\n \"\"\"\n\n @classmethod\n def is_supported(cls):\n if cls._supported is None:\n COLORTERM = os.environ.get(\"COLORTERM\") or \"\"\n TERM = os.environ.get(\"TERM\") or \"\"\n cls._supported = (\n \"truecolor\" in COLORTERM or \"24bit\" in COLORTERM or \"256color\" in TERM\n )\n\n return cls._supported\n\n def _get_render_size(self) -> Tuple[int, int]:\n return tuple(map(mul, self.rendered_size, (1, 2)))\n\n @staticmethod\n def _pixels_cols(\n *, pixels: Optional[int] = None, cols: Optional[int] = None\n ) -> int:\n return pixels if pixels is not None else cols\n\n @staticmethod\n def _pixels_lines(\n *, pixels: Optional[int] = None, lines: Optional[int] = None\n ) -> int:\n return ceil(pixels / 2) if pixels is not None else lines * 2\n\n def _render_image(\n self,\n img: PIL.Image.Image,\n alpha: Union[None, float, str],\n *,\n frame: bool = False,\n split_cells: bool = False,\n ) -> str:\n # NOTE:\n # It's more efficient to write separate strings to the buffer separately\n # than concatenate and write together.\n\n def update_buffer():\n if alpha:\n no_alpha = False\n if a_cluster1 == 0 == a_cluster2:\n buf_write(SGR_DEFAULT)\n buf_write(blank * n)\n elif a_cluster1 == 0: # up is transparent\n buf_write(SGR_DEFAULT)\n buf_write(SGR_FG_DIRECT % cluster2)\n buf_write(lower_pixel * n)\n elif a_cluster2 == 0: # down is transparent\n buf_write(SGR_DEFAULT)\n buf_write(SGR_FG_DIRECT % cluster1)\n buf_write(upper_pixel * n)\n else:\n no_alpha = True\n\n if not alpha or no_alpha:\n r, g, b = cluster2\n # Kitty does not render BG colors equal to the default BG color\n if is_on_kitty and cluster2 == bg_color:\n r += r < 255 or -1\n buf_write(SGR_BG_DIRECT % (r, g, b))\n if cluster1 == cluster2:\n buf_write(blank * n)\n else:\n buf_write(SGR_FG_DIRECT % cluster1)\n buf_write(upper_pixel * n)\n\n buffer = io.StringIO()\n buf_write = buffer.write # Eliminate attribute resolution cost\n\n bg_color = get_fg_bg_colors()[1]\n is_on_kitty = self._is_on_kitty()\n if split_cells:\n blank = \" \\0\"\n lower_pixel = LOWER_PIXEL + \"\\0\"\n upper_pixel = UPPER_PIXEL + \"\\0\"\n else:\n blank = \" \"\n lower_pixel = LOWER_PIXEL\n upper_pixel = UPPER_PIXEL\n end_of_line = SGR_DEFAULT + \"\\n\"\n\n width, height = self._get_render_size()\n frame_img = img if frame else None\n img, rgb, a = self._get_render_data(img, alpha, round_alpha=True, frame=frame)\n alpha = img.mode == \"RGBA\"\n\n # clean up (ImageIterator uses one PIL image throughout)\n if frame_img is not img:\n self._close_image(img)\n\n rgb_pairs = (\n (\n zip(rgb[x : x + width], rgb[x + width : x + width * 2]),\n (rgb[x], rgb[x + width]),\n )\n for x in range(0, len(rgb), width * 2)\n )\n a_pairs = (\n (\n zip(a[x : x + width], a[x + width : x + width * 2]),\n (a[x], a[x + width]),\n )\n for x in range(0, len(a), width * 2)\n )\n\n row_no = 0\n # Two rows of pixels per line\n for (rgb_pair, (cluster1, cluster2)), (a_pair, (a_cluster1, a_cluster2)) in zip(\n rgb_pairs, a_pairs\n ):\n row_no += 2\n n = 0\n for (px1, px2), (a1, a2) in zip(rgb_pair, a_pair):\n # Color-code characters and write to buffer\n # when upper and/or lower pixel color/alpha-level changes\n if not (alpha and a1 == a_cluster1 == 0 == a_cluster2 == a2) and (\n px1 != cluster1\n or px2 != cluster2\n or alpha\n and (\n # From non-transparent to transparent\n a_cluster1 != a1 == 0\n or a_cluster2 != a2 == 0\n # From transparent to non-transparent\n or 0 == a_cluster1 != a1\n or 0 == a_cluster2 != a2\n )\n ):\n update_buffer()\n cluster1 = px1\n cluster2 = px2\n if alpha:\n a_cluster1 = a1\n a_cluster2 = a2\n n = 0\n n += 1\n\n update_buffer() # Rest of the line\n if split_cells:\n # Set the last \"\\0\" to be overwritten by the next byte\n buffer.seek(buffer.tell() - 1)\n if row_no < height: # last line not yet rendered\n buf_write(end_of_line)\n\n buf_write(SGR_DEFAULT) # Reset color after last line\n\n with buffer:\n return buffer.getvalue()\n\n\n# Source: src/term_image/image/common.py\nclass ImageSource(Enum):\n \"\"\"Image source type.\"\"\"\n\n #: The instance was derived from a path to a local image file.\n #:\n #: :meta hide-value:\n FILE_PATH = SourceAttr(\"_source\")\n\n #: The instance was derived from a PIL image instance.\n #:\n #: :meta hide-value:\n PIL_IMAGE = SourceAttr(\"_source\")\n\n #: The instance was derived from an image URL.\n #:\n #: :meta hide-value:\n URL = SourceAttr(\"_url\")\n\n\n# Source: src/term_image/image/__init__.py\ndef from_url(\n url: str,\n **kwargs: Union[None, int],\n) -> BaseImage:\n \"\"\"Creates an image instance from an image URL.\n\n Returns:\n An instance of the automatically selected image render style (as returned by\n :py:func:`auto_image_class`).\n\n Same arguments and raised exceptions as :py:meth:`BaseImage.from_url`.\n \"\"\"\n return auto_image_class().from_url(url, **kwargs)", "n_imports_parsed": 6, "n_files_resolved": 4, "n_chars_extracted": 6492}, "tests/renderable/test_types.py::144": {"resolved_imports": ["src/term_image/geometry.py", "src/term_image/renderable/_renderable.py", "src/term_image/renderable/_types.py"], "used_names": [], "enclosing_function": "test_no_fields", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/test_iterator.py::345": {"resolved_imports": ["src/term_image/_ctlseqs.py", "src/term_image/exceptions.py", "src/term_image/image/block.py", "src/term_image/image/common.py"], "used_names": ["ImageIterator", "TermImageError", "pytest"], "enclosing_function": "test_seek", "extracted_code": "# Source: src/term_image/exceptions.py\nclass TermImageError(Exception):\n \"\"\"Exception baseclass. Raised for generic errors.\"\"\"\n\n\n# Source: src/term_image/image/common.py\nclass ImageIterator:\n \"\"\"Efficiently iterate over :term:`rendered` frames of an :term:`animated` image\n\n Args:\n image: Animated image.\n repeat: The number of times to go over the entire image. A negative value\n implies infinite repetition.\n format_spec: The :ref:`format specifier ` for the rendered\n frames (default: auto).\n cached: Determines if the :term:`rendered` frames will be cached (for speed up\n of subsequent renders) or not. If it is\n\n * a boolean, caching is enabled if ``True``. Otherwise, caching is disabled.\n * a positive integer, caching is enabled only if the framecount of the image\n is less than or equal to the given number.\n\n Raises:\n TypeError: An argument is of an inappropriate type.\n ValueError: An argument is of an appropriate type but has an\n unexpected/invalid value.\n term_image.exceptions.StyleError: Invalid style-specific format specifier.\n\n * If *repeat* equals ``1``, caching is disabled.\n * The iterator has immediate response to changes in the image size.\n * If the image size is :term:`dynamic `, it's computed per frame.\n * The number of the last yielded frame is set as the image's seek position.\n * Directly adjusting the seek position of the image doesn't affect iteration.\n Use :py:meth:`ImageIterator.seek` instead.\n * After the iterator is exhausted, the underlying image is set to frame ``0``.\n \"\"\"\n\n def __init__(\n self,\n image: BaseImage,\n repeat: int = -1,\n format_spec: str = \"\",\n cached: Union[bool, int] = 100,\n ) -> None:\n if not isinstance(image, BaseImage):\n raise arg_type_error(\"image\", image)\n if not image._is_animated:\n raise ValueError(\"'image' is not animated\")\n\n if not isinstance(repeat, int):\n raise arg_type_error(\"repeat\", repeat)\n if not repeat:\n raise arg_value_error(\"repeat\", repeat)\n\n if not isinstance(format_spec, str):\n raise arg_type_error(\"format_spec\", format_spec)\n *fmt, alpha, style_args = image._check_format_spec(format_spec)\n\n if not isinstance(cached, int): # `bool` is a subclass of `int`\n raise arg_type_error(\"cached\", cached)\n if False is not cached <= 0:\n raise arg_value_error_range(\"cached\", cached)\n\n self._image = image\n self._repeat = repeat\n self._format = format_spec\n self._cached = repeat != 1 and (\n cached if isinstance(cached, bool) else image.n_frames <= cached\n )\n self._loop_no = None\n self._animator = image._renderer(\n self._animate, alpha, fmt, style_args, check_size=False\n )\n\n def __del__(self) -> None:\n self.close()\n\n def __iter__(self) -> ImageIterator:\n return self\n\n def __next__(self) -> str:\n try:\n return next(self._animator)\n except StopIteration:\n self.close()\n raise StopIteration(\n \"Iteration has reached the given repeat count\"\n ) from None\n except AttributeError as e:\n if str(e).endswith(\"'_animator'\"):\n raise StopIteration(\"Iterator exhausted or closed\") from None\n else:\n self.close()\n raise\n except Exception:\n self.close()\n raise\n\n def __repr__(self) -> str:\n return (\n \"{}(image={!r}, repeat={}, format_spec={!r}, cached={}, loop_no={})\".format(\n type(self).__name__,\n *self.__dict__.values(),\n )\n )\n\n loop_no = property(\n lambda self: self._loop_no,\n doc=\"\"\"Iteration repeat countdown\n\n :type: Optional[int]\n\n GET:\n Returns:\n\n * ``None``, if iteration hasn't started.\n * Otherwise, the current iteration repeat countdown value.\n\n Changes on the first iteration of each loop, except for infinite iteration\n where it's always ``-1``. When iteration has ended, the value is zero.\n \"\"\",\n )\n\n def close(self) -> None:\n \"\"\"Closes the iterator and releases resources used.\n\n Does not reset the frame number of the underlying image.\n\n NOTE:\n This method is automatically called when the iterator is exhausted or\n garbage-collected.\n \"\"\"\n try:\n self._animator.close()\n del self._animator\n self._image._close_image(self._img)\n del self._img\n except AttributeError:\n pass\n\n def seek(self, pos: int) -> None:\n \"\"\"Sets the frame number to be yielded on the next iteration without affecting\n the repeat count.\n\n Args:\n pos: Next frame number.\n\n Raises:\n TypeError: An argument is of an inappropriate type.\n ValueError: An argument is of an appropriate type but has an\n unexpected/invalid value.\n term_image.exceptions.TermImageError: Iteration has not yet started or the\n iterator is exhausted/closed.\n\n Frame numbers start from ``0`` (zero).\n \"\"\"\n if not isinstance(pos, int):\n raise arg_type_error(\"pos\", pos)\n if not 0 <= pos < self._image.n_frames:\n raise arg_value_error_range(\"pos\", pos, f\"n_frames={self._image.n_frames}\")\n\n try:\n self._animator.send(pos)\n except TypeError:\n raise TermImageError(\"Iteration has not yet started\") from None\n except AttributeError:\n raise TermImageError(\"Iterator exhausted or closed\") from None\n\n def _animate(\n self,\n img: PIL.Image.Image,\n alpha: Union[None, float, str],\n fmt: Tuple[Union[None, str, int]],\n style_args: Dict[str, Any],\n ) -> Generator[str, int, None]:\n \"\"\"Returns a generator that yields rendered and formatted frames of the\n underlying image.\n \"\"\"\n self._img = img # For cleanup\n image = self._image\n cached = self._cached\n self._loop_no = repeat = self._repeat\n if cached:\n cache = [(None,) * 2] * image.n_frames\n\n sent = None\n n = 0\n while repeat:\n if sent is None:\n image._seek_position = n\n try:\n frame = image._format_render(\n image._render_image(img, alpha, frame=True, **style_args), *fmt\n )\n except EOFError:\n image._seek_position = n = 0\n if repeat > 0: # Avoid infinitely large negative numbers\n self._loop_no = repeat = repeat - 1\n if cached:\n break\n continue\n else:\n if cached:\n cache[n] = (frame, hash(image.rendered_size))\n\n sent = yield frame\n n = n + 1 if sent is None else sent - 1\n\n if cached:\n n_frames = len(cache)\n while repeat:\n while n < n_frames:\n if sent is None:\n image._seek_position = n\n frame, size_hash = cache[n]\n if hash(image.rendered_size) != size_hash:\n frame = image._format_render(\n image._render_image(img, alpha, frame=True, **style_args),\n *fmt,\n )\n cache[n] = (frame, hash(image.rendered_size))\n\n sent = yield frame\n n = n + 1 if sent is None else sent - 1\n\n image._seek_position = n = 0\n if repeat > 0: # Avoid infinitely large negative numbers\n self._loop_no = repeat = repeat - 1\n\n # For consistency in behaviour\n if img is image._source:\n img.seek(0)", "n_imports_parsed": 7, "n_files_resolved": 4, "n_chars_extracted": 8234}, "tests/test_geometry.py::15": {"resolved_imports": ["src/term_image/geometry.py"], "used_names": ["RawSize", "pytest"], "enclosing_function": "test_height", "extracted_code": "# Source: src/term_image/geometry.py\nclass RawSize(NamedTuple):\n \"\"\"The dimensions of a rectangular region.\n\n Args:\n width: The horizontal dimension\n height: The vertical dimension\n\n NOTE:\n * A dimension may be non-positive but the validity and meaning would be\n determined by the receiving interface.\n * This is a subclass of :py:class:`tuple`. Hence, instances can be used anyway\n and anywhere tuples can.\n \"\"\"\n\n width: int\n height: int\n\n @classmethod\n def _new(cls, width: int, height: int) -> Self:\n \"\"\"Alternate constructor for internal use only.\"\"\"\n return tuple.__new__(cls, (width, height))", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 682}, "tests/renderable/test_types.py::971": {"resolved_imports": ["src/term_image/geometry.py", "src/term_image/renderable/_renderable.py", "src/term_image/renderable/_types.py"], "used_names": ["ArgsNamespace", "Renderable", "pytest"], "enclosing_function": "test_render_cls_update", "extracted_code": "# Source: src/term_image/renderable/_renderable.py\nclass Renderable(metaclass=RenderableMeta, _base=True):\n \"\"\"A renderable.\n\n Args:\n frame_count: Number of frames. If it's a\n\n * positive integer, the number of frames is as given.\n * :py:class:`~term_image.renderable.FrameCount` enum member, see the\n member's description.\n\n If equal to 1 (one), the renderable is non-animated.\n Otherwise, it is animated.\n\n frame_duration: The duration of a frame. If it's a\n\n * positive integer, it implies a static duration (in **milliseconds**)\n i.e the same duration applies to every frame.\n * :py:class:`~term_image.renderable.FrameDuration` enum member, see the\n member's description.\n\n This argument is ignored if *frame_count* equals 1 (one)\n i.e the renderable is non-animated.\n\n Raises:\n ValueError: An argument has an invalid value.\n\n ATTENTION:\n This is an abstract base class. Hence, only **concrete** subclasses can be\n instantiated.\n\n .. seealso::\n\n :ref:`renderable-ext-api`\n :py:class:`Renderable`\\\\ 's Extension API\n \"\"\"\n\n # Class Attributes =========================================================\n\n # Initialized by `RenderableMeta` and may be updated by `ArgsNamespaceMeta`\n Args: ClassVar[type[ArgsNamespace] | None]\n \"\"\":term:`Render class`\\\\ -specific render arguments.\n\n This is either:\n\n - a render argument namespace class (subclass of :py:class:`ArgsNamespace`)\n associated [#an-ass]_ with the render class, or\n - :py:data:`None`, if the render class has no render arguments.\n\n If this is a class, an instance of it (or a subclass thereof) is contained within\n any :py:class:`RenderArgs` instance associated [#ra-ass]_ with the render class or\n any of its subclasses. Also, an instance of this class (or a subclass of it) is\n returned by :py:meth:`render_args[render_cls]\n `; where *render_args* is\n an instance of :py:class:`~term_image.renderable.RenderArgs` as previously\n described and *render_cls* is the render class with which this namespace class\n is associated [#an-ass]_.\n\n .. collapse:: Example\n\n >>> class Foo(Renderable):\n ... pass\n ...\n ... class FooArgs(ArgsNamespace, render_cls=Foo):\n ... foo: str | None = None\n ...\n >>> Foo.Args is FooArgs\n True\n >>>\n >>> # default\n >>> foo_args = Foo.Args()\n >>> foo_args\n FooArgs(foo=None)\n >>> foo_args.foo is None\n True\n >>>\n >>> render_args = RenderArgs(Foo)\n >>> render_args[Foo]\n FooArgs(foo=None)\n >>>\n >>> # non-default\n >>> foo_args = Foo.Args(\"FOO\")\n >>> foo_args\n FooArgs(foo='FOO')\n >>> foo_args.foo\n 'FOO'\n >>>\n >>> render_args = RenderArgs(Foo, foo_args.update(foo=\"bar\"))\n >>> render_args[Foo]\n FooArgs(foo='bar')\n\n On the other hand, if this is :py:data:`None`, it implies the render class has no\n render arguments.\n\n .. collapse:: Example\n\n >>> class Bar(Renderable):\n ... pass\n ...\n >>> Bar.Args is None\n True\n >>> render_args = RenderArgs(Bar)\n >>> render_args[Bar]\n Traceback (most recent call last):\n ...\n NoArgsNamespaceError: 'Bar' has no render arguments\n \"\"\"\n\n # Initialized by `RenderableMeta` and may be updated by `DataNamespaceMeta`\n _Data_: ClassVar[type[DataNamespace] | None]\n \"\"\":term:`Render class`\\\\ -specific render data.\n\n This is either:\n\n - a render data namespace class (subclass of :py:class:`DataNamespace`)\n associated [#dn-ass]_ with the render class, or\n - :py:data:`None`, if the render class has no render data.\n\n If this is a class, an instance of it (or a subclass thereof) is contained within\n any :py:class:`RenderData` instance associated [#rd-ass]_ with the render class or\n any of its subclasses. Also, an instance of this class (or a subclass of it) is\n returned by :py:meth:`render_data[render_cls]\n `; where *render_data* is\n an instance of :py:class:`~term_image.renderable.RenderData` as previously\n described and *render_cls* is the render class with which this namespace class\n is associated [#dn-ass]_.\n\n .. collapse:: Example\n\n >>> class Foo(Renderable):\n ... pass\n ...\n ... class _Data_(DataNamespace, render_cls=Foo):\n ... foo: str | None\n ...\n >>> Foo._Data_ is FooData\n True\n >>>\n >>> foo_data = Foo._Data_()\n >>> foo_data\n >\n >>> foo_data.foo\n Traceback (most recent call last):\n ...\n UninitializedDataFieldError: The render data field 'foo' of 'Foo' has not \\\nbeen initialized\n >>>\n >>> foo_data.foo = \"FOO\"\n >>> foo_data\n \n >>> foo_data.foo\n 'FOO'\n >>>\n >>> render_data = RenderData(Foo)\n >>> render_data[Foo]\n >\n >>>\n >>> render_data[Foo].foo = \"bar\"\n >>> render_data[Foo]\n \n\n On the other hand, if this is :py:data:`None`, it implies the render class has no\n render data.\n\n .. collapse:: Example\n\n >>> class Bar(Renderable):\n ... pass\n ...\n >>> Bar._Data_ is None\n True\n >>>\n >>> render_data = RenderData(Bar)\n >>> render_data[Bar]\n Traceback (most recent call last):\n ...\n NoDataNamespaceError: 'Bar' has no render data\n\n .. seealso::\n\n :py:class:`~term_image.renderable.RenderableData`\n Render data for :py:class:`~term_image.renderable.Renderable`.\n \"\"\"\n\n _EXPORTED_ATTRS_: ClassVar[tuple[str, ...]]\n \"\"\"Exported attributes.\n\n This specifies class attributes defined by the class (not a parent) on itself\n **but not** its subclasses which should be exported to definitions of the class\n in subprocesses.\n\n These attributes are typically assigned using ``__class__.*`` within methods.\n\n NOTE:\n * Defining this is optional.\n * The attributes are exported for a class if and only if they are defined\n on that class when starting a subprocess.\n * The attributes are exported only for subprocesses started via\n :py:class:`multiprocessing.Process`.\n\n TIP:\n This can be used to export \"private\" attributes of the class across\n subprocesses.\n \"\"\"\n\n _EXPORTED_DESCENDANT_ATTRS_: ClassVar[tuple[str, ...]]\n \"\"\"Exported :term:`descendant` attributes.\n\n This specifies class attributes defined by the class (not a parent) on itself\n **and** its subclasses (i.e :term:`descendant` attributes) which should be exported\n to definitions of the class and its subclasses in subprocesses.\n\n These attributes are typically assigned using ``cls.*`` within class methods.\n\n This extends the exported descendant attributes of parent classes i.e all\n exported descendant attributes of a class are also exported for its subclasses.\n\n NOTE:\n * Defining this is optional.\n * The attributes are exported for a class if and only if they are defined\n on that class when starting a subprocess.\n * The attributes are exported only for subprocesses started via\n :py:class:`multiprocessing.Process`.\n\n TIP:\n This can be used to export \"private\" :term:`descendant` attributes of the\n class across subprocesses.\n \"\"\"\n\n _ALL_DEFAULT_ARGS: ClassVar[MappingProxyType[type[Renderable], ArgsNamespace]]\n _RENDER_DATA_MRO: ClassVar[MappingProxyType[type[Renderable], type[DataNamespace]]]\n _ALL_EXPORTED_ATTRS: ClassVar[tuple[str, ...]]\n\n # Instance Attributes ======================================================\n\n animated: bool\n \"\"\"``True`` if the renderable is :term:`animated`. Otherwise, ``False``.\"\"\"\n\n _frame: int\n _frame_count: int | FrameCount\n _frame_duration: int | FrameDuration\n\n # Special Methods ==========================================================\n\n def __init__(\n self,\n frame_count: int | FrameCount,\n frame_duration: int | FrameDuration,\n ) -> None:\n if isinstance(frame_count, int) and frame_count < 1:\n raise arg_value_error_range(\"frame_count\", frame_count)\n\n if frame_count != 1:\n if isinstance(frame_duration, int) and frame_duration <= 0:\n raise arg_value_error_range(\"frame_duration\", frame_duration)\n self._frame_duration = frame_duration\n\n self.animated = frame_count != 1\n self._frame_count = frame_count\n self._frame = 0\n\n def __iter__(self) -> term_image.render.RenderIterator:\n \"\"\"Returns a render iterator.\n\n Returns:\n A render iterator (with frame caching disabled and all other optional\n arguments to :py:class:`~term_image.render.RenderIterator` being the\n default values).\n\n Raises:\n NonAnimatedRenderableError: The renderable is non-animated.\n\n :term:`Animated` renderables are iterable i.e they can be used with various\n means of iteration such as the ``for`` statement and iterable unpacking.\n \"\"\"\n from term_image.render import RenderIterator\n\n try:\n return RenderIterator(self, cache=False)\n except ValueError:\n raise NonAnimatedRenderableError(\n \"Non-animated renderables are not iterable\"\n ) from None\n\n def __repr__(self) -> str:\n return f\"<{type(self).__name__}: frame_count={self._frame_count}>\"\n\n def __str__(self) -> str:\n \"\"\":term:`Renders` the current frame with default arguments and no padding.\n\n Returns:\n The frame :term:`render output`.\n\n Raises:\n RenderError: An error occurred during :term:`rendering`.\n \"\"\"\n return self._init_render_(self._render_)[0].render_output\n\n # Properties ===============================================================\n\n @property\n def frame_count(self) -> int | Literal[FrameCount.INDEFINITE]:\n \"\"\"Frame count\n\n GET:\n Returns either\n\n * the number of frames the renderable has, or\n * :py:attr:`~term_image.renderable.FrameCount.INDEFINITE`.\n \"\"\"\n if self._frame_count is FrameCount.POSTPONED:\n self._frame_count = self._get_frame_count_()\n\n return self._frame_count\n\n @property\n def frame_duration(self) -> int | FrameDuration:\n \"\"\"Frame duration\n\n GET:\n Returns\n\n * a positive integer, a static duration (in **milliseconds**) i.e the\n same duration applies to every frame; or\n * :py:attr:`~term_image.renderable.FrameDuration.DYNAMIC`.\n\n SET:\n If the value is\n\n * a positive integer, it implies a static duration (in **milliseconds**)\n i.e the same duration applies to every frame.\n * :py:attr:`~term_image.renderable.FrameDuration.DYNAMIC`, see the\n enum member's description.\n\n Raises:\n NonAnimatedRenderableError: The renderable is non-animated.\n \"\"\"\n try:\n return self._frame_duration\n except AttributeError:\n if not self.animated:\n raise NonAnimatedRenderableError(\n \"Non-animated renderables have no frame duration\"\n ) from None\n raise\n\n @frame_duration.setter\n def frame_duration(self, duration: int | FrameDuration) -> None:\n if not self.animated:\n raise NonAnimatedRenderableError(\n \"Cannot set frame duration for a non-animated renderable\"\n )\n\n if isinstance(duration, int) and duration <= 0:\n raise arg_value_error_range(\"frame_duration\", duration)\n\n self._frame_duration = duration\n\n @property\n def render_size(self) -> geometry.Size:\n \"\"\":term:`Render size`\n\n GET:\n Returns the size of the renderable's :term:`render output`.\n \"\"\"\n return self._get_render_size_()\n\n # Public Methods ===========================================================\n\n def draw(\n self,\n render_args: RenderArgs | None = None,\n padding: Padding = AlignedPadding(0, -2),\n *,\n animate: bool = True,\n loops: int = -1,\n cache: bool | int = 100,\n check_size: bool = True,\n allow_scroll: bool = False,\n hide_cursor: bool = True,\n echo_input: bool = False,\n ) -> None:\n \"\"\"Draws the current frame or an animation to standard output.\n\n Args:\n render_args: Render arguments.\n padding: :term:`Render output` padding.\n animate: Whether to enable animation for :term:`animated` renderables.\n If disabled, only the current frame is drawn.\n loops: See :py:class:`~term_image.render.RenderIterator`\n (applies to **animations only**).\n cache: See :py:class:`~term_image.render.RenderIterator`.\n (applies to **animations only**).\n check_size: Whether to validate the padded :term:`render size` of\n **non-animations**.\n allow_scroll: Whether to validate the padded :term:`render height` of\n **non-animations**. Ignored if *check_size* is ``False``.\n hide_cursor: Whether to hide the cursor **while drawing**.\n echo_input: Whether to display input **while drawing** (applies on **Unix\n only**).\n\n .. note::\n * If disabled (default), input is not read/consumed, it's just not\n displayed.\n * If enabled, echoed input may affect cursor positioning and\n therefore, the output (especially for animations).\n\n Raises:\n RenderSizeOutofRangeError: The padded :term:`render size` can not fit into\n the :term:`terminal size`.\n IncompatibleRenderArgsError: Incompatible render arguments.\n RenderError: An error occurred during :term:`rendering`.\n\n If *check_size* is ``True`` (or it's an animation),\n\n * the padded :term:`render width` must not be greater than the\n :term:`terminal width`.\n * and *allow_scroll* is ``False`` (or it's an animation), the padded\n :term:`render height` must not be greater than the :term:`terminal height`.\n\n NOTE:\n * *hide_cursor* and *echo_input* apply if and only if the output stream\n is connected to a terminal.\n * For animations (i.e animated renderables with *animate* = ``True``),\n the padded :term:`render size` is always validated.\n * Animations with **definite** frame count, **by default**, are infinitely\n looped but can be terminated with :py:data:`~signal.SIGINT`\n (``CTRL + C``), **without** raising :py:class:`KeyboardInterrupt`.\n \"\"\"\n animation = self.animated and animate\n output = sys.stdout\n not_echo_input = OS_IS_UNIX and not echo_input and output.isatty()\n hide_cursor = hide_cursor and output.isatty()\n\n # Validate size and get render data and args\n render_data: RenderData\n real_render_args: RenderArgs\n (render_data, real_render_args), padding = self._init_render_(\n lambda *args: args,\n render_args,\n padding,\n iteration=animation,\n finalize=False,\n check_size=animation or check_size,\n allow_scroll=not animation and allow_scroll,\n )\n\n if not_echo_input:\n output_fd = output.fileno()\n old_attr = termios.tcgetattr(output_fd)\n new_attr = termios.tcgetattr(output_fd)\n new_attr[3] &= ~termios.ECHO\n try:\n if hide_cursor:\n output.write(HIDE_CURSOR)\n if not_echo_input:\n termios.tcsetattr(output_fd, termios.TCSAFLUSH, new_attr)\n\n if animation:\n self._animate_(\n render_data, real_render_args, padding, loops, cache, output\n )\n else:\n frame = self._render_(render_data, real_render_args)\n padded_size = padding.get_padded_size(frame.render_size)\n render = (\n frame.render_output\n if frame.render_size == padded_size\n else padding.pad(frame.render_output, frame.render_size)\n )\n try:\n output.write(render)\n output.flush()\n except KeyboardInterrupt:\n self._handle_interrupted_draw_(\n render_data, real_render_args, output\n )\n raise\n finally:\n output.write(\"\\n\")\n if hide_cursor:\n output.write(SHOW_CURSOR)\n output.flush()\n if not_echo_input:\n termios.tcsetattr(output_fd, termios.TCSANOW, old_attr)\n render_data.finalize()\n\n def render(\n self,\n render_args: RenderArgs | None = None,\n padding: Padding = NO_PADDING,\n ) -> Frame:\n \"\"\":term:`Renders` the current frame.\n\n Args:\n render_args: Render arguments.\n padding: :term:`Render output` padding.\n\n Returns:\n The rendered frame.\n\n Raises:\n IncompatibleRenderArgsError: Incompatible render arguments.\n RenderError: An error occurred during :term:`rendering`.\n \"\"\"\n frame, padding = self._init_render_(self._render_, render_args, padding)\n padded_size = padding.get_padded_size(frame.render_size)\n\n return (\n frame\n if frame.render_size == padded_size\n else Frame(\n frame.number,\n frame.duration,\n padded_size,\n padding.pad(frame.render_output, frame.render_size),\n )\n )\n\n def seek(self, offset: int, whence: Seek = Seek.START) -> int:\n \"\"\"Sets the current frame number.\n\n Args:\n offset: Frame offset (relative to *whence*).\n whence: Reference position for *offset*.\n\n Returns:\n The new current frame number.\n\n Raises:\n IndefiniteSeekError: The renderable has\n :py:attr:`~term_image.renderable.FrameCount.INDEFINITE` frame count.\n ValueError: *offset* is out of range.\n\n The value range for *offset* depends on *whence*:\n\n .. list-table::\n :align: left\n :header-rows: 1\n :widths: auto\n\n * - *whence*\n - Valid value range for *offset*\n\n * - :py:attr:`~term_image.renderable.Seek.START`\n - ``0`` <= *offset* < :py:attr:`frame_count`\n * - :py:attr:`~term_image.renderable.Seek.CURRENT`\n - -:py:meth:`tell` <= *offset* < :py:attr:`frame_count` - :py:meth:`tell`\n * - :py:attr:`~term_image.renderable.Seek.END`\n - -:py:attr:`frame_count` < *offset* <= ``0``\n \"\"\"\n frame_count = self.frame_count\n\n if frame_count is FrameCount.INDEFINITE:\n raise IndefiniteSeekError(\n \"Cannot seek a renderable with INDEFINITE frame count\"\n )\n\n frame = (\n offset\n if whence is Seek.START\n else (\n self._frame + offset\n if whence is Seek.CURRENT\n else frame_count + offset - 1\n )\n )\n if not 0 <= frame < frame_count:\n raise arg_value_error_range(\n \"offset\",\n offset,\n (\n f\"whence={whence.name}, frame_count={frame_count}\"\n + (f\", current={self._frame}\" if whence is Seek.CURRENT else \"\")\n ),\n )\n self._frame = frame\n\n return frame\n\n def tell(self) -> int:\n \"\"\"Returns the current frame number.\n\n Returns:\n Zero, if the renderable is non-animated or has\n :py:attr:`~term_image.renderable.FrameCount.INDEFINITE` frame count.\n Otherwise, the current frame number.\n \"\"\"\n return self._frame\n\n # Extension methods ========================================================\n\n def _animate_(\n self,\n render_data: RenderData,\n render_args: RenderArgs,\n padding: Padding,\n loops: int,\n cache: bool | int,\n output: TextIO,\n ) -> None:\n \"\"\"Animates frames of a renderable.\n\n Args:\n render_data: Render data.\n render_args: Render arguments associated with the renderable's class.\n output: The text I/O stream to which rendered frames will be written.\n\n All other parameters are the same as for :py:meth:`draw`, except that\n *padding* must have **absolute** dimensions if it's an instance of\n :py:class:`~term_image.padding.AlignedPadding`.\n\n This is called by :py:meth:`draw` for animations.\n\n NOTE:\n * The base implementation does not finalize *render_data*.\n * :term:`Render size` validation is expected to have been performed by\n the caller.\n * When called by :py:meth:`draw` (at least, the base implementation),\n *loops* and *cache* wouldn't have been validated.\n \"\"\"\n from term_image.render import RenderIterator\n\n render_size: Size = render_data[Renderable].size\n height = render_size.height\n pad_left, _, _, pad_bottom = padding._get_exact_dimensions_(render_size)\n render_iter = RenderIterator._from_render_data_(\n self,\n render_data,\n render_args,\n padding,\n loops,\n False if loops == 1 else cache,\n finalize=False,\n )\n cursor_to_next_render_line = f\"\\n{cursor_forward(pad_left)}\"\n cursor_to_render_top_left = (\n f\"\\r{cursor_up(height - 1)}{cursor_forward(pad_left)}\"\n )\n write = output.write\n flush = output.flush\n first_frame_written = False\n\n try:\n # first frame\n try:\n frame = next(render_iter)\n except StopIteration: # `INDEFINITE` frame count\n return\n\n try:\n write(frame.render_output)\n flush()\n except KeyboardInterrupt:\n self._handle_interrupted_draw_(render_data, render_args, output)\n return\n else:\n # Move the cursor to the top-left cell of the region occupied by the\n # render output\n write(\n f\"\\r{cursor_up(height + pad_bottom - 1)}{cursor_forward(pad_left)}\"\n )\n flush()\n\n first_frame_written = True\n\n # Padding has been drawn with the first frame, only the actual render is\n # needed henceforth.\n render_iter.set_padding(NO_PADDING)\n\n # render next frame during previous frame's duration\n duration_ms = frame.duration\n start_ns = perf_counter_ns()\n\n for frame in render_iter: # Render next frame\n # left-over of previous frame's duration\n sleep(\n max(0, duration_ms * 10**6 - (perf_counter_ns() - start_ns)) / 10**9\n )\n\n # clear previous frame, if necessary\n self._clear_frame_(render_data, render_args, pad_left + 1, output)\n\n # draw next frame\n try:\n write(frame.render_output.replace(\"\\n\", cursor_to_next_render_line))\n flush()\n except KeyboardInterrupt:\n self._handle_interrupted_draw_(render_data, render_args, output)\n return\n\n write(cursor_to_render_top_left)\n flush()\n\n # render next frame during previous frame's duration\n start_ns = perf_counter_ns()\n duration_ms = frame.duration\n\n # left-over of last frame's duration\n sleep(max(0, duration_ms * 10**6 - (perf_counter_ns() - start_ns)) / 10**9)\n except KeyboardInterrupt:\n pass\n finally:\n render_iter.close()\n if first_frame_written:\n # Move the cursor to the last line to prevent \"overlaid\" output\n write(cursor_down(height + pad_bottom - 1))\n flush()\n\n def _clear_frame_(\n self,\n render_data: RenderData,\n render_args: RenderArgs,\n cursor_x: int,\n output: TextIO,\n ) -> None:\n \"\"\"Clears the previous frame of an animation, if necessary.\n\n Args:\n render_data: Render data.\n render_args: Render arguments.\n cursor_x: Column/horizontal position of the cursor at the point of calling\n this method.\n\n .. note:: The position is **1-based** i.e the leftmost column on the\n screen is at position 1 (one).\n\n output: The text I/O stream to which frames of the animation are being\n written.\n\n Called by the base implementation of :py:meth:`_animate_` just before drawing\n the next frame of an animation.\n\n Upon calling this method, the cursor should be positioned at the top-left-most\n cell of the region occupied by the frame render output on the terminal screen.\n\n Upon return, ensure the cursor is at the same position it was at the point of\n calling this method (at least logically, since *output* shouldn't be flushed\n yet).\n\n The base implementation does nothing.\n\n NOTE:\n * This is required only if drawing the next frame doesn't inherently\n overwrite the previous frame.\n * This is only meant (and should only be used) as a last resort since\n clearing the previous frame before drawing the next may result in\n visible flicker.\n * Ensure whatever this method does doesn't result in the screen being\n scrolled.\n\n TIP:\n To reduce flicker, it's advisable to **not** flush *output*. It will be\n flushed after writing the next frame.\n \"\"\"\n\n @classmethod\n def _finalize_render_data_(cls, render_data: RenderData) -> None:\n \"\"\"Finalizes render data.\n\n Args:\n render_data: Render data.\n\n Typically, an overriding method should\n\n * finalize the data generated by :py:meth:`_get_render_data_` of the\n **same class**, if necessary,\n * call the overridden method, passing on *render_data*.\n\n NOTE:\n * It's recommended to call :py:meth:`RenderData.finalize()\n `\n instead as that assures a single invocation of this method.\n * Any definition of this method should be safe for multiple invocations on\n the same :py:class:`~term_image.renderable.RenderData` instance, just in\n case.\n\n .. seealso::\n :py:meth:`_get_render_data_`,\n :py:meth:`RenderData.finalize()\n `,\n the *finalize* parameter of :py:meth:`_init_render_`.\n \"\"\"\n\n def _get_frame_count_(self) -> int | Literal[FrameCount.INDEFINITE]:\n \"\"\"Implements :py:attr:`~term_image.renderable.FrameCount.POSTPONED` frame\n count evaluation.\n\n Returns:\n The frame count of the renderable. See :py:attr:`frame_count`.\n\n .. note::\n Returning :py:attr:`~term_image.renderable.FrameCount.POSTPONED` or\n ``1`` (one) is invalid and may result in unexpected/undefined behaviour\n across various interfaces defined by this library (and those derived\n from them), since re-postponing evaluation is unsupported and the\n renderable would have been taken to be animated.\n\n The base implementation raises :py:class:`NotImplementedError`.\n \"\"\"\n raise NotImplementedError(\"POSTPONED frame count evaluation isn't implemented\")\n\n def _get_render_data_(self, *, iteration: bool) -> RenderData:\n \"\"\"Generates data required for rendering that's based on internal or\n external state.\n\n Args:\n iteration: Whether the render operation requiring the data involves a\n sequence of :term:`renders` (most likely of different frames), or it's\n a one-off render.\n\n Returns:\n The generated render data.\n\n The render data should include **copies** of any **variable/mutable**\n internal/external state required for rendering and other data generated from\n constant state but which should **persist** throughout a render operation\n (which may involve consecutive/repeated renders of one or more frames).\n\n May also be used to \"allocate\" and initialize storage for mutable/variable\n data specific to a render operation.\n\n Typically, an overriding method should\n\n * call the overridden method,\n * update the namespace for its defining class (i.e\n :py:meth:`render_data[__class__]\n `) within the\n :py:class:`~term_image.renderable.RenderData` instance returned by the\n overridden method,\n * return the same :py:class:`~term_image.renderable.RenderData` instance.\n\n IMPORTANT:\n The :py:class:`~term_image.renderable.RenderData` instance returned must be\n associated [#rd-ass]_ with the type of the renderable on which this method\n is called i.e ``type(self)``. This is always the case for the base\n implementation of this method.\n\n NOTE:\n This method being called doesn't mean the data generated will be used\n immediately.\n\n .. seealso::\n :py:class:`~term_image.renderable.RenderData`,\n :py:meth:`_finalize_render_data_`,\n :py:meth:`~term_image.renderable.Renderable._init_render_`.\n \"\"\"\n render_data = RenderData(type(self))\n renderable_data: RenderableData = render_data[Renderable]\n renderable_data.update(\n size=self._get_render_size_(),\n frame_offset=self._frame,\n seek_whence=Seek.START,\n iteration=iteration,\n )\n if self.animated:\n renderable_data.duration = self._frame_duration\n\n return render_data\n\n @abstractmethod\n def _get_render_size_(self) -> geometry.Size:\n \"\"\"Returns the renderable's :term:`render size`.\n\n Returns:\n The size of the renderable's :term:`render output`.\n\n The base implementation raises :py:class:`NotImplementedError`.\n\n NOTE:\n Both dimensions are expected to be positive.\n\n .. seealso:: :py:attr:`render_size`\n \"\"\"\n raise NotImplementedError\n\n def _handle_interrupted_draw_(\n self, render_data: RenderData, render_args: RenderArgs, output: TextIO\n ) -> None:\n \"\"\"Performs any special handling necessary when an interruption occurs while\n writing a :term:`render output` to a stream.\n\n Args:\n render_data: Render data.\n render_args: Render arguments.\n output: The text I/O stream to which the render output was being written.\n\n Called by the base implementations of :py:meth:`draw` (for non-animations)\n and :py:meth:`_animate_` when :py:class:`KeyboardInterrupt` is raised while\n writing a render output.\n\n The base implementation does nothing.\n\n NOTE:\n *output* should be flushed by this method.\n\n HINT:\n For a renderable that uses SGR sequences in its render output, this method\n may write ``CSI 0 m`` to *output*.\n \"\"\"\n\n # *render_args*, no *padding*; or neither\n @overload\n def _init_render_(\n self,\n renderer: Callable[[RenderData, RenderArgs], T],\n render_args: RenderArgs | None = None,\n *,\n iteration: bool = False,\n finalize: bool = True,\n check_size: bool = False,\n allow_scroll: bool = False,\n ) -> tuple[T, None]: ...\n\n # both *render_args* and *padding*\n @overload\n def _init_render_(\n self,\n renderer: Callable[[RenderData, RenderArgs], T],\n render_args: RenderArgs | None,\n padding: OptionalPaddingT,\n *,\n iteration: bool = False,\n finalize: bool = True,\n check_size: bool = False,\n allow_scroll: bool = False,\n ) -> tuple[T, OptionalPaddingT]: ...\n\n # *padding*, no *render_args*\n @overload\n def _init_render_(\n self,\n renderer: Callable[[RenderData, RenderArgs], T],\n *,\n padding: OptionalPaddingT,\n iteration: bool = False,\n finalize: bool = True,\n check_size: bool = False,\n allow_scroll: bool = False,\n ) -> tuple[T, OptionalPaddingT]: ...\n\n def _init_render_(\n self,\n renderer: Callable[[RenderData, RenderArgs], T],\n render_args: RenderArgs | None = None,\n padding: Padding | None = None,\n *,\n iteration: bool = False,\n finalize: bool = True,\n check_size: bool = False,\n allow_scroll: bool = False,\n ) -> tuple[T, Padding | None]:\n \"\"\"Initiates a render operation.\n\n Args:\n renderer: Performs a render operation or extracts render data and arguments\n for a render operation to be performed later on.\n render_args: Render arguments.\n padding (:py:data:`OptionalPaddingT`): :term:`Render output` padding.\n iteration: Whether the render operation involves a sequence of renders\n (most likely of different frames), or it's a one-off render.\n finalize: Whether to finalize the render data passed to *renderer*\n immediately *renderer* returns.\n check_size: Whether to validate the [padded] :term:`render size` of\n **non-animations**.\n allow_scroll: Whether to validate the [padded] :term:`render height` of\n **non-animations**. Ignored if *check_size* is ``False``.\n\n Returns:\n A tuple containing\n\n * The return value of *renderer*.\n * *padding* (with equivalent **absolute** dimensions if it's an instance of\n :py:class:`~term_image.padding.AlignedPadding`).\n\n Raises:\n IncompatibleRenderArgsError: Incompatible render arguments.\n RenderSizeOutofRangeError: *check_size* is ``True`` and the [padded]\n :term:`render size` cannot fit into the :term:`terminal size`.\n\n :rtype: tuple[T, :py:data:`OptionalPaddingT`]\n\n After preparing render data and processing arguments, *renderer* is called with\n the following positional arguments:\n\n 1. Render data associated with **the renderable's class**\n 2. Render arguments associated with **the renderable's class** and initialized\n with *render_args*\n\n Any exception raised by *renderer* is propagated.\n\n IMPORTANT:\n Beyond this method (i.e any context from *renderer* onwards), use of any\n variable state (internal or external) should be avoided if possible.\n Any variable state (internal or external) required for rendering should\n be provided via :py:meth:`_get_render_data_`.\n\n If at all any variable state has to be used and is not\n reasonable/practicable to be provided via :py:meth:`_get_render_data_`,\n it should be read only once during a single render and passed to any\n nested/subsequent calls that require the value of that state during the\n same render.\n\n This is to prevent inconsistency in data used for the same render which may\n result in unexpected output.\n \"\"\"\n if not (render_args and render_args.render_cls is type(self)):\n # Validate compatibility (and convert, if compatible)\n render_args = RenderArgs(type(self), render_args)\n terminal_size = get_terminal_size()\n render_data = self._get_render_data_(iteration=iteration)\n try:\n if padding and isinstance(padding, AlignedPadding) and padding.relative:\n padding = padding.resolve(terminal_size)\n\n if check_size:\n render_size: Size = render_data[Renderable].size\n width, height = (\n padding.get_padded_size(render_size) if padding else render_size\n )\n terminal_width, terminal_height = terminal_size\n\n if width > terminal_width:\n raise RenderSizeOutofRangeError(\n f\"{'Padded render' if padding else 'Render'} width out of \"\n f\"range (got: {width}; terminal_width={terminal_width})\"\n )\n if not allow_scroll and height > terminal_height:\n raise RenderSizeOutofRangeError(\n f\"{'Padded render' if padding else 'Render'} height out of \"\n f\"range (got: {height}; terminal_height={terminal_height})\"\n )\n\n return renderer(render_data, render_args), padding\n finally:\n if finalize:\n render_data.finalize()\n\n @abstractmethod\n def _render_(self, render_data: RenderData, render_args: RenderArgs) -> Frame:\n \"\"\":term:`Renders` a frame.\n\n Args:\n render_data: Render data.\n render_args: Render arguments.\n\n Returns:\n The rendered frame.\n\n * The :py:attr:`~term_image.renderable.Frame.render_size` field =\n :py:attr:`render_data[Renderable].size\n `.\n * The :py:attr:`~term_image.renderable.Frame.render_output` field holds the\n :term:`render output`. This string should:\n\n * contain as many lines as ``render_size.height`` i.e exactly\n ``render_size.height - 1`` occurrences of ``\\\\n`` (the newline\n sequence).\n * occupy exactly ``render_size.height`` lines and ``render_size.width``\n columns on each line when drawn onto a terminal screen, **at least**\n when the render **size** it not greater than the terminal size on\n either axis.\n\n .. tip::\n If for any reason, the output behaves differently when the render\n **height** is greater than the terminal height, the behaviour, along\n with any possible alternatives or workarounds, should be duely noted.\n This doesn't apply to the **width**.\n\n * **not** end with ``\\\\n`` (the newline sequence).\n\n * As for the :py:attr:`~term_image.renderable.Frame.duration` field, if\n the renderable is:\n\n * **animated**; the value should be determined from the frame data\n source (or a default/fallback value, if undeterminable), if\n :py:attr:`render_data[Renderable].duration\n ` is\n :py:attr:`~term_image.renderable.FrameDuration.DYNAMIC`.\n Otherwise, it should be equal to\n :py:attr:`render_data[Renderable].duration\n `.\n * **non-animated**; the value range is unspecified i.e it may be given\n any value.\n\n Raises:\n StopIteration: End of iteration for an animated renderable with\n :py:attr:`~term_image.renderable.FrameCount.INDEFINITE` frame count.\n RenderError: An error occurred while rendering.\n\n NOTE:\n :py:class:`StopIteration` may be raised if and only if\n :py:attr:`render_data[Renderable].iteration\n ` is ``True``.\n Otherwise, it would be out of place.\n\n .. seealso:: :py:class:`~term_image.renderable.RenderableData`.\n \"\"\"\n raise NotImplementedError\n\n\n# Source: src/term_image/renderable/_types.py\nclass ArgsNamespace(ArgsDataNamespace, metaclass=ArgsNamespaceMeta, _base=True):\n \"\"\"ArgsNamespace(*values, **fields)\n\n :term:`Render class`\\\\ -specific render argument namespace.\n\n Args:\n values: Render argument field values.\n\n The values are mapped to fields in the order in which the fields were\n defined.\n\n fields: Render argument fields.\n\n The keywords must be names of render argument fields for the associated\n [#an-ass]_ render class.\n\n Raises:\n UnassociatedNamespaceError: The namespace class hasn't been associated\n [#an-ass]_ with a render class.\n TypeError: More values (positional arguments) than there are fields.\n UnknownArgsFieldError: Unknown field name(s).\n TypeError: Multiple values given for a field.\n\n If no value is given for a field, its default value is used.\n\n NOTE:\n * Fields are exposed as instance attributes.\n * Instances are immutable but updated copies can be created via\n :py:meth:`update`.\n\n .. Completed in /docs/source/api/renderable.rst\n \"\"\"\n\n def __init__(self, *values: Any, **fields: Any) -> None:\n default_fields = type(self)._FIELDS\n\n if len(values) > len(default_fields):\n raise TypeError(\n f\"{type(self).__name__!r} defines {len(default_fields)} render \"\n f\"argument field(s) but {len(values)} values were given\"\n )\n value_fields = dict(zip(default_fields, values))\n\n unknown = fields.keys() - default_fields.keys()\n if unknown:\n raise UnknownArgsFieldError(\n f\"Unknown render argument fields {tuple(unknown)} for \"\n f\"{type(self)._RENDER_CLS.__name__!r}\"\n )\n multiple = fields.keys() & value_fields.keys()\n if multiple:\n raise TypeError(\n f\"Got multiple values for render argument fields \"\n f\"{tuple(multiple)} of {type(self)._RENDER_CLS.__name__!r}\"\n )\n\n super().__init__({**default_fields, **value_fields, **fields})\n\n def __repr__(self) -> str:\n return \"\".join(\n (\n f\"{type(self).__name__}(\",\n \", \".join(\n f\"{name}={getattr(self, name)!r}\" for name in type(self)._FIELDS\n ),\n \")\",\n )\n )\n\n def __getattr__(self, name: str) -> Never:\n raise UnknownArgsFieldError(\n f\"Unknown render argument field {name!r} for \"\n f\"{type(self)._RENDER_CLS.__name__!r}\"\n )\n\n def __setattr__(self, name: str, value: Never) -> Never:\n raise AttributeError(\n \"Cannot modify render argument fields, use the `update()` method \"\n \"of the namespace or the containing `RenderArgs` instance, as \"\n \"applicable, instead\"\n )\n\n def __eq__(self, other: object) -> bool:\n \"\"\"Compares the namespace with another.\n\n Args:\n other: Another render argument namespace.\n\n Returns:\n ``True`` if both operands are associated with the same\n :term:`render class` and have equal field values.\n Otherwise, ``False``.\n \"\"\"\n if isinstance(other, ArgsNamespace):\n return self is other or (\n type(self)._RENDER_CLS is type(other)._RENDER_CLS\n and all(\n getattr(self, name) == getattr(other, name)\n for name in type(self)._FIELDS\n )\n )\n\n return NotImplemented\n\n def __hash__(self) -> int:\n \"\"\"Computes the hash of the namespace.\n\n Returns:\n The computed hash.\n\n IMPORTANT:\n Like tuples, an instance is hashable if and only if the field values\n are hashable.\n \"\"\"\n # Field names and their order is the same for all instances associated\n # with the same render class.\n return hash(\n (\n type(self)._RENDER_CLS,\n tuple([getattr(self, field) for field in type(self)._FIELDS]),\n )\n )\n\n def __or__(self, other: ArgsNamespace | RenderArgs) -> RenderArgs:\n \"\"\"Derives a set of render arguments from the combination of both operands.\n\n Args:\n other: Another render argument namespace or a set of render arguments.\n\n Returns:\n A set of render arguments associated with the **most derived** one\n of the associated :term:`render classes` of both operands.\n\n Raises:\n IncompatibleArgsNamespaceError: *other* is a render argument namespace\n and neither operand is compatible [#ra-com]_ [#an-com]_ with the\n associated :term:`render class` of the other.\n IncompatibleRenderArgsError: *other* is a set of render arguments\n and neither operand is compatible [#ra-com]_ [#an-com]_ with the\n associated :term:`render class` of the other.\n\n NOTE:\n * If *other* is a render argument namespace associated with the\n same :term:`render class` as *self*, *other* takes precedence.\n * If *other* is a set of render arguments that contains a namespace\n associated with the same :term:`render class` as *self*, *self* takes\n precedence.\n \"\"\"\n self_render_cls = type(self)._RENDER_CLS\n\n if isinstance(other, ArgsNamespace):\n other_render_cls = type(other)._RENDER_CLS\n if self_render_cls is other_render_cls:\n return RenderArgs(other_render_cls, other)\n if issubclass(self_render_cls, other_render_cls):\n return RenderArgs(self_render_cls, self, other)\n if issubclass(other_render_cls, self_render_cls):\n return RenderArgs(other_render_cls, self, other)\n raise IncompatibleArgsNamespaceError(\n f\"A render argument namespace for {other_render_cls.__name__!r} \"\n \"cannot be combined with a render argument namespace for \"\n f\"{self_render_cls.__name__!r}.\"\n )\n\n if isinstance(other, RenderArgs):\n other_render_cls = other.render_cls\n if issubclass(self_render_cls, other_render_cls):\n return RenderArgs(self_render_cls, other, self)\n if issubclass(other_render_cls, self_render_cls):\n return RenderArgs(other_render_cls, other, self)\n raise IncompatibleRenderArgsError(\n f\"A set of render arguments for {other_render_cls.__name__!r} \"\n \"cannot be combined with a render argument namespace for \"\n f\"{self_render_cls.__name__!r}.\"\n )\n\n return NotImplemented\n\n def __pos__(self) -> RenderArgs:\n \"\"\"Creates a set of render arguments from the namespace.\n\n Returns:\n A set of render arguments associated with the same :term:`render class`\n as the namespace and initialized with the namespace.\n\n TIP:\n ``+namespace`` is shorthand for\n :py:meth:`namespace.to_render_args() `.\n \"\"\"\n return RenderArgs(type(self)._RENDER_CLS, self)\n\n def __ror__(self, other: ArgsNamespace | RenderArgs) -> RenderArgs:\n \"\"\"Same as :py:meth:`__or__` but with reflected operands.\n\n NOTE:\n Unlike :py:meth:`__or__`, if *other* is a render argument namespace\n associated with the same :term:`render class` as *self*, *self* takes\n precedence.\n \"\"\"\n # Not commutative\n if isinstance(other, ArgsNamespace) and (\n type(self)._RENDER_CLS is type(other)._RENDER_CLS\n ):\n return RenderArgs(type(self)._RENDER_CLS, self)\n\n return type(self).__or__(self, other) # All other cases are commutative\n\n def as_dict(self) -> dict[str, Any]:\n \"\"\"Copies the namespace as a dictionary.\n\n Returns:\n A dictionary mapping field names to their values.\n\n WARNING:\n The number and order of fields are guaranteed to be the same for a\n namespace class that defines fields, its subclasses, and all their\n instances; but beyond this, should not be relied upon as the details\n (such as the specific number or order) may change without notice.\n\n The order is an implementation detail of the Render Arguments/Data API\n and the number should be considered an implementation detail of the\n specific namespace subclass.\n \"\"\"\n return {name: getattr(self, name) for name in type(self)._FIELDS}\n\n @classmethod\n def get_fields(cls) -> Mapping[str, Any]:\n \"\"\"Returns the field definitions.\n\n Returns:\n A mapping of field names to their default values.\n\n WARNING:\n The number and order of fields are guaranteed to be the same for a\n namespace class that defines fields, its subclasses, and all their\n instances; but beyond this, should not be relied upon as the details\n (such as the specific number or order) may change without notice.\n\n The order is an implementation detail of the Render Arguments/Data API\n and the number should be considered an implementation detail of the\n specific namespace subclass.\n \"\"\"\n return cls._FIELDS\n\n def to_render_args(self, render_cls: type[Renderable] | None = None) -> RenderArgs:\n \"\"\"Creates a set of render arguments from the namespace.\n\n Args:\n render_cls: A :term:`render class`, with which the namespace is\n compatible [#an-com]_.\n\n Returns:\n A set of render arguments associated with *render_cls* (or the\n associated [#an-ass]_ render class of the namespace, if ``None``) and\n initialized with the namespace.\n\n Propagates exceptions raised by the\n :py:class:`~term_image.renderable.RenderArgs` constructor, as applicable.\n\n .. seealso:: :py:meth:`__pos__`.\n \"\"\"\n return RenderArgs(render_cls or type(self)._RENDER_CLS, self)\n\n def update(self, **fields: Any) -> Self:\n \"\"\"Updates render argument fields.\n\n Args:\n fields: Render argument fields.\n\n Returns:\n A namespace with the given fields updated.\n\n Raises:\n UnknownArgsFieldError: Unknown field name(s).\n \"\"\"\n if not fields:\n return self\n\n unknown = fields.keys() - type(self)._FIELDS.keys()\n if unknown:\n raise UnknownArgsFieldError(\n f\"Unknown render argument field(s) {tuple(unknown)} for \"\n f\"{type(self)._RENDER_CLS.__name__!r}\"\n )\n\n new = type(self).__new__(type(self))\n new_fields = self.as_dict()\n new_fields.update(fields)\n super(ArgsNamespace, new).__init__(new_fields)\n\n return new", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 52244}, "tests/test_padding.py::164": {"resolved_imports": ["src/term_image/_ctlseqs.py", "src/term_image/geometry.py", "src/term_image/padding.py"], "used_names": ["AlignedPadding", "VAlign", "pytest"], "enclosing_function": "test_non_default", "extracted_code": "# Source: src/term_image/padding.py\nclass VAlign(IntEnum):\n \"\"\"Vertical alignment enumeration\"\"\"\n\n TOP = 0\n \"\"\"Top vertical alignment\n\n :meta hide-value:\n \"\"\"\n\n MIDDLE = auto()\n \"\"\"Middle vertical alignment\n\n :meta hide-value:\n \"\"\"\n\n BOTTOM = auto()\n \"\"\"Bottom vertical alignment\n\n :meta hide-value:\n \"\"\"\n\nclass AlignedPadding(Padding):\n \"\"\"Aligned :term:`render output` padding.\n\n Args:\n width: Minimum :term:`render width`.\n height: Minimum :term:`render height`.\n h_align: Horizontal alignment.\n v_align: Vertical alignment.\n\n If *width* or *height* is:\n\n * positive, it is **absolute** and used as-is.\n * non-positive, it is **relative** to the corresponding terminal dimension\n (**at the point of resolution**) and equivalent to the absolute dimension\n ``max(terminal_dimension + relative_dimension, 1)``.\n\n The *padded render dimension* (i.e the dimension of a :term:`render output` after\n it's padded) on each axis is given by::\n\n padded_dimension = max(render_dimension, absolute_minimum_dimension)\n\n In words... If the **absolute** *minimum render dimension* on an axis is less than\n or equal to the corresponding *render dimension*, there is no padding on that axis\n and the *padded render dimension* on that axis is equal to the *render dimension*.\n Otherwise, the render output will be padded along that axis and the *padded render\n dimension* on that axis is equal to the *minimum render dimension*.\n\n The amount of padding to each side depends on the alignment, defined by *h_align*\n and *v_align*.\n\n IMPORTANT:\n :py:class:`RelativePaddingDimensionError` is raised if any padding-related\n computation/operation (basically, calling any method other than\n :py:meth:`resolve`) is performed on an instance with **relative** *minimum\n render dimension(s)* i.e if :py:attr:`relative` is ``True``.\n\n NOTE:\n Any interface receiving an instance with **relative** dimension(s) should\n typically resolve it/them upon reception.\n\n TIP:\n * Instances are immutable and hashable.\n * Instances with equal fields compare equal.\n \"\"\"\n\n # Class Attributes =========================================================\n\n __slots__ = (\"width\", \"height\", \"h_align\", \"v_align\", \"relative\")\n\n # Instance Attributes ======================================================\n\n width: int\n \"\"\"Minimum :term:`render width`\"\"\"\n\n height: int\n \"\"\"Minimum :term:`render height`\"\"\"\n\n h_align: HAlign\n \"\"\"Horizontal alignment\"\"\"\n\n v_align: VAlign\n \"\"\"Vertical alignment\"\"\"\n\n fill: str\n\n relative: bool\n \"\"\"``True`` if either or both *minimum render dimension(s)* is/are relative i.e\n non-positive. Otherwise, ``False``.\n \"\"\"\n\n # Special Methods ==========================================================\n\n def __init__(\n self,\n width: int,\n height: int,\n h_align: HAlign = HAlign.CENTER,\n v_align: VAlign = VAlign.MIDDLE,\n fill: str = \" \",\n ):\n super().__init__(fill)\n\n _setattr = super().__setattr__\n _setattr(\"width\", width)\n _setattr(\"height\", height)\n _setattr(\"h_align\", h_align)\n _setattr(\"v_align\", v_align)\n _setattr(\"relative\", not width > 0 < height)\n\n def __repr__(self) -> str:\n return \"{}(width={}, height={}, h_align={}, v_align={}, fill={!r})\".format(\n type(self).__name__,\n self.width,\n self.height,\n self.h_align.name,\n self.v_align.name,\n self.fill,\n )\n\n # Properties ===============================================================\n\n @property\n def size(self) -> RawSize:\n \"\"\"Minimum :term:`render size`\n\n GET:\n Returns the *minimum render dimensions*.\n \"\"\"\n return _RawSize(self.width, self.height)\n\n # Public Methods ===========================================================\n\n @override\n def get_padded_size(self, render_size: Size) -> Size:\n \"\"\"Computes an expected padded :term:`render size`.\n\n See :py:meth:`Padding.get_padded_size`.\n\n Raises:\n RelativePaddingDimensionError: Relative *minimum render dimension(s)*.\n \"\"\"\n if self.relative:\n raise RelativePaddingDimensionError(\"Relative minimum render dimension(s)\")\n\n return _Size(max(self.width, render_size[0]), max(self.height, render_size[1]))\n\n def resolve(self, terminal_size: os.terminal_size) -> AlignedPadding:\n \"\"\"Resolves **relative** *minimum render dimensions*.\n\n Args:\n terminal_size: The terminal size against which to resolve relative\n dimensions.\n\n Returns:\n An instance with equivalent **absolute** dimensions.\n \"\"\"\n if not self.relative:\n return self\n\n width, height, *args, _ = astuple(self)\n terminal_width, terminal_height = terminal_size\n if width <= 0:\n width = max(terminal_width + width, 1)\n if height <= 0:\n height = max(terminal_height + height, 1)\n\n return type(self)(width, height, *args)\n\n # Extension methods ========================================================\n\n @override\n def _get_exact_dimensions_(self, render_size: Size) -> tuple[int, int, int, int]:\n if self.relative:\n raise RelativePaddingDimensionError(\"Relative minimum render dimension(s)\")\n\n width, height, h_align, v_align = astuple(self)[:4]\n render_width, render_height = render_size\n\n if width > render_width:\n padding_width = width - render_width\n numerator, denominator = _ALIGN_RATIOS[h_align]\n left = padding_width * numerator // denominator\n right = padding_width - left\n else:\n left = right = 0\n\n if height > render_height:\n padding_height = height - render_height\n numerator, denominator = _ALIGN_RATIOS[v_align]\n top = padding_height * numerator // denominator\n bottom = padding_height - top\n else:\n top = bottom = 0\n\n return left, top, right, bottom", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 6282}, "tests/renderable/test_types.py::1614": {"resolved_imports": ["src/term_image/geometry.py", "src/term_image/renderable/_renderable.py", "src/term_image/renderable/_types.py"], "used_names": ["DataNamespace", "Renderable", "pytest"], "enclosing_function": "test_render_cls_update", "extracted_code": "# Source: src/term_image/renderable/_renderable.py\nclass Renderable(metaclass=RenderableMeta, _base=True):\n \"\"\"A renderable.\n\n Args:\n frame_count: Number of frames. If it's a\n\n * positive integer, the number of frames is as given.\n * :py:class:`~term_image.renderable.FrameCount` enum member, see the\n member's description.\n\n If equal to 1 (one), the renderable is non-animated.\n Otherwise, it is animated.\n\n frame_duration: The duration of a frame. If it's a\n\n * positive integer, it implies a static duration (in **milliseconds**)\n i.e the same duration applies to every frame.\n * :py:class:`~term_image.renderable.FrameDuration` enum member, see the\n member's description.\n\n This argument is ignored if *frame_count* equals 1 (one)\n i.e the renderable is non-animated.\n\n Raises:\n ValueError: An argument has an invalid value.\n\n ATTENTION:\n This is an abstract base class. Hence, only **concrete** subclasses can be\n instantiated.\n\n .. seealso::\n\n :ref:`renderable-ext-api`\n :py:class:`Renderable`\\\\ 's Extension API\n \"\"\"\n\n # Class Attributes =========================================================\n\n # Initialized by `RenderableMeta` and may be updated by `ArgsNamespaceMeta`\n Args: ClassVar[type[ArgsNamespace] | None]\n \"\"\":term:`Render class`\\\\ -specific render arguments.\n\n This is either:\n\n - a render argument namespace class (subclass of :py:class:`ArgsNamespace`)\n associated [#an-ass]_ with the render class, or\n - :py:data:`None`, if the render class has no render arguments.\n\n If this is a class, an instance of it (or a subclass thereof) is contained within\n any :py:class:`RenderArgs` instance associated [#ra-ass]_ with the render class or\n any of its subclasses. Also, an instance of this class (or a subclass of it) is\n returned by :py:meth:`render_args[render_cls]\n `; where *render_args* is\n an instance of :py:class:`~term_image.renderable.RenderArgs` as previously\n described and *render_cls* is the render class with which this namespace class\n is associated [#an-ass]_.\n\n .. collapse:: Example\n\n >>> class Foo(Renderable):\n ... pass\n ...\n ... class FooArgs(ArgsNamespace, render_cls=Foo):\n ... foo: str | None = None\n ...\n >>> Foo.Args is FooArgs\n True\n >>>\n >>> # default\n >>> foo_args = Foo.Args()\n >>> foo_args\n FooArgs(foo=None)\n >>> foo_args.foo is None\n True\n >>>\n >>> render_args = RenderArgs(Foo)\n >>> render_args[Foo]\n FooArgs(foo=None)\n >>>\n >>> # non-default\n >>> foo_args = Foo.Args(\"FOO\")\n >>> foo_args\n FooArgs(foo='FOO')\n >>> foo_args.foo\n 'FOO'\n >>>\n >>> render_args = RenderArgs(Foo, foo_args.update(foo=\"bar\"))\n >>> render_args[Foo]\n FooArgs(foo='bar')\n\n On the other hand, if this is :py:data:`None`, it implies the render class has no\n render arguments.\n\n .. collapse:: Example\n\n >>> class Bar(Renderable):\n ... pass\n ...\n >>> Bar.Args is None\n True\n >>> render_args = RenderArgs(Bar)\n >>> render_args[Bar]\n Traceback (most recent call last):\n ...\n NoArgsNamespaceError: 'Bar' has no render arguments\n \"\"\"\n\n # Initialized by `RenderableMeta` and may be updated by `DataNamespaceMeta`\n _Data_: ClassVar[type[DataNamespace] | None]\n \"\"\":term:`Render class`\\\\ -specific render data.\n\n This is either:\n\n - a render data namespace class (subclass of :py:class:`DataNamespace`)\n associated [#dn-ass]_ with the render class, or\n - :py:data:`None`, if the render class has no render data.\n\n If this is a class, an instance of it (or a subclass thereof) is contained within\n any :py:class:`RenderData` instance associated [#rd-ass]_ with the render class or\n any of its subclasses. Also, an instance of this class (or a subclass of it) is\n returned by :py:meth:`render_data[render_cls]\n `; where *render_data* is\n an instance of :py:class:`~term_image.renderable.RenderData` as previously\n described and *render_cls* is the render class with which this namespace class\n is associated [#dn-ass]_.\n\n .. collapse:: Example\n\n >>> class Foo(Renderable):\n ... pass\n ...\n ... class _Data_(DataNamespace, render_cls=Foo):\n ... foo: str | None\n ...\n >>> Foo._Data_ is FooData\n True\n >>>\n >>> foo_data = Foo._Data_()\n >>> foo_data\n >\n >>> foo_data.foo\n Traceback (most recent call last):\n ...\n UninitializedDataFieldError: The render data field 'foo' of 'Foo' has not \\\nbeen initialized\n >>>\n >>> foo_data.foo = \"FOO\"\n >>> foo_data\n \n >>> foo_data.foo\n 'FOO'\n >>>\n >>> render_data = RenderData(Foo)\n >>> render_data[Foo]\n >\n >>>\n >>> render_data[Foo].foo = \"bar\"\n >>> render_data[Foo]\n \n\n On the other hand, if this is :py:data:`None`, it implies the render class has no\n render data.\n\n .. collapse:: Example\n\n >>> class Bar(Renderable):\n ... pass\n ...\n >>> Bar._Data_ is None\n True\n >>>\n >>> render_data = RenderData(Bar)\n >>> render_data[Bar]\n Traceback (most recent call last):\n ...\n NoDataNamespaceError: 'Bar' has no render data\n\n .. seealso::\n\n :py:class:`~term_image.renderable.RenderableData`\n Render data for :py:class:`~term_image.renderable.Renderable`.\n \"\"\"\n\n _EXPORTED_ATTRS_: ClassVar[tuple[str, ...]]\n \"\"\"Exported attributes.\n\n This specifies class attributes defined by the class (not a parent) on itself\n **but not** its subclasses which should be exported to definitions of the class\n in subprocesses.\n\n These attributes are typically assigned using ``__class__.*`` within methods.\n\n NOTE:\n * Defining this is optional.\n * The attributes are exported for a class if and only if they are defined\n on that class when starting a subprocess.\n * The attributes are exported only for subprocesses started via\n :py:class:`multiprocessing.Process`.\n\n TIP:\n This can be used to export \"private\" attributes of the class across\n subprocesses.\n \"\"\"\n\n _EXPORTED_DESCENDANT_ATTRS_: ClassVar[tuple[str, ...]]\n \"\"\"Exported :term:`descendant` attributes.\n\n This specifies class attributes defined by the class (not a parent) on itself\n **and** its subclasses (i.e :term:`descendant` attributes) which should be exported\n to definitions of the class and its subclasses in subprocesses.\n\n These attributes are typically assigned using ``cls.*`` within class methods.\n\n This extends the exported descendant attributes of parent classes i.e all\n exported descendant attributes of a class are also exported for its subclasses.\n\n NOTE:\n * Defining this is optional.\n * The attributes are exported for a class if and only if they are defined\n on that class when starting a subprocess.\n * The attributes are exported only for subprocesses started via\n :py:class:`multiprocessing.Process`.\n\n TIP:\n This can be used to export \"private\" :term:`descendant` attributes of the\n class across subprocesses.\n \"\"\"\n\n _ALL_DEFAULT_ARGS: ClassVar[MappingProxyType[type[Renderable], ArgsNamespace]]\n _RENDER_DATA_MRO: ClassVar[MappingProxyType[type[Renderable], type[DataNamespace]]]\n _ALL_EXPORTED_ATTRS: ClassVar[tuple[str, ...]]\n\n # Instance Attributes ======================================================\n\n animated: bool\n \"\"\"``True`` if the renderable is :term:`animated`. Otherwise, ``False``.\"\"\"\n\n _frame: int\n _frame_count: int | FrameCount\n _frame_duration: int | FrameDuration\n\n # Special Methods ==========================================================\n\n def __init__(\n self,\n frame_count: int | FrameCount,\n frame_duration: int | FrameDuration,\n ) -> None:\n if isinstance(frame_count, int) and frame_count < 1:\n raise arg_value_error_range(\"frame_count\", frame_count)\n\n if frame_count != 1:\n if isinstance(frame_duration, int) and frame_duration <= 0:\n raise arg_value_error_range(\"frame_duration\", frame_duration)\n self._frame_duration = frame_duration\n\n self.animated = frame_count != 1\n self._frame_count = frame_count\n self._frame = 0\n\n def __iter__(self) -> term_image.render.RenderIterator:\n \"\"\"Returns a render iterator.\n\n Returns:\n A render iterator (with frame caching disabled and all other optional\n arguments to :py:class:`~term_image.render.RenderIterator` being the\n default values).\n\n Raises:\n NonAnimatedRenderableError: The renderable is non-animated.\n\n :term:`Animated` renderables are iterable i.e they can be used with various\n means of iteration such as the ``for`` statement and iterable unpacking.\n \"\"\"\n from term_image.render import RenderIterator\n\n try:\n return RenderIterator(self, cache=False)\n except ValueError:\n raise NonAnimatedRenderableError(\n \"Non-animated renderables are not iterable\"\n ) from None\n\n def __repr__(self) -> str:\n return f\"<{type(self).__name__}: frame_count={self._frame_count}>\"\n\n def __str__(self) -> str:\n \"\"\":term:`Renders` the current frame with default arguments and no padding.\n\n Returns:\n The frame :term:`render output`.\n\n Raises:\n RenderError: An error occurred during :term:`rendering`.\n \"\"\"\n return self._init_render_(self._render_)[0].render_output\n\n # Properties ===============================================================\n\n @property\n def frame_count(self) -> int | Literal[FrameCount.INDEFINITE]:\n \"\"\"Frame count\n\n GET:\n Returns either\n\n * the number of frames the renderable has, or\n * :py:attr:`~term_image.renderable.FrameCount.INDEFINITE`.\n \"\"\"\n if self._frame_count is FrameCount.POSTPONED:\n self._frame_count = self._get_frame_count_()\n\n return self._frame_count\n\n @property\n def frame_duration(self) -> int | FrameDuration:\n \"\"\"Frame duration\n\n GET:\n Returns\n\n * a positive integer, a static duration (in **milliseconds**) i.e the\n same duration applies to every frame; or\n * :py:attr:`~term_image.renderable.FrameDuration.DYNAMIC`.\n\n SET:\n If the value is\n\n * a positive integer, it implies a static duration (in **milliseconds**)\n i.e the same duration applies to every frame.\n * :py:attr:`~term_image.renderable.FrameDuration.DYNAMIC`, see the\n enum member's description.\n\n Raises:\n NonAnimatedRenderableError: The renderable is non-animated.\n \"\"\"\n try:\n return self._frame_duration\n except AttributeError:\n if not self.animated:\n raise NonAnimatedRenderableError(\n \"Non-animated renderables have no frame duration\"\n ) from None\n raise\n\n @frame_duration.setter\n def frame_duration(self, duration: int | FrameDuration) -> None:\n if not self.animated:\n raise NonAnimatedRenderableError(\n \"Cannot set frame duration for a non-animated renderable\"\n )\n\n if isinstance(duration, int) and duration <= 0:\n raise arg_value_error_range(\"frame_duration\", duration)\n\n self._frame_duration = duration\n\n @property\n def render_size(self) -> geometry.Size:\n \"\"\":term:`Render size`\n\n GET:\n Returns the size of the renderable's :term:`render output`.\n \"\"\"\n return self._get_render_size_()\n\n # Public Methods ===========================================================\n\n def draw(\n self,\n render_args: RenderArgs | None = None,\n padding: Padding = AlignedPadding(0, -2),\n *,\n animate: bool = True,\n loops: int = -1,\n cache: bool | int = 100,\n check_size: bool = True,\n allow_scroll: bool = False,\n hide_cursor: bool = True,\n echo_input: bool = False,\n ) -> None:\n \"\"\"Draws the current frame or an animation to standard output.\n\n Args:\n render_args: Render arguments.\n padding: :term:`Render output` padding.\n animate: Whether to enable animation for :term:`animated` renderables.\n If disabled, only the current frame is drawn.\n loops: See :py:class:`~term_image.render.RenderIterator`\n (applies to **animations only**).\n cache: See :py:class:`~term_image.render.RenderIterator`.\n (applies to **animations only**).\n check_size: Whether to validate the padded :term:`render size` of\n **non-animations**.\n allow_scroll: Whether to validate the padded :term:`render height` of\n **non-animations**. Ignored if *check_size* is ``False``.\n hide_cursor: Whether to hide the cursor **while drawing**.\n echo_input: Whether to display input **while drawing** (applies on **Unix\n only**).\n\n .. note::\n * If disabled (default), input is not read/consumed, it's just not\n displayed.\n * If enabled, echoed input may affect cursor positioning and\n therefore, the output (especially for animations).\n\n Raises:\n RenderSizeOutofRangeError: The padded :term:`render size` can not fit into\n the :term:`terminal size`.\n IncompatibleRenderArgsError: Incompatible render arguments.\n RenderError: An error occurred during :term:`rendering`.\n\n If *check_size* is ``True`` (or it's an animation),\n\n * the padded :term:`render width` must not be greater than the\n :term:`terminal width`.\n * and *allow_scroll* is ``False`` (or it's an animation), the padded\n :term:`render height` must not be greater than the :term:`terminal height`.\n\n NOTE:\n * *hide_cursor* and *echo_input* apply if and only if the output stream\n is connected to a terminal.\n * For animations (i.e animated renderables with *animate* = ``True``),\n the padded :term:`render size` is always validated.\n * Animations with **definite** frame count, **by default**, are infinitely\n looped but can be terminated with :py:data:`~signal.SIGINT`\n (``CTRL + C``), **without** raising :py:class:`KeyboardInterrupt`.\n \"\"\"\n animation = self.animated and animate\n output = sys.stdout\n not_echo_input = OS_IS_UNIX and not echo_input and output.isatty()\n hide_cursor = hide_cursor and output.isatty()\n\n # Validate size and get render data and args\n render_data: RenderData\n real_render_args: RenderArgs\n (render_data, real_render_args), padding = self._init_render_(\n lambda *args: args,\n render_args,\n padding,\n iteration=animation,\n finalize=False,\n check_size=animation or check_size,\n allow_scroll=not animation and allow_scroll,\n )\n\n if not_echo_input:\n output_fd = output.fileno()\n old_attr = termios.tcgetattr(output_fd)\n new_attr = termios.tcgetattr(output_fd)\n new_attr[3] &= ~termios.ECHO\n try:\n if hide_cursor:\n output.write(HIDE_CURSOR)\n if not_echo_input:\n termios.tcsetattr(output_fd, termios.TCSAFLUSH, new_attr)\n\n if animation:\n self._animate_(\n render_data, real_render_args, padding, loops, cache, output\n )\n else:\n frame = self._render_(render_data, real_render_args)\n padded_size = padding.get_padded_size(frame.render_size)\n render = (\n frame.render_output\n if frame.render_size == padded_size\n else padding.pad(frame.render_output, frame.render_size)\n )\n try:\n output.write(render)\n output.flush()\n except KeyboardInterrupt:\n self._handle_interrupted_draw_(\n render_data, real_render_args, output\n )\n raise\n finally:\n output.write(\"\\n\")\n if hide_cursor:\n output.write(SHOW_CURSOR)\n output.flush()\n if not_echo_input:\n termios.tcsetattr(output_fd, termios.TCSANOW, old_attr)\n render_data.finalize()\n\n def render(\n self,\n render_args: RenderArgs | None = None,\n padding: Padding = NO_PADDING,\n ) -> Frame:\n \"\"\":term:`Renders` the current frame.\n\n Args:\n render_args: Render arguments.\n padding: :term:`Render output` padding.\n\n Returns:\n The rendered frame.\n\n Raises:\n IncompatibleRenderArgsError: Incompatible render arguments.\n RenderError: An error occurred during :term:`rendering`.\n \"\"\"\n frame, padding = self._init_render_(self._render_, render_args, padding)\n padded_size = padding.get_padded_size(frame.render_size)\n\n return (\n frame\n if frame.render_size == padded_size\n else Frame(\n frame.number,\n frame.duration,\n padded_size,\n padding.pad(frame.render_output, frame.render_size),\n )\n )\n\n def seek(self, offset: int, whence: Seek = Seek.START) -> int:\n \"\"\"Sets the current frame number.\n\n Args:\n offset: Frame offset (relative to *whence*).\n whence: Reference position for *offset*.\n\n Returns:\n The new current frame number.\n\n Raises:\n IndefiniteSeekError: The renderable has\n :py:attr:`~term_image.renderable.FrameCount.INDEFINITE` frame count.\n ValueError: *offset* is out of range.\n\n The value range for *offset* depends on *whence*:\n\n .. list-table::\n :align: left\n :header-rows: 1\n :widths: auto\n\n * - *whence*\n - Valid value range for *offset*\n\n * - :py:attr:`~term_image.renderable.Seek.START`\n - ``0`` <= *offset* < :py:attr:`frame_count`\n * - :py:attr:`~term_image.renderable.Seek.CURRENT`\n - -:py:meth:`tell` <= *offset* < :py:attr:`frame_count` - :py:meth:`tell`\n * - :py:attr:`~term_image.renderable.Seek.END`\n - -:py:attr:`frame_count` < *offset* <= ``0``\n \"\"\"\n frame_count = self.frame_count\n\n if frame_count is FrameCount.INDEFINITE:\n raise IndefiniteSeekError(\n \"Cannot seek a renderable with INDEFINITE frame count\"\n )\n\n frame = (\n offset\n if whence is Seek.START\n else (\n self._frame + offset\n if whence is Seek.CURRENT\n else frame_count + offset - 1\n )\n )\n if not 0 <= frame < frame_count:\n raise arg_value_error_range(\n \"offset\",\n offset,\n (\n f\"whence={whence.name}, frame_count={frame_count}\"\n + (f\", current={self._frame}\" if whence is Seek.CURRENT else \"\")\n ),\n )\n self._frame = frame\n\n return frame\n\n def tell(self) -> int:\n \"\"\"Returns the current frame number.\n\n Returns:\n Zero, if the renderable is non-animated or has\n :py:attr:`~term_image.renderable.FrameCount.INDEFINITE` frame count.\n Otherwise, the current frame number.\n \"\"\"\n return self._frame\n\n # Extension methods ========================================================\n\n def _animate_(\n self,\n render_data: RenderData,\n render_args: RenderArgs,\n padding: Padding,\n loops: int,\n cache: bool | int,\n output: TextIO,\n ) -> None:\n \"\"\"Animates frames of a renderable.\n\n Args:\n render_data: Render data.\n render_args: Render arguments associated with the renderable's class.\n output: The text I/O stream to which rendered frames will be written.\n\n All other parameters are the same as for :py:meth:`draw`, except that\n *padding* must have **absolute** dimensions if it's an instance of\n :py:class:`~term_image.padding.AlignedPadding`.\n\n This is called by :py:meth:`draw` for animations.\n\n NOTE:\n * The base implementation does not finalize *render_data*.\n * :term:`Render size` validation is expected to have been performed by\n the caller.\n * When called by :py:meth:`draw` (at least, the base implementation),\n *loops* and *cache* wouldn't have been validated.\n \"\"\"\n from term_image.render import RenderIterator\n\n render_size: Size = render_data[Renderable].size\n height = render_size.height\n pad_left, _, _, pad_bottom = padding._get_exact_dimensions_(render_size)\n render_iter = RenderIterator._from_render_data_(\n self,\n render_data,\n render_args,\n padding,\n loops,\n False if loops == 1 else cache,\n finalize=False,\n )\n cursor_to_next_render_line = f\"\\n{cursor_forward(pad_left)}\"\n cursor_to_render_top_left = (\n f\"\\r{cursor_up(height - 1)}{cursor_forward(pad_left)}\"\n )\n write = output.write\n flush = output.flush\n first_frame_written = False\n\n try:\n # first frame\n try:\n frame = next(render_iter)\n except StopIteration: # `INDEFINITE` frame count\n return\n\n try:\n write(frame.render_output)\n flush()\n except KeyboardInterrupt:\n self._handle_interrupted_draw_(render_data, render_args, output)\n return\n else:\n # Move the cursor to the top-left cell of the region occupied by the\n # render output\n write(\n f\"\\r{cursor_up(height + pad_bottom - 1)}{cursor_forward(pad_left)}\"\n )\n flush()\n\n first_frame_written = True\n\n # Padding has been drawn with the first frame, only the actual render is\n # needed henceforth.\n render_iter.set_padding(NO_PADDING)\n\n # render next frame during previous frame's duration\n duration_ms = frame.duration\n start_ns = perf_counter_ns()\n\n for frame in render_iter: # Render next frame\n # left-over of previous frame's duration\n sleep(\n max(0, duration_ms * 10**6 - (perf_counter_ns() - start_ns)) / 10**9\n )\n\n # clear previous frame, if necessary\n self._clear_frame_(render_data, render_args, pad_left + 1, output)\n\n # draw next frame\n try:\n write(frame.render_output.replace(\"\\n\", cursor_to_next_render_line))\n flush()\n except KeyboardInterrupt:\n self._handle_interrupted_draw_(render_data, render_args, output)\n return\n\n write(cursor_to_render_top_left)\n flush()\n\n # render next frame during previous frame's duration\n start_ns = perf_counter_ns()\n duration_ms = frame.duration\n\n # left-over of last frame's duration\n sleep(max(0, duration_ms * 10**6 - (perf_counter_ns() - start_ns)) / 10**9)\n except KeyboardInterrupt:\n pass\n finally:\n render_iter.close()\n if first_frame_written:\n # Move the cursor to the last line to prevent \"overlaid\" output\n write(cursor_down(height + pad_bottom - 1))\n flush()\n\n def _clear_frame_(\n self,\n render_data: RenderData,\n render_args: RenderArgs,\n cursor_x: int,\n output: TextIO,\n ) -> None:\n \"\"\"Clears the previous frame of an animation, if necessary.\n\n Args:\n render_data: Render data.\n render_args: Render arguments.\n cursor_x: Column/horizontal position of the cursor at the point of calling\n this method.\n\n .. note:: The position is **1-based** i.e the leftmost column on the\n screen is at position 1 (one).\n\n output: The text I/O stream to which frames of the animation are being\n written.\n\n Called by the base implementation of :py:meth:`_animate_` just before drawing\n the next frame of an animation.\n\n Upon calling this method, the cursor should be positioned at the top-left-most\n cell of the region occupied by the frame render output on the terminal screen.\n\n Upon return, ensure the cursor is at the same position it was at the point of\n calling this method (at least logically, since *output* shouldn't be flushed\n yet).\n\n The base implementation does nothing.\n\n NOTE:\n * This is required only if drawing the next frame doesn't inherently\n overwrite the previous frame.\n * This is only meant (and should only be used) as a last resort since\n clearing the previous frame before drawing the next may result in\n visible flicker.\n * Ensure whatever this method does doesn't result in the screen being\n scrolled.\n\n TIP:\n To reduce flicker, it's advisable to **not** flush *output*. It will be\n flushed after writing the next frame.\n \"\"\"\n\n @classmethod\n def _finalize_render_data_(cls, render_data: RenderData) -> None:\n \"\"\"Finalizes render data.\n\n Args:\n render_data: Render data.\n\n Typically, an overriding method should\n\n * finalize the data generated by :py:meth:`_get_render_data_` of the\n **same class**, if necessary,\n * call the overridden method, passing on *render_data*.\n\n NOTE:\n * It's recommended to call :py:meth:`RenderData.finalize()\n `\n instead as that assures a single invocation of this method.\n * Any definition of this method should be safe for multiple invocations on\n the same :py:class:`~term_image.renderable.RenderData` instance, just in\n case.\n\n .. seealso::\n :py:meth:`_get_render_data_`,\n :py:meth:`RenderData.finalize()\n `,\n the *finalize* parameter of :py:meth:`_init_render_`.\n \"\"\"\n\n def _get_frame_count_(self) -> int | Literal[FrameCount.INDEFINITE]:\n \"\"\"Implements :py:attr:`~term_image.renderable.FrameCount.POSTPONED` frame\n count evaluation.\n\n Returns:\n The frame count of the renderable. See :py:attr:`frame_count`.\n\n .. note::\n Returning :py:attr:`~term_image.renderable.FrameCount.POSTPONED` or\n ``1`` (one) is invalid and may result in unexpected/undefined behaviour\n across various interfaces defined by this library (and those derived\n from them), since re-postponing evaluation is unsupported and the\n renderable would have been taken to be animated.\n\n The base implementation raises :py:class:`NotImplementedError`.\n \"\"\"\n raise NotImplementedError(\"POSTPONED frame count evaluation isn't implemented\")\n\n def _get_render_data_(self, *, iteration: bool) -> RenderData:\n \"\"\"Generates data required for rendering that's based on internal or\n external state.\n\n Args:\n iteration: Whether the render operation requiring the data involves a\n sequence of :term:`renders` (most likely of different frames), or it's\n a one-off render.\n\n Returns:\n The generated render data.\n\n The render data should include **copies** of any **variable/mutable**\n internal/external state required for rendering and other data generated from\n constant state but which should **persist** throughout a render operation\n (which may involve consecutive/repeated renders of one or more frames).\n\n May also be used to \"allocate\" and initialize storage for mutable/variable\n data specific to a render operation.\n\n Typically, an overriding method should\n\n * call the overridden method,\n * update the namespace for its defining class (i.e\n :py:meth:`render_data[__class__]\n `) within the\n :py:class:`~term_image.renderable.RenderData` instance returned by the\n overridden method,\n * return the same :py:class:`~term_image.renderable.RenderData` instance.\n\n IMPORTANT:\n The :py:class:`~term_image.renderable.RenderData` instance returned must be\n associated [#rd-ass]_ with the type of the renderable on which this method\n is called i.e ``type(self)``. This is always the case for the base\n implementation of this method.\n\n NOTE:\n This method being called doesn't mean the data generated will be used\n immediately.\n\n .. seealso::\n :py:class:`~term_image.renderable.RenderData`,\n :py:meth:`_finalize_render_data_`,\n :py:meth:`~term_image.renderable.Renderable._init_render_`.\n \"\"\"\n render_data = RenderData(type(self))\n renderable_data: RenderableData = render_data[Renderable]\n renderable_data.update(\n size=self._get_render_size_(),\n frame_offset=self._frame,\n seek_whence=Seek.START,\n iteration=iteration,\n )\n if self.animated:\n renderable_data.duration = self._frame_duration\n\n return render_data\n\n @abstractmethod\n def _get_render_size_(self) -> geometry.Size:\n \"\"\"Returns the renderable's :term:`render size`.\n\n Returns:\n The size of the renderable's :term:`render output`.\n\n The base implementation raises :py:class:`NotImplementedError`.\n\n NOTE:\n Both dimensions are expected to be positive.\n\n .. seealso:: :py:attr:`render_size`\n \"\"\"\n raise NotImplementedError\n\n def _handle_interrupted_draw_(\n self, render_data: RenderData, render_args: RenderArgs, output: TextIO\n ) -> None:\n \"\"\"Performs any special handling necessary when an interruption occurs while\n writing a :term:`render output` to a stream.\n\n Args:\n render_data: Render data.\n render_args: Render arguments.\n output: The text I/O stream to which the render output was being written.\n\n Called by the base implementations of :py:meth:`draw` (for non-animations)\n and :py:meth:`_animate_` when :py:class:`KeyboardInterrupt` is raised while\n writing a render output.\n\n The base implementation does nothing.\n\n NOTE:\n *output* should be flushed by this method.\n\n HINT:\n For a renderable that uses SGR sequences in its render output, this method\n may write ``CSI 0 m`` to *output*.\n \"\"\"\n\n # *render_args*, no *padding*; or neither\n @overload\n def _init_render_(\n self,\n renderer: Callable[[RenderData, RenderArgs], T],\n render_args: RenderArgs | None = None,\n *,\n iteration: bool = False,\n finalize: bool = True,\n check_size: bool = False,\n allow_scroll: bool = False,\n ) -> tuple[T, None]: ...\n\n # both *render_args* and *padding*\n @overload\n def _init_render_(\n self,\n renderer: Callable[[RenderData, RenderArgs], T],\n render_args: RenderArgs | None,\n padding: OptionalPaddingT,\n *,\n iteration: bool = False,\n finalize: bool = True,\n check_size: bool = False,\n allow_scroll: bool = False,\n ) -> tuple[T, OptionalPaddingT]: ...\n\n # *padding*, no *render_args*\n @overload\n def _init_render_(\n self,\n renderer: Callable[[RenderData, RenderArgs], T],\n *,\n padding: OptionalPaddingT,\n iteration: bool = False,\n finalize: bool = True,\n check_size: bool = False,\n allow_scroll: bool = False,\n ) -> tuple[T, OptionalPaddingT]: ...\n\n def _init_render_(\n self,\n renderer: Callable[[RenderData, RenderArgs], T],\n render_args: RenderArgs | None = None,\n padding: Padding | None = None,\n *,\n iteration: bool = False,\n finalize: bool = True,\n check_size: bool = False,\n allow_scroll: bool = False,\n ) -> tuple[T, Padding | None]:\n \"\"\"Initiates a render operation.\n\n Args:\n renderer: Performs a render operation or extracts render data and arguments\n for a render operation to be performed later on.\n render_args: Render arguments.\n padding (:py:data:`OptionalPaddingT`): :term:`Render output` padding.\n iteration: Whether the render operation involves a sequence of renders\n (most likely of different frames), or it's a one-off render.\n finalize: Whether to finalize the render data passed to *renderer*\n immediately *renderer* returns.\n check_size: Whether to validate the [padded] :term:`render size` of\n **non-animations**.\n allow_scroll: Whether to validate the [padded] :term:`render height` of\n **non-animations**. Ignored if *check_size* is ``False``.\n\n Returns:\n A tuple containing\n\n * The return value of *renderer*.\n * *padding* (with equivalent **absolute** dimensions if it's an instance of\n :py:class:`~term_image.padding.AlignedPadding`).\n\n Raises:\n IncompatibleRenderArgsError: Incompatible render arguments.\n RenderSizeOutofRangeError: *check_size* is ``True`` and the [padded]\n :term:`render size` cannot fit into the :term:`terminal size`.\n\n :rtype: tuple[T, :py:data:`OptionalPaddingT`]\n\n After preparing render data and processing arguments, *renderer* is called with\n the following positional arguments:\n\n 1. Render data associated with **the renderable's class**\n 2. Render arguments associated with **the renderable's class** and initialized\n with *render_args*\n\n Any exception raised by *renderer* is propagated.\n\n IMPORTANT:\n Beyond this method (i.e any context from *renderer* onwards), use of any\n variable state (internal or external) should be avoided if possible.\n Any variable state (internal or external) required for rendering should\n be provided via :py:meth:`_get_render_data_`.\n\n If at all any variable state has to be used and is not\n reasonable/practicable to be provided via :py:meth:`_get_render_data_`,\n it should be read only once during a single render and passed to any\n nested/subsequent calls that require the value of that state during the\n same render.\n\n This is to prevent inconsistency in data used for the same render which may\n result in unexpected output.\n \"\"\"\n if not (render_args and render_args.render_cls is type(self)):\n # Validate compatibility (and convert, if compatible)\n render_args = RenderArgs(type(self), render_args)\n terminal_size = get_terminal_size()\n render_data = self._get_render_data_(iteration=iteration)\n try:\n if padding and isinstance(padding, AlignedPadding) and padding.relative:\n padding = padding.resolve(terminal_size)\n\n if check_size:\n render_size: Size = render_data[Renderable].size\n width, height = (\n padding.get_padded_size(render_size) if padding else render_size\n )\n terminal_width, terminal_height = terminal_size\n\n if width > terminal_width:\n raise RenderSizeOutofRangeError(\n f\"{'Padded render' if padding else 'Render'} width out of \"\n f\"range (got: {width}; terminal_width={terminal_width})\"\n )\n if not allow_scroll and height > terminal_height:\n raise RenderSizeOutofRangeError(\n f\"{'Padded render' if padding else 'Render'} height out of \"\n f\"range (got: {height}; terminal_height={terminal_height})\"\n )\n\n return renderer(render_data, render_args), padding\n finally:\n if finalize:\n render_data.finalize()\n\n @abstractmethod\n def _render_(self, render_data: RenderData, render_args: RenderArgs) -> Frame:\n \"\"\":term:`Renders` a frame.\n\n Args:\n render_data: Render data.\n render_args: Render arguments.\n\n Returns:\n The rendered frame.\n\n * The :py:attr:`~term_image.renderable.Frame.render_size` field =\n :py:attr:`render_data[Renderable].size\n `.\n * The :py:attr:`~term_image.renderable.Frame.render_output` field holds the\n :term:`render output`. This string should:\n\n * contain as many lines as ``render_size.height`` i.e exactly\n ``render_size.height - 1`` occurrences of ``\\\\n`` (the newline\n sequence).\n * occupy exactly ``render_size.height`` lines and ``render_size.width``\n columns on each line when drawn onto a terminal screen, **at least**\n when the render **size** it not greater than the terminal size on\n either axis.\n\n .. tip::\n If for any reason, the output behaves differently when the render\n **height** is greater than the terminal height, the behaviour, along\n with any possible alternatives or workarounds, should be duely noted.\n This doesn't apply to the **width**.\n\n * **not** end with ``\\\\n`` (the newline sequence).\n\n * As for the :py:attr:`~term_image.renderable.Frame.duration` field, if\n the renderable is:\n\n * **animated**; the value should be determined from the frame data\n source (or a default/fallback value, if undeterminable), if\n :py:attr:`render_data[Renderable].duration\n ` is\n :py:attr:`~term_image.renderable.FrameDuration.DYNAMIC`.\n Otherwise, it should be equal to\n :py:attr:`render_data[Renderable].duration\n `.\n * **non-animated**; the value range is unspecified i.e it may be given\n any value.\n\n Raises:\n StopIteration: End of iteration for an animated renderable with\n :py:attr:`~term_image.renderable.FrameCount.INDEFINITE` frame count.\n RenderError: An error occurred while rendering.\n\n NOTE:\n :py:class:`StopIteration` may be raised if and only if\n :py:attr:`render_data[Renderable].iteration\n ` is ``True``.\n Otherwise, it would be out of place.\n\n .. seealso:: :py:class:`~term_image.renderable.RenderableData`.\n \"\"\"\n raise NotImplementedError\n\n\n# Source: src/term_image/renderable/_types.py\nclass DataNamespace(ArgsDataNamespace, metaclass=DataNamespaceMeta, _base=True):\n \"\"\"DataNamespace()\n\n :term:`Render class`\\\\ -specific render data namespace.\n\n Raises:\n UnassociatedNamespaceError: The namespace class hasn't been associated\n [#dn-ass]_ with a render class.\n\n Subclassing, defining (and inheriting) fields and associating with a render\n class are just as they are for :ref:`args-namespace`, except that values\n assigned to class attributes are neither required nor used.\n\n Every field of a namespace is **uninitialized** immediately after instantiation.\n The fields are expected to be initialized within the\n :py:meth:`~term_image.renderable.Renderable._get_render_data_` method of the\n render class with which the namespace is associated [#dn-ass]_ or at some other\n point during a render operation, if necessary.\n\n NOTE:\n * Fields are exposed as instance attributes.\n * Instances are mutable and fields can be updated **in-place**, either\n individually by assignment to an attribute reference or in batch via\n :py:meth:`update`.\n * An instance shouldn't be copied by any means because finalizing its\n containing :py:class:`RenderData` instance may invalidate all copies of\n the namespace.\n\n .. Completed in /docs/source/api/renderable.rst\n \"\"\"\n\n _FIELDS: ClassVar[MappingProxyType[str, None]]\n\n def __init__(self) -> None:\n pass\n\n def __repr__(self) -> str:\n fields_repr = {}\n for name in type(self)._FIELDS:\n try:\n fields_repr[name] = repr(getattr(self, name))\n except UninitializedDataFieldError:\n fields_repr[name] = \"\"\n\n return \"\".join(\n (\n f\"<{type(self).__name__}: \",\n \", \".join(\n f\"{name}={value_repr}\" for name, value_repr in fields_repr.items()\n ),\n \">\",\n )\n )\n\n def __getattr__(self, name: str) -> Never:\n if name in type(self)._FIELDS:\n raise UninitializedDataFieldError(\n f\"The render data field {name!r} of \"\n f\"{type(self)._RENDER_CLS.__name__!r} has not been initialized\"\n )\n\n raise UnknownDataFieldError(\n f\"Unknown render data field {name!r} for \"\n f\"{type(self)._RENDER_CLS.__name__!r}\"\n )\n\n def __setattr__(self, name: str, value: Any) -> None:\n try:\n super().__setattr__(name, value)\n except AttributeError:\n raise UnknownDataFieldError(\n f\"Unknown render data field {name!r} for \"\n f\"{type(self)._RENDER_CLS.__name__!r}\"\n ) from None\n\n def as_dict(self) -> dict[str, Any]:\n \"\"\"Copies the namespace as a dictionary.\n\n Returns:\n A dictionary mapping field names to their current values.\n\n Raises:\n UninitializedDataFieldError: A field has not been initialized.\n\n WARNING:\n The number and order of fields are guaranteed to be the same for a\n namespace class that defines fields, its subclasses, and all their\n instances; but beyond this, should not be relied upon as the details\n (such as the specific number or order) may change without notice.\n\n The order is an implementation detail of the Render Arguments/Data API\n and the number should be considered an implementation detail of the\n specific namespace subclass.\n \"\"\"\n return {name: getattr(self, name) for name in type(self)._FIELDS}\n\n @classmethod\n def get_fields(cls) -> tuple[str, ...]:\n \"\"\"Returns the field names.\n\n Returns:\n A tuple of field names.\n\n WARNING:\n The number and order of fields are guaranteed to be the same for a\n namespace class that defines fields, its subclasses, and all their\n instances; but beyond this, should not be relied upon as the details\n (such as the specific number or order) may change without notice.\n\n The order is an implementation detail of the Render Arguments/Data API\n and the number should be considered an implementation detail of the\n specific namespace subclass.\n \"\"\"\n return tuple(cls._FIELDS)\n\n def update(self, **fields: Any) -> None:\n \"\"\"Updates render data fields.\n\n Args:\n fields: Render data fields.\n\n Raises:\n UnknownDataFieldError: Unknown field name(s).\n \"\"\"\n if fields:\n unknown = fields.keys() - type(self)._FIELDS.keys()\n if unknown:\n raise UnknownDataFieldError(\n f\"Unknown render data field(s) {tuple(unknown)} for \"\n f\"{type(self)._RENDER_CLS.__name__!r}\"\n )\n\n setattr_ = super().__setattr__\n for field in fields.items():\n setattr_(*field)", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 46231}, "tests/widget/urwid/test_main.py::362": {"resolved_imports": ["src/term_image/__init__.py", "src/term_image/_ctlseqs.py", "src/term_image/exceptions.py", "src/term_image/image/block.py", "src/term_image/image/common.py", "src/term_image/image/iterm2.py", "src/term_image/image/kitty.py", "src/term_image/widget/_urwid.py"], "used_names": ["UrwidImage", "UrwidImageError", "gc", "pytest"], "enclosing_function": "test_limit", "extracted_code": "# Source: src/term_image/exceptions.py\nclass UrwidImageError(TermImageError):\n \"\"\"Raised for errors specific to :py:class:`~term_image.widget.UrwidImage`.\"\"\"\n\n\n# Source: src/term_image/widget/_urwid.py\nclass UrwidImage(urwid.Widget):\n \"\"\"Image widget (box/flow) for the urwid TUI framework.\n\n Args:\n image: The image to be rendered by the widget.\n format_spec: :ref:`Render format specifier `. Padding width and\n height are ignored.\n upscale: If ``True``, the image will be upscaled to fit maximally within the\n available size, if necessary, while still preserving the aspect ratio.\n Otherwise, the image is never upscaled.\n\n Raises:\n TypeError: An argument is of an inappropriate type.\n ValueError: An argument is of an appropriate type but has an\n unexpected/invalid value.\n term_image.exceptions.StyleError: Invalid style-specific format specifier.\n term_image.exceptions.UrwidImageError: Too many image widgets rendering images\n with the *kitty* render style.\n\n | Any ample space in the widget's render size is filled with spaces.\n | For animated images, the current frame (at render-time) is rendered.\n\n TIP:\n If *image* is of a :ref:`graphics-based ` render style and the\n widget is being used as or within a **flow** widget, with overlays or in any\n other case where the canvas will require vertical trimming, make sure to use a\n render method that splits images across lines such as the **LINES** render\n method for *kitty* and *iterm2* render styles.\n\n NOTE:\n * The `z-index` style-specific format spec field for\n :py:class:`~term_image.image.KittyImage` is ignored as this is used\n internally.\n * A **maximum** of ``2**32 - 2`` instances initialized with\n :py:class:`~term_image.image.KittyImage` instances may exist at the same time.\n\n IMPORTANT:\n This is defined if and only if the ``urwid`` package is available.\n \"\"\"\n\n _sizing = frozenset((urwid.BOX, urwid.FLOW))\n ignore_focus = True\n\n _ti_error_placeholder = None\n\n # For kitty images\n _ti_disguise_state = 0\n _ti_free_z_indexes = set()\n\n # Progresses thus: 1, -1, 2, -2, 3, ..., 2**31 - 1, -(2**31 - 1)\n # This sequence results in shorter image escape sequences compared to starting\n # from -(2**31)\n _ti_next_z_index = 1\n\n def __init__(\n self, image: BaseImage, format_spec: str = \"\", *, upscale: bool = False\n ) -> None:\n if not isinstance(image, BaseImage):\n raise arg_type_error(\"image\", image)\n\n if not isinstance(format_spec, str):\n raise arg_type_error(\"format_spec\", format_spec)\n *fmt, alpha, style_args = image._check_format_spec(format_spec)\n\n if not isinstance(upscale, bool):\n raise arg_type_error(\"upscale\", upscale)\n\n super().__init__()\n self._ti_image = image\n self._ti_h_align, _, self._ti_v_align, _ = fmt\n self._ti_alpha = alpha\n self._ti_style_args = style_args\n self._ti_sizing = Size.FIT if upscale else Size.AUTO\n\n if isinstance(image, TextImage):\n style_args[\"split_cells\"] = True\n elif isinstance(image, KittyImage):\n style_args[\"z_index\"] = self._ti_z_index = self._ti_get_z_index()\n\n # Since Konsole doesn't blend images placed at the same location and\n # z-index, unlike Kitty (and potentially others), `blend=True` is\n # better on Konsole as it reduces/eliminates flicker.\n if get_terminal_name_version()[0] != \"konsole\":\n # To clear directly overlapped images when urwid redraws a line without\n # a change in image position\n style_args[\"blend\"] = False\n\n def __del__(self) -> None:\n if hasattr(self, \"_ti_z_index\"):\n __class__._ti_free_z_indexes.add(self._ti_z_index)\n\n image = property(\n lambda self: self._ti_image,\n doc=\"\"\"\n The image rendered by the widget\n\n :type: BaseImage\n\n GET:\n Returns the image instance rendered by the widget.\n \"\"\",\n )\n\n def render(self, size: Tuple[int, int], focus: bool = False) -> urwid.Canvas:\n image = self._ti_image\n\n if len(size) == 2: # box\n image.set_size(self._ti_sizing, frame_size=size)\n elif len(size) == 1: # flow\n if self._ti_sizing is Size.FIT:\n image.set_size(size[0])\n else:\n fit_size = self._ti_image._valid_size(size[0])\n ori_size = self._ti_image._valid_size(Size.ORIGINAL)\n image._size = (\n ori_size\n if ori_size[0] <= fit_size[0] and ori_size[1] <= fit_size[1]\n else fit_size\n )\n size = (size[0], image._size[1])\n else: # fixed\n raise UrwidImageError(\"Not a fixed widget\")\n\n try:\n render = image._format_render(\n image._renderer(\n image._render_image, self._ti_alpha, **self._ti_style_args\n ),\n self._ti_h_align,\n size[0],\n self._ti_v_align,\n size[1],\n )\n except Exception:\n if type(self)._ti_error_placeholder is None:\n raise\n canv = type(self)._ti_error_placeholder.render(size, focus)\n else:\n canv = UrwidImageCanvas(render, size, image._size)\n\n return canv\n\n def rows(self, size: Tuple[int], focus: bool = False) -> int:\n fit_size = self._ti_image._valid_size(size[0])\n if self._ti_sizing is Size.FIT:\n n_rows = fit_size[1]\n else:\n ori_size = self._ti_image._valid_size(Size.ORIGINAL)\n n_rows = (\n ori_size[1]\n if ori_size[0] <= fit_size[0] and ori_size[1] <= fit_size[1]\n else fit_size[1]\n )\n\n return n_rows\n\n @classmethod\n def set_error_placeholder(cls, widget: Optional[urwid.Widget]) -> None:\n \"\"\"Sets the widget to be rendered in place of an image when rendering fails.\n\n Args:\n widget: The placeholder widget or ``None`` to remove the placeholder.\n\n Raises:\n TypeError: *widget* is not an urwid widget.\n\n If set, any exception raised during rendering is **suppressed** and the\n placeholder is rendered in place of the image.\n \"\"\"\n if not isinstance(widget, urwid.Widget):\n raise arg_type_error(\"widget\", widget)\n\n cls._ti_error_placeholder = widget\n\n @staticmethod\n def _ti_get_z_index() -> int:\n if __class__._ti_free_z_indexes:\n return __class__._ti_free_z_indexes.pop()\n\n z_index = __class__._ti_next_z_index\n if z_index == 2**31:\n raise UrwidImageError(\"Too many image widgets with the kitty render style\")\n __class__._ti_next_z_index = -z_index if z_index > 0 else -z_index + 1\n\n return z_index\n\n def _ti_change_disguise(self) -> None:\n \"\"\"See :py:meth`UrwidImageCanvas._ti_change_disguise`.\"\"\"\n self._ti_disguise_state = (self._ti_disguise_state + 1) % 3", "n_imports_parsed": 10, "n_files_resolved": 8, "n_chars_extracted": 7330}, "tests/test_padding.py::34": {"resolved_imports": ["src/term_image/_ctlseqs.py", "src/term_image/geometry.py", "src/term_image/padding.py"], "used_names": [], "enclosing_function": "test_fill", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/renderable/test_types.py::1068": {"resolved_imports": ["src/term_image/geometry.py", "src/term_image/renderable/_renderable.py", "src/term_image/renderable/_types.py"], "used_names": ["UnknownArgsFieldError", "pytest"], "enclosing_function": "test_getattr", "extracted_code": "# Source: src/term_image/renderable/_types.py\nclass UnknownArgsFieldError(RenderArgsError, AttributeError):\n \"\"\"Raised when an attempt is made to access or modify an unknown render argument\n field.\n \"\"\"", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 211}, "tests/test_geometry.py::35": {"resolved_imports": ["src/term_image/geometry.py"], "used_names": ["RawSize", "pytest"], "enclosing_function": "test_equal_to_normally_constructed", "extracted_code": "# Source: src/term_image/geometry.py\nclass RawSize(NamedTuple):\n \"\"\"The dimensions of a rectangular region.\n\n Args:\n width: The horizontal dimension\n height: The vertical dimension\n\n NOTE:\n * A dimension may be non-positive but the validity and meaning would be\n determined by the receiving interface.\n * This is a subclass of :py:class:`tuple`. Hence, instances can be used anyway\n and anywhere tuples can.\n \"\"\"\n\n width: int\n height: int\n\n @classmethod\n def _new(cls, width: int, height: int) -> Self:\n \"\"\"Alternate constructor for internal use only.\"\"\"\n return tuple.__new__(cls, (width, height))", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 682}, "tests/test_image/test_block.py::73": {"resolved_imports": ["src/term_image/_ctlseqs.py", "src/term_image/image/block.py", "src/term_image/image/common.py"], "used_names": ["SGR_BG_DIRECT", "SGR_DEFAULT", "set_fg_bg_colors"], "enclosing_function": "test_background_colour", "extracted_code": "# Source: src/term_image/_ctlseqs.py\nSGR_BG_DIRECT = SGR % f\"48;2;{Pm(3)}\"\n\nSGR_DEFAULT = SGR % \"\"", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 98}, "tests/widget/urwid/test_main.py::321": {"resolved_imports": ["src/term_image/__init__.py", "src/term_image/_ctlseqs.py", "src/term_image/exceptions.py", "src/term_image/image/block.py", "src/term_image/image/common.py", "src/term_image/image/iterm2.py", "src/term_image/image/kitty.py", "src/term_image/widget/_urwid.py"], "used_names": ["UrwidImage", "gc"], "enclosing_function": "test_alloc", "extracted_code": "# Source: src/term_image/widget/_urwid.py\nclass UrwidImage(urwid.Widget):\n \"\"\"Image widget (box/flow) for the urwid TUI framework.\n\n Args:\n image: The image to be rendered by the widget.\n format_spec: :ref:`Render format specifier `. Padding width and\n height are ignored.\n upscale: If ``True``, the image will be upscaled to fit maximally within the\n available size, if necessary, while still preserving the aspect ratio.\n Otherwise, the image is never upscaled.\n\n Raises:\n TypeError: An argument is of an inappropriate type.\n ValueError: An argument is of an appropriate type but has an\n unexpected/invalid value.\n term_image.exceptions.StyleError: Invalid style-specific format specifier.\n term_image.exceptions.UrwidImageError: Too many image widgets rendering images\n with the *kitty* render style.\n\n | Any ample space in the widget's render size is filled with spaces.\n | For animated images, the current frame (at render-time) is rendered.\n\n TIP:\n If *image* is of a :ref:`graphics-based ` render style and the\n widget is being used as or within a **flow** widget, with overlays or in any\n other case where the canvas will require vertical trimming, make sure to use a\n render method that splits images across lines such as the **LINES** render\n method for *kitty* and *iterm2* render styles.\n\n NOTE:\n * The `z-index` style-specific format spec field for\n :py:class:`~term_image.image.KittyImage` is ignored as this is used\n internally.\n * A **maximum** of ``2**32 - 2`` instances initialized with\n :py:class:`~term_image.image.KittyImage` instances may exist at the same time.\n\n IMPORTANT:\n This is defined if and only if the ``urwid`` package is available.\n \"\"\"\n\n _sizing = frozenset((urwid.BOX, urwid.FLOW))\n ignore_focus = True\n\n _ti_error_placeholder = None\n\n # For kitty images\n _ti_disguise_state = 0\n _ti_free_z_indexes = set()\n\n # Progresses thus: 1, -1, 2, -2, 3, ..., 2**31 - 1, -(2**31 - 1)\n # This sequence results in shorter image escape sequences compared to starting\n # from -(2**31)\n _ti_next_z_index = 1\n\n def __init__(\n self, image: BaseImage, format_spec: str = \"\", *, upscale: bool = False\n ) -> None:\n if not isinstance(image, BaseImage):\n raise arg_type_error(\"image\", image)\n\n if not isinstance(format_spec, str):\n raise arg_type_error(\"format_spec\", format_spec)\n *fmt, alpha, style_args = image._check_format_spec(format_spec)\n\n if not isinstance(upscale, bool):\n raise arg_type_error(\"upscale\", upscale)\n\n super().__init__()\n self._ti_image = image\n self._ti_h_align, _, self._ti_v_align, _ = fmt\n self._ti_alpha = alpha\n self._ti_style_args = style_args\n self._ti_sizing = Size.FIT if upscale else Size.AUTO\n\n if isinstance(image, TextImage):\n style_args[\"split_cells\"] = True\n elif isinstance(image, KittyImage):\n style_args[\"z_index\"] = self._ti_z_index = self._ti_get_z_index()\n\n # Since Konsole doesn't blend images placed at the same location and\n # z-index, unlike Kitty (and potentially others), `blend=True` is\n # better on Konsole as it reduces/eliminates flicker.\n if get_terminal_name_version()[0] != \"konsole\":\n # To clear directly overlapped images when urwid redraws a line without\n # a change in image position\n style_args[\"blend\"] = False\n\n def __del__(self) -> None:\n if hasattr(self, \"_ti_z_index\"):\n __class__._ti_free_z_indexes.add(self._ti_z_index)\n\n image = property(\n lambda self: self._ti_image,\n doc=\"\"\"\n The image rendered by the widget\n\n :type: BaseImage\n\n GET:\n Returns the image instance rendered by the widget.\n \"\"\",\n )\n\n def render(self, size: Tuple[int, int], focus: bool = False) -> urwid.Canvas:\n image = self._ti_image\n\n if len(size) == 2: # box\n image.set_size(self._ti_sizing, frame_size=size)\n elif len(size) == 1: # flow\n if self._ti_sizing is Size.FIT:\n image.set_size(size[0])\n else:\n fit_size = self._ti_image._valid_size(size[0])\n ori_size = self._ti_image._valid_size(Size.ORIGINAL)\n image._size = (\n ori_size\n if ori_size[0] <= fit_size[0] and ori_size[1] <= fit_size[1]\n else fit_size\n )\n size = (size[0], image._size[1])\n else: # fixed\n raise UrwidImageError(\"Not a fixed widget\")\n\n try:\n render = image._format_render(\n image._renderer(\n image._render_image, self._ti_alpha, **self._ti_style_args\n ),\n self._ti_h_align,\n size[0],\n self._ti_v_align,\n size[1],\n )\n except Exception:\n if type(self)._ti_error_placeholder is None:\n raise\n canv = type(self)._ti_error_placeholder.render(size, focus)\n else:\n canv = UrwidImageCanvas(render, size, image._size)\n\n return canv\n\n def rows(self, size: Tuple[int], focus: bool = False) -> int:\n fit_size = self._ti_image._valid_size(size[0])\n if self._ti_sizing is Size.FIT:\n n_rows = fit_size[1]\n else:\n ori_size = self._ti_image._valid_size(Size.ORIGINAL)\n n_rows = (\n ori_size[1]\n if ori_size[0] <= fit_size[0] and ori_size[1] <= fit_size[1]\n else fit_size[1]\n )\n\n return n_rows\n\n @classmethod\n def set_error_placeholder(cls, widget: Optional[urwid.Widget]) -> None:\n \"\"\"Sets the widget to be rendered in place of an image when rendering fails.\n\n Args:\n widget: The placeholder widget or ``None`` to remove the placeholder.\n\n Raises:\n TypeError: *widget* is not an urwid widget.\n\n If set, any exception raised during rendering is **suppressed** and the\n placeholder is rendered in place of the image.\n \"\"\"\n if not isinstance(widget, urwid.Widget):\n raise arg_type_error(\"widget\", widget)\n\n cls._ti_error_placeholder = widget\n\n @staticmethod\n def _ti_get_z_index() -> int:\n if __class__._ti_free_z_indexes:\n return __class__._ti_free_z_indexes.pop()\n\n z_index = __class__._ti_next_z_index\n if z_index == 2**31:\n raise UrwidImageError(\"Too many image widgets with the kitty render style\")\n __class__._ti_next_z_index = -z_index if z_index > 0 else -z_index + 1\n\n return z_index\n\n def _ti_change_disguise(self) -> None:\n \"\"\"See :py:meth`UrwidImageCanvas._ti_change_disguise`.\"\"\"\n self._ti_disguise_state = (self._ti_disguise_state + 1) % 3", "n_imports_parsed": 10, "n_files_resolved": 8, "n_chars_extracted": 7167}, "tests/test_color.py::60": {"resolved_imports": ["src/term_image/color.py"], "used_names": ["Color", "pytest"], "enclosing_function": "test_hex", "extracted_code": "# Source: src/term_image/color.py\nclass Color(_DummyColor):\n \"\"\"A color.\n\n Args:\n r: The red channel.\n g: The green channel.\n b: The blue channel.\n a: The alpha channel (opacity).\n\n Raises:\n ValueError: The value of a channel is not within the valid range.\n\n NOTE:\n The valid value range for all channels is 0 to 255, both inclusive.\n\n TIP:\n This class is a :py:class:`~typing.NamedTuple` of four fields.\n\n WARNING:\n In the case of multiple inheritance i.e if subclassing this class along with\n other classes, this class should appear last (i.e to the far right) in the\n base class list.\n \"\"\"\n\n __slots__ = ()\n\n # Overrides these descriptors in order to speed up attribute resolution and to\n # simplify auto documentation.\n r: int = _DummyColor.r\n r.__doc__ = \"\"\"The red channel\"\"\"\n\n g: int = _DummyColor.g\n g.__doc__ = \"\"\"The green channel\"\"\"\n\n b: int = _DummyColor.b\n b.__doc__ = \"\"\"The blue channel\"\"\"\n\n a: int = _DummyColor.a\n a.__doc__ = \"\"\"The alpha channel (opacity)\"\"\"\n\n def __new__(cls, r: int, g: int, b: int, a: int = 255) -> Self:\n # Only the 8 LSb may be set for any value within the range [0, 255].\n # `x & ~255` unsets the 8 LSb. Hence, if the result is non-zero (i.e any\n # of the bits above the lowest 8 is set), it implies `x` is out of range.\n #\n # Actually benchmarked *this* against the \"simpler\" logically-negated chained\n # comparison (i.e `0 <= x <= 255`) and *this* was significantly faster for all\n # cases i.e within, on the boundaries, and outside (on both sides).\n if (r | g | b | a) & ~255: # First test to see if *any* is out of range\n if r & ~255:\n raise arg_value_error_range(\"r\", r)\n if g & ~255:\n raise arg_value_error_range(\"g\", g)\n if b & ~255:\n raise arg_value_error_range(\"b\", b)\n # There's no point checking since at least one is out of range\n raise arg_value_error_range(\"a\", a)\n\n # Using `tuple` directly instead of `super()` for performance\n return tuple.__new__(cls, (r, g, b, a))\n\n @property\n def hex(self) -> str:\n \"\"\"Converts the color to its RGBA hexadecimal representation.\n\n Returns:\n The RGBA hex color string, starting with the ``#`` character i.e\n ``#rrggbbaa``.\n\n Each channel is represented by two **lowercase** hex digits ranging from\n ``00`` to ``ff``.\n \"\"\"\n return \"#%02x%02x%02x%02x\" % self\n\n @property\n def rgb(self) -> tuple[int, int, int]:\n \"\"\"Extracts the R, G and B channels of the color.\n\n Returns:\n A 3-tuple containing the red, green and blue channel values.\n \"\"\"\n return self[:3]\n\n @property\n def rgb_hex(self) -> str:\n \"\"\"Converts the color to its RGB hexadecimal representation.\n\n Returns:\n The RGB hex color string, starting with the ``#`` character i.e ``#rrggbb``.\n\n Each channel is represented by two **lowercase** hex digits ranging from\n ``00`` to ``ff``.\n \"\"\"\n return \"#%02x%02x%02x\" % self[:3]\n\n @classmethod\n def from_hex(cls, color: str) -> Self:\n \"\"\"Creates a new instance from a hexadecimal color string.\n\n Args:\n color: A **case-insensitive** RGB or RGBA hex color string, **optionally**\n starting with the ``#`` (pound) character i.e ``[#]rrggbb[aa]``.\n\n Returns:\n A new instance representing the given hex color string.\n\n Raises:\n ValueError: Invalid hex color string.\n\n NOTE:\n For an RGB hex color string, the value of A (the alpha channel) is\n taken to be 255.\n \"\"\"\n if not (match := _RGBA_HEX_RE.fullmatch(color)):\n raise ValueError(f\"Invalid hex color string (got: {color!r})\")\n\n return tuple.__new__(cls, [int(x, 16) for x in match.groups(\"ff\")])\n\n @classmethod\n def _new(cls, r: int, g: int, b: int, a: int = 255) -> Self:\n \"\"\"Alternate constructor for internal use only.\"\"\"\n return tuple.__new__(cls, (r, g, b, a))", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 4255}, "tests/renderable/test_types.py::349": {"resolved_imports": ["src/term_image/geometry.py", "src/term_image/renderable/_renderable.py", "src/term_image/renderable/_types.py"], "used_names": ["NoArgsNamespaceError", "RenderArgs", "Renderable", "pytest"], "enclosing_function": "test_base", "extracted_code": "# Source: src/term_image/renderable/_renderable.py\nclass Renderable(metaclass=RenderableMeta, _base=True):\n \"\"\"A renderable.\n\n Args:\n frame_count: Number of frames. If it's a\n\n * positive integer, the number of frames is as given.\n * :py:class:`~term_image.renderable.FrameCount` enum member, see the\n member's description.\n\n If equal to 1 (one), the renderable is non-animated.\n Otherwise, it is animated.\n\n frame_duration: The duration of a frame. If it's a\n\n * positive integer, it implies a static duration (in **milliseconds**)\n i.e the same duration applies to every frame.\n * :py:class:`~term_image.renderable.FrameDuration` enum member, see the\n member's description.\n\n This argument is ignored if *frame_count* equals 1 (one)\n i.e the renderable is non-animated.\n\n Raises:\n ValueError: An argument has an invalid value.\n\n ATTENTION:\n This is an abstract base class. Hence, only **concrete** subclasses can be\n instantiated.\n\n .. seealso::\n\n :ref:`renderable-ext-api`\n :py:class:`Renderable`\\\\ 's Extension API\n \"\"\"\n\n # Class Attributes =========================================================\n\n # Initialized by `RenderableMeta` and may be updated by `ArgsNamespaceMeta`\n Args: ClassVar[type[ArgsNamespace] | None]\n \"\"\":term:`Render class`\\\\ -specific render arguments.\n\n This is either:\n\n - a render argument namespace class (subclass of :py:class:`ArgsNamespace`)\n associated [#an-ass]_ with the render class, or\n - :py:data:`None`, if the render class has no render arguments.\n\n If this is a class, an instance of it (or a subclass thereof) is contained within\n any :py:class:`RenderArgs` instance associated [#ra-ass]_ with the render class or\n any of its subclasses. Also, an instance of this class (or a subclass of it) is\n returned by :py:meth:`render_args[render_cls]\n `; where *render_args* is\n an instance of :py:class:`~term_image.renderable.RenderArgs` as previously\n described and *render_cls* is the render class with which this namespace class\n is associated [#an-ass]_.\n\n .. collapse:: Example\n\n >>> class Foo(Renderable):\n ... pass\n ...\n ... class FooArgs(ArgsNamespace, render_cls=Foo):\n ... foo: str | None = None\n ...\n >>> Foo.Args is FooArgs\n True\n >>>\n >>> # default\n >>> foo_args = Foo.Args()\n >>> foo_args\n FooArgs(foo=None)\n >>> foo_args.foo is None\n True\n >>>\n >>> render_args = RenderArgs(Foo)\n >>> render_args[Foo]\n FooArgs(foo=None)\n >>>\n >>> # non-default\n >>> foo_args = Foo.Args(\"FOO\")\n >>> foo_args\n FooArgs(foo='FOO')\n >>> foo_args.foo\n 'FOO'\n >>>\n >>> render_args = RenderArgs(Foo, foo_args.update(foo=\"bar\"))\n >>> render_args[Foo]\n FooArgs(foo='bar')\n\n On the other hand, if this is :py:data:`None`, it implies the render class has no\n render arguments.\n\n .. collapse:: Example\n\n >>> class Bar(Renderable):\n ... pass\n ...\n >>> Bar.Args is None\n True\n >>> render_args = RenderArgs(Bar)\n >>> render_args[Bar]\n Traceback (most recent call last):\n ...\n NoArgsNamespaceError: 'Bar' has no render arguments\n \"\"\"\n\n # Initialized by `RenderableMeta` and may be updated by `DataNamespaceMeta`\n _Data_: ClassVar[type[DataNamespace] | None]\n \"\"\":term:`Render class`\\\\ -specific render data.\n\n This is either:\n\n - a render data namespace class (subclass of :py:class:`DataNamespace`)\n associated [#dn-ass]_ with the render class, or\n - :py:data:`None`, if the render class has no render data.\n\n If this is a class, an instance of it (or a subclass thereof) is contained within\n any :py:class:`RenderData` instance associated [#rd-ass]_ with the render class or\n any of its subclasses. Also, an instance of this class (or a subclass of it) is\n returned by :py:meth:`render_data[render_cls]\n `; where *render_data* is\n an instance of :py:class:`~term_image.renderable.RenderData` as previously\n described and *render_cls* is the render class with which this namespace class\n is associated [#dn-ass]_.\n\n .. collapse:: Example\n\n >>> class Foo(Renderable):\n ... pass\n ...\n ... class _Data_(DataNamespace, render_cls=Foo):\n ... foo: str | None\n ...\n >>> Foo._Data_ is FooData\n True\n >>>\n >>> foo_data = Foo._Data_()\n >>> foo_data\n >\n >>> foo_data.foo\n Traceback (most recent call last):\n ...\n UninitializedDataFieldError: The render data field 'foo' of 'Foo' has not \\\nbeen initialized\n >>>\n >>> foo_data.foo = \"FOO\"\n >>> foo_data\n \n >>> foo_data.foo\n 'FOO'\n >>>\n >>> render_data = RenderData(Foo)\n >>> render_data[Foo]\n >\n >>>\n >>> render_data[Foo].foo = \"bar\"\n >>> render_data[Foo]\n \n\n On the other hand, if this is :py:data:`None`, it implies the render class has no\n render data.\n\n .. collapse:: Example\n\n >>> class Bar(Renderable):\n ... pass\n ...\n >>> Bar._Data_ is None\n True\n >>>\n >>> render_data = RenderData(Bar)\n >>> render_data[Bar]\n Traceback (most recent call last):\n ...\n NoDataNamespaceError: 'Bar' has no render data\n\n .. seealso::\n\n :py:class:`~term_image.renderable.RenderableData`\n Render data for :py:class:`~term_image.renderable.Renderable`.\n \"\"\"\n\n _EXPORTED_ATTRS_: ClassVar[tuple[str, ...]]\n \"\"\"Exported attributes.\n\n This specifies class attributes defined by the class (not a parent) on itself\n **but not** its subclasses which should be exported to definitions of the class\n in subprocesses.\n\n These attributes are typically assigned using ``__class__.*`` within methods.\n\n NOTE:\n * Defining this is optional.\n * The attributes are exported for a class if and only if they are defined\n on that class when starting a subprocess.\n * The attributes are exported only for subprocesses started via\n :py:class:`multiprocessing.Process`.\n\n TIP:\n This can be used to export \"private\" attributes of the class across\n subprocesses.\n \"\"\"\n\n _EXPORTED_DESCENDANT_ATTRS_: ClassVar[tuple[str, ...]]\n \"\"\"Exported :term:`descendant` attributes.\n\n This specifies class attributes defined by the class (not a parent) on itself\n **and** its subclasses (i.e :term:`descendant` attributes) which should be exported\n to definitions of the class and its subclasses in subprocesses.\n\n These attributes are typically assigned using ``cls.*`` within class methods.\n\n This extends the exported descendant attributes of parent classes i.e all\n exported descendant attributes of a class are also exported for its subclasses.\n\n NOTE:\n * Defining this is optional.\n * The attributes are exported for a class if and only if they are defined\n on that class when starting a subprocess.\n * The attributes are exported only for subprocesses started via\n :py:class:`multiprocessing.Process`.\n\n TIP:\n This can be used to export \"private\" :term:`descendant` attributes of the\n class across subprocesses.\n \"\"\"\n\n _ALL_DEFAULT_ARGS: ClassVar[MappingProxyType[type[Renderable], ArgsNamespace]]\n _RENDER_DATA_MRO: ClassVar[MappingProxyType[type[Renderable], type[DataNamespace]]]\n _ALL_EXPORTED_ATTRS: ClassVar[tuple[str, ...]]\n\n # Instance Attributes ======================================================\n\n animated: bool\n \"\"\"``True`` if the renderable is :term:`animated`. Otherwise, ``False``.\"\"\"\n\n _frame: int\n _frame_count: int | FrameCount\n _frame_duration: int | FrameDuration\n\n # Special Methods ==========================================================\n\n def __init__(\n self,\n frame_count: int | FrameCount,\n frame_duration: int | FrameDuration,\n ) -> None:\n if isinstance(frame_count, int) and frame_count < 1:\n raise arg_value_error_range(\"frame_count\", frame_count)\n\n if frame_count != 1:\n if isinstance(frame_duration, int) and frame_duration <= 0:\n raise arg_value_error_range(\"frame_duration\", frame_duration)\n self._frame_duration = frame_duration\n\n self.animated = frame_count != 1\n self._frame_count = frame_count\n self._frame = 0\n\n def __iter__(self) -> term_image.render.RenderIterator:\n \"\"\"Returns a render iterator.\n\n Returns:\n A render iterator (with frame caching disabled and all other optional\n arguments to :py:class:`~term_image.render.RenderIterator` being the\n default values).\n\n Raises:\n NonAnimatedRenderableError: The renderable is non-animated.\n\n :term:`Animated` renderables are iterable i.e they can be used with various\n means of iteration such as the ``for`` statement and iterable unpacking.\n \"\"\"\n from term_image.render import RenderIterator\n\n try:\n return RenderIterator(self, cache=False)\n except ValueError:\n raise NonAnimatedRenderableError(\n \"Non-animated renderables are not iterable\"\n ) from None\n\n def __repr__(self) -> str:\n return f\"<{type(self).__name__}: frame_count={self._frame_count}>\"\n\n def __str__(self) -> str:\n \"\"\":term:`Renders` the current frame with default arguments and no padding.\n\n Returns:\n The frame :term:`render output`.\n\n Raises:\n RenderError: An error occurred during :term:`rendering`.\n \"\"\"\n return self._init_render_(self._render_)[0].render_output\n\n # Properties ===============================================================\n\n @property\n def frame_count(self) -> int | Literal[FrameCount.INDEFINITE]:\n \"\"\"Frame count\n\n GET:\n Returns either\n\n * the number of frames the renderable has, or\n * :py:attr:`~term_image.renderable.FrameCount.INDEFINITE`.\n \"\"\"\n if self._frame_count is FrameCount.POSTPONED:\n self._frame_count = self._get_frame_count_()\n\n return self._frame_count\n\n @property\n def frame_duration(self) -> int | FrameDuration:\n \"\"\"Frame duration\n\n GET:\n Returns\n\n * a positive integer, a static duration (in **milliseconds**) i.e the\n same duration applies to every frame; or\n * :py:attr:`~term_image.renderable.FrameDuration.DYNAMIC`.\n\n SET:\n If the value is\n\n * a positive integer, it implies a static duration (in **milliseconds**)\n i.e the same duration applies to every frame.\n * :py:attr:`~term_image.renderable.FrameDuration.DYNAMIC`, see the\n enum member's description.\n\n Raises:\n NonAnimatedRenderableError: The renderable is non-animated.\n \"\"\"\n try:\n return self._frame_duration\n except AttributeError:\n if not self.animated:\n raise NonAnimatedRenderableError(\n \"Non-animated renderables have no frame duration\"\n ) from None\n raise\n\n @frame_duration.setter\n def frame_duration(self, duration: int | FrameDuration) -> None:\n if not self.animated:\n raise NonAnimatedRenderableError(\n \"Cannot set frame duration for a non-animated renderable\"\n )\n\n if isinstance(duration, int) and duration <= 0:\n raise arg_value_error_range(\"frame_duration\", duration)\n\n self._frame_duration = duration\n\n @property\n def render_size(self) -> geometry.Size:\n \"\"\":term:`Render size`\n\n GET:\n Returns the size of the renderable's :term:`render output`.\n \"\"\"\n return self._get_render_size_()\n\n # Public Methods ===========================================================\n\n def draw(\n self,\n render_args: RenderArgs | None = None,\n padding: Padding = AlignedPadding(0, -2),\n *,\n animate: bool = True,\n loops: int = -1,\n cache: bool | int = 100,\n check_size: bool = True,\n allow_scroll: bool = False,\n hide_cursor: bool = True,\n echo_input: bool = False,\n ) -> None:\n \"\"\"Draws the current frame or an animation to standard output.\n\n Args:\n render_args: Render arguments.\n padding: :term:`Render output` padding.\n animate: Whether to enable animation for :term:`animated` renderables.\n If disabled, only the current frame is drawn.\n loops: See :py:class:`~term_image.render.RenderIterator`\n (applies to **animations only**).\n cache: See :py:class:`~term_image.render.RenderIterator`.\n (applies to **animations only**).\n check_size: Whether to validate the padded :term:`render size` of\n **non-animations**.\n allow_scroll: Whether to validate the padded :term:`render height` of\n **non-animations**. Ignored if *check_size* is ``False``.\n hide_cursor: Whether to hide the cursor **while drawing**.\n echo_input: Whether to display input **while drawing** (applies on **Unix\n only**).\n\n .. note::\n * If disabled (default), input is not read/consumed, it's just not\n displayed.\n * If enabled, echoed input may affect cursor positioning and\n therefore, the output (especially for animations).\n\n Raises:\n RenderSizeOutofRangeError: The padded :term:`render size` can not fit into\n the :term:`terminal size`.\n IncompatibleRenderArgsError: Incompatible render arguments.\n RenderError: An error occurred during :term:`rendering`.\n\n If *check_size* is ``True`` (or it's an animation),\n\n * the padded :term:`render width` must not be greater than the\n :term:`terminal width`.\n * and *allow_scroll* is ``False`` (or it's an animation), the padded\n :term:`render height` must not be greater than the :term:`terminal height`.\n\n NOTE:\n * *hide_cursor* and *echo_input* apply if and only if the output stream\n is connected to a terminal.\n * For animations (i.e animated renderables with *animate* = ``True``),\n the padded :term:`render size` is always validated.\n * Animations with **definite** frame count, **by default**, are infinitely\n looped but can be terminated with :py:data:`~signal.SIGINT`\n (``CTRL + C``), **without** raising :py:class:`KeyboardInterrupt`.\n \"\"\"\n animation = self.animated and animate\n output = sys.stdout\n not_echo_input = OS_IS_UNIX and not echo_input and output.isatty()\n hide_cursor = hide_cursor and output.isatty()\n\n # Validate size and get render data and args\n render_data: RenderData\n real_render_args: RenderArgs\n (render_data, real_render_args), padding = self._init_render_(\n lambda *args: args,\n render_args,\n padding,\n iteration=animation,\n finalize=False,\n check_size=animation or check_size,\n allow_scroll=not animation and allow_scroll,\n )\n\n if not_echo_input:\n output_fd = output.fileno()\n old_attr = termios.tcgetattr(output_fd)\n new_attr = termios.tcgetattr(output_fd)\n new_attr[3] &= ~termios.ECHO\n try:\n if hide_cursor:\n output.write(HIDE_CURSOR)\n if not_echo_input:\n termios.tcsetattr(output_fd, termios.TCSAFLUSH, new_attr)\n\n if animation:\n self._animate_(\n render_data, real_render_args, padding, loops, cache, output\n )\n else:\n frame = self._render_(render_data, real_render_args)\n padded_size = padding.get_padded_size(frame.render_size)\n render = (\n frame.render_output\n if frame.render_size == padded_size\n else padding.pad(frame.render_output, frame.render_size)\n )\n try:\n output.write(render)\n output.flush()\n except KeyboardInterrupt:\n self._handle_interrupted_draw_(\n render_data, real_render_args, output\n )\n raise\n finally:\n output.write(\"\\n\")\n if hide_cursor:\n output.write(SHOW_CURSOR)\n output.flush()\n if not_echo_input:\n termios.tcsetattr(output_fd, termios.TCSANOW, old_attr)\n render_data.finalize()\n\n def render(\n self,\n render_args: RenderArgs | None = None,\n padding: Padding = NO_PADDING,\n ) -> Frame:\n \"\"\":term:`Renders` the current frame.\n\n Args:\n render_args: Render arguments.\n padding: :term:`Render output` padding.\n\n Returns:\n The rendered frame.\n\n Raises:\n IncompatibleRenderArgsError: Incompatible render arguments.\n RenderError: An error occurred during :term:`rendering`.\n \"\"\"\n frame, padding = self._init_render_(self._render_, render_args, padding)\n padded_size = padding.get_padded_size(frame.render_size)\n\n return (\n frame\n if frame.render_size == padded_size\n else Frame(\n frame.number,\n frame.duration,\n padded_size,\n padding.pad(frame.render_output, frame.render_size),\n )\n )\n\n def seek(self, offset: int, whence: Seek = Seek.START) -> int:\n \"\"\"Sets the current frame number.\n\n Args:\n offset: Frame offset (relative to *whence*).\n whence: Reference position for *offset*.\n\n Returns:\n The new current frame number.\n\n Raises:\n IndefiniteSeekError: The renderable has\n :py:attr:`~term_image.renderable.FrameCount.INDEFINITE` frame count.\n ValueError: *offset* is out of range.\n\n The value range for *offset* depends on *whence*:\n\n .. list-table::\n :align: left\n :header-rows: 1\n :widths: auto\n\n * - *whence*\n - Valid value range for *offset*\n\n * - :py:attr:`~term_image.renderable.Seek.START`\n - ``0`` <= *offset* < :py:attr:`frame_count`\n * - :py:attr:`~term_image.renderable.Seek.CURRENT`\n - -:py:meth:`tell` <= *offset* < :py:attr:`frame_count` - :py:meth:`tell`\n * - :py:attr:`~term_image.renderable.Seek.END`\n - -:py:attr:`frame_count` < *offset* <= ``0``\n \"\"\"\n frame_count = self.frame_count\n\n if frame_count is FrameCount.INDEFINITE:\n raise IndefiniteSeekError(\n \"Cannot seek a renderable with INDEFINITE frame count\"\n )\n\n frame = (\n offset\n if whence is Seek.START\n else (\n self._frame + offset\n if whence is Seek.CURRENT\n else frame_count + offset - 1\n )\n )\n if not 0 <= frame < frame_count:\n raise arg_value_error_range(\n \"offset\",\n offset,\n (\n f\"whence={whence.name}, frame_count={frame_count}\"\n + (f\", current={self._frame}\" if whence is Seek.CURRENT else \"\")\n ),\n )\n self._frame = frame\n\n return frame\n\n def tell(self) -> int:\n \"\"\"Returns the current frame number.\n\n Returns:\n Zero, if the renderable is non-animated or has\n :py:attr:`~term_image.renderable.FrameCount.INDEFINITE` frame count.\n Otherwise, the current frame number.\n \"\"\"\n return self._frame\n\n # Extension methods ========================================================\n\n def _animate_(\n self,\n render_data: RenderData,\n render_args: RenderArgs,\n padding: Padding,\n loops: int,\n cache: bool | int,\n output: TextIO,\n ) -> None:\n \"\"\"Animates frames of a renderable.\n\n Args:\n render_data: Render data.\n render_args: Render arguments associated with the renderable's class.\n output: The text I/O stream to which rendered frames will be written.\n\n All other parameters are the same as for :py:meth:`draw`, except that\n *padding* must have **absolute** dimensions if it's an instance of\n :py:class:`~term_image.padding.AlignedPadding`.\n\n This is called by :py:meth:`draw` for animations.\n\n NOTE:\n * The base implementation does not finalize *render_data*.\n * :term:`Render size` validation is expected to have been performed by\n the caller.\n * When called by :py:meth:`draw` (at least, the base implementation),\n *loops* and *cache* wouldn't have been validated.\n \"\"\"\n from term_image.render import RenderIterator\n\n render_size: Size = render_data[Renderable].size\n height = render_size.height\n pad_left, _, _, pad_bottom = padding._get_exact_dimensions_(render_size)\n render_iter = RenderIterator._from_render_data_(\n self,\n render_data,\n render_args,\n padding,\n loops,\n False if loops == 1 else cache,\n finalize=False,\n )\n cursor_to_next_render_line = f\"\\n{cursor_forward(pad_left)}\"\n cursor_to_render_top_left = (\n f\"\\r{cursor_up(height - 1)}{cursor_forward(pad_left)}\"\n )\n write = output.write\n flush = output.flush\n first_frame_written = False\n\n try:\n # first frame\n try:\n frame = next(render_iter)\n except StopIteration: # `INDEFINITE` frame count\n return\n\n try:\n write(frame.render_output)\n flush()\n except KeyboardInterrupt:\n self._handle_interrupted_draw_(render_data, render_args, output)\n return\n else:\n # Move the cursor to the top-left cell of the region occupied by the\n # render output\n write(\n f\"\\r{cursor_up(height + pad_bottom - 1)}{cursor_forward(pad_left)}\"\n )\n flush()\n\n first_frame_written = True\n\n # Padding has been drawn with the first frame, only the actual render is\n # needed henceforth.\n render_iter.set_padding(NO_PADDING)\n\n # render next frame during previous frame's duration\n duration_ms = frame.duration\n start_ns = perf_counter_ns()\n\n for frame in render_iter: # Render next frame\n # left-over of previous frame's duration\n sleep(\n max(0, duration_ms * 10**6 - (perf_counter_ns() - start_ns)) / 10**9\n )\n\n # clear previous frame, if necessary\n self._clear_frame_(render_data, render_args, pad_left + 1, output)\n\n # draw next frame\n try:\n write(frame.render_output.replace(\"\\n\", cursor_to_next_render_line))\n flush()\n except KeyboardInterrupt:\n self._handle_interrupted_draw_(render_data, render_args, output)\n return\n\n write(cursor_to_render_top_left)\n flush()\n\n # render next frame during previous frame's duration\n start_ns = perf_counter_ns()\n duration_ms = frame.duration\n\n # left-over of last frame's duration\n sleep(max(0, duration_ms * 10**6 - (perf_counter_ns() - start_ns)) / 10**9)\n except KeyboardInterrupt:\n pass\n finally:\n render_iter.close()\n if first_frame_written:\n # Move the cursor to the last line to prevent \"overlaid\" output\n write(cursor_down(height + pad_bottom - 1))\n flush()\n\n def _clear_frame_(\n self,\n render_data: RenderData,\n render_args: RenderArgs,\n cursor_x: int,\n output: TextIO,\n ) -> None:\n \"\"\"Clears the previous frame of an animation, if necessary.\n\n Args:\n render_data: Render data.\n render_args: Render arguments.\n cursor_x: Column/horizontal position of the cursor at the point of calling\n this method.\n\n .. note:: The position is **1-based** i.e the leftmost column on the\n screen is at position 1 (one).\n\n output: The text I/O stream to which frames of the animation are being\n written.\n\n Called by the base implementation of :py:meth:`_animate_` just before drawing\n the next frame of an animation.\n\n Upon calling this method, the cursor should be positioned at the top-left-most\n cell of the region occupied by the frame render output on the terminal screen.\n\n Upon return, ensure the cursor is at the same position it was at the point of\n calling this method (at least logically, since *output* shouldn't be flushed\n yet).\n\n The base implementation does nothing.\n\n NOTE:\n * This is required only if drawing the next frame doesn't inherently\n overwrite the previous frame.\n * This is only meant (and should only be used) as a last resort since\n clearing the previous frame before drawing the next may result in\n visible flicker.\n * Ensure whatever this method does doesn't result in the screen being\n scrolled.\n\n TIP:\n To reduce flicker, it's advisable to **not** flush *output*. It will be\n flushed after writing the next frame.\n \"\"\"\n\n @classmethod\n def _finalize_render_data_(cls, render_data: RenderData) -> None:\n \"\"\"Finalizes render data.\n\n Args:\n render_data: Render data.\n\n Typically, an overriding method should\n\n * finalize the data generated by :py:meth:`_get_render_data_` of the\n **same class**, if necessary,\n * call the overridden method, passing on *render_data*.\n\n NOTE:\n * It's recommended to call :py:meth:`RenderData.finalize()\n `\n instead as that assures a single invocation of this method.\n * Any definition of this method should be safe for multiple invocations on\n the same :py:class:`~term_image.renderable.RenderData` instance, just in\n case.\n\n .. seealso::\n :py:meth:`_get_render_data_`,\n :py:meth:`RenderData.finalize()\n `,\n the *finalize* parameter of :py:meth:`_init_render_`.\n \"\"\"\n\n def _get_frame_count_(self) -> int | Literal[FrameCount.INDEFINITE]:\n \"\"\"Implements :py:attr:`~term_image.renderable.FrameCount.POSTPONED` frame\n count evaluation.\n\n Returns:\n The frame count of the renderable. See :py:attr:`frame_count`.\n\n .. note::\n Returning :py:attr:`~term_image.renderable.FrameCount.POSTPONED` or\n ``1`` (one) is invalid and may result in unexpected/undefined behaviour\n across various interfaces defined by this library (and those derived\n from them), since re-postponing evaluation is unsupported and the\n renderable would have been taken to be animated.\n\n The base implementation raises :py:class:`NotImplementedError`.\n \"\"\"\n raise NotImplementedError(\"POSTPONED frame count evaluation isn't implemented\")\n\n def _get_render_data_(self, *, iteration: bool) -> RenderData:\n \"\"\"Generates data required for rendering that's based on internal or\n external state.\n\n Args:\n iteration: Whether the render operation requiring the data involves a\n sequence of :term:`renders` (most likely of different frames), or it's\n a one-off render.\n\n Returns:\n The generated render data.\n\n The render data should include **copies** of any **variable/mutable**\n internal/external state required for rendering and other data generated from\n constant state but which should **persist** throughout a render operation\n (which may involve consecutive/repeated renders of one or more frames).\n\n May also be used to \"allocate\" and initialize storage for mutable/variable\n data specific to a render operation.\n\n Typically, an overriding method should\n\n * call the overridden method,\n * update the namespace for its defining class (i.e\n :py:meth:`render_data[__class__]\n `) within the\n :py:class:`~term_image.renderable.RenderData` instance returned by the\n overridden method,\n * return the same :py:class:`~term_image.renderable.RenderData` instance.\n\n IMPORTANT:\n The :py:class:`~term_image.renderable.RenderData` instance returned must be\n associated [#rd-ass]_ with the type of the renderable on which this method\n is called i.e ``type(self)``. This is always the case for the base\n implementation of this method.\n\n NOTE:\n This method being called doesn't mean the data generated will be used\n immediately.\n\n .. seealso::\n :py:class:`~term_image.renderable.RenderData`,\n :py:meth:`_finalize_render_data_`,\n :py:meth:`~term_image.renderable.Renderable._init_render_`.\n \"\"\"\n render_data = RenderData(type(self))\n renderable_data: RenderableData = render_data[Renderable]\n renderable_data.update(\n size=self._get_render_size_(),\n frame_offset=self._frame,\n seek_whence=Seek.START,\n iteration=iteration,\n )\n if self.animated:\n renderable_data.duration = self._frame_duration\n\n return render_data\n\n @abstractmethod\n def _get_render_size_(self) -> geometry.Size:\n \"\"\"Returns the renderable's :term:`render size`.\n\n Returns:\n The size of the renderable's :term:`render output`.\n\n The base implementation raises :py:class:`NotImplementedError`.\n\n NOTE:\n Both dimensions are expected to be positive.\n\n .. seealso:: :py:attr:`render_size`\n \"\"\"\n raise NotImplementedError\n\n def _handle_interrupted_draw_(\n self, render_data: RenderData, render_args: RenderArgs, output: TextIO\n ) -> None:\n \"\"\"Performs any special handling necessary when an interruption occurs while\n writing a :term:`render output` to a stream.\n\n Args:\n render_data: Render data.\n render_args: Render arguments.\n output: The text I/O stream to which the render output was being written.\n\n Called by the base implementations of :py:meth:`draw` (for non-animations)\n and :py:meth:`_animate_` when :py:class:`KeyboardInterrupt` is raised while\n writing a render output.\n\n The base implementation does nothing.\n\n NOTE:\n *output* should be flushed by this method.\n\n HINT:\n For a renderable that uses SGR sequences in its render output, this method\n may write ``CSI 0 m`` to *output*.\n \"\"\"\n\n # *render_args*, no *padding*; or neither\n @overload\n def _init_render_(\n self,\n renderer: Callable[[RenderData, RenderArgs], T],\n render_args: RenderArgs | None = None,\n *,\n iteration: bool = False,\n finalize: bool = True,\n check_size: bool = False,\n allow_scroll: bool = False,\n ) -> tuple[T, None]: ...\n\n # both *render_args* and *padding*\n @overload\n def _init_render_(\n self,\n renderer: Callable[[RenderData, RenderArgs], T],\n render_args: RenderArgs | None,\n padding: OptionalPaddingT,\n *,\n iteration: bool = False,\n finalize: bool = True,\n check_size: bool = False,\n allow_scroll: bool = False,\n ) -> tuple[T, OptionalPaddingT]: ...\n\n # *padding*, no *render_args*\n @overload\n def _init_render_(\n self,\n renderer: Callable[[RenderData, RenderArgs], T],\n *,\n padding: OptionalPaddingT,\n iteration: bool = False,\n finalize: bool = True,\n check_size: bool = False,\n allow_scroll: bool = False,\n ) -> tuple[T, OptionalPaddingT]: ...\n\n def _init_render_(\n self,\n renderer: Callable[[RenderData, RenderArgs], T],\n render_args: RenderArgs | None = None,\n padding: Padding | None = None,\n *,\n iteration: bool = False,\n finalize: bool = True,\n check_size: bool = False,\n allow_scroll: bool = False,\n ) -> tuple[T, Padding | None]:\n \"\"\"Initiates a render operation.\n\n Args:\n renderer: Performs a render operation or extracts render data and arguments\n for a render operation to be performed later on.\n render_args: Render arguments.\n padding (:py:data:`OptionalPaddingT`): :term:`Render output` padding.\n iteration: Whether the render operation involves a sequence of renders\n (most likely of different frames), or it's a one-off render.\n finalize: Whether to finalize the render data passed to *renderer*\n immediately *renderer* returns.\n check_size: Whether to validate the [padded] :term:`render size` of\n **non-animations**.\n allow_scroll: Whether to validate the [padded] :term:`render height` of\n **non-animations**. Ignored if *check_size* is ``False``.\n\n Returns:\n A tuple containing\n\n * The return value of *renderer*.\n * *padding* (with equivalent **absolute** dimensions if it's an instance of\n :py:class:`~term_image.padding.AlignedPadding`).\n\n Raises:\n IncompatibleRenderArgsError: Incompatible render arguments.\n RenderSizeOutofRangeError: *check_size* is ``True`` and the [padded]\n :term:`render size` cannot fit into the :term:`terminal size`.\n\n :rtype: tuple[T, :py:data:`OptionalPaddingT`]\n\n After preparing render data and processing arguments, *renderer* is called with\n the following positional arguments:\n\n 1. Render data associated with **the renderable's class**\n 2. Render arguments associated with **the renderable's class** and initialized\n with *render_args*\n\n Any exception raised by *renderer* is propagated.\n\n IMPORTANT:\n Beyond this method (i.e any context from *renderer* onwards), use of any\n variable state (internal or external) should be avoided if possible.\n Any variable state (internal or external) required for rendering should\n be provided via :py:meth:`_get_render_data_`.\n\n If at all any variable state has to be used and is not\n reasonable/practicable to be provided via :py:meth:`_get_render_data_`,\n it should be read only once during a single render and passed to any\n nested/subsequent calls that require the value of that state during the\n same render.\n\n This is to prevent inconsistency in data used for the same render which may\n result in unexpected output.\n \"\"\"\n if not (render_args and render_args.render_cls is type(self)):\n # Validate compatibility (and convert, if compatible)\n render_args = RenderArgs(type(self), render_args)\n terminal_size = get_terminal_size()\n render_data = self._get_render_data_(iteration=iteration)\n try:\n if padding and isinstance(padding, AlignedPadding) and padding.relative:\n padding = padding.resolve(terminal_size)\n\n if check_size:\n render_size: Size = render_data[Renderable].size\n width, height = (\n padding.get_padded_size(render_size) if padding else render_size\n )\n terminal_width, terminal_height = terminal_size\n\n if width > terminal_width:\n raise RenderSizeOutofRangeError(\n f\"{'Padded render' if padding else 'Render'} width out of \"\n f\"range (got: {width}; terminal_width={terminal_width})\"\n )\n if not allow_scroll and height > terminal_height:\n raise RenderSizeOutofRangeError(\n f\"{'Padded render' if padding else 'Render'} height out of \"\n f\"range (got: {height}; terminal_height={terminal_height})\"\n )\n\n return renderer(render_data, render_args), padding\n finally:\n if finalize:\n render_data.finalize()\n\n @abstractmethod\n def _render_(self, render_data: RenderData, render_args: RenderArgs) -> Frame:\n \"\"\":term:`Renders` a frame.\n\n Args:\n render_data: Render data.\n render_args: Render arguments.\n\n Returns:\n The rendered frame.\n\n * The :py:attr:`~term_image.renderable.Frame.render_size` field =\n :py:attr:`render_data[Renderable].size\n `.\n * The :py:attr:`~term_image.renderable.Frame.render_output` field holds the\n :term:`render output`. This string should:\n\n * contain as many lines as ``render_size.height`` i.e exactly\n ``render_size.height - 1`` occurrences of ``\\\\n`` (the newline\n sequence).\n * occupy exactly ``render_size.height`` lines and ``render_size.width``\n columns on each line when drawn onto a terminal screen, **at least**\n when the render **size** it not greater than the terminal size on\n either axis.\n\n .. tip::\n If for any reason, the output behaves differently when the render\n **height** is greater than the terminal height, the behaviour, along\n with any possible alternatives or workarounds, should be duely noted.\n This doesn't apply to the **width**.\n\n * **not** end with ``\\\\n`` (the newline sequence).\n\n * As for the :py:attr:`~term_image.renderable.Frame.duration` field, if\n the renderable is:\n\n * **animated**; the value should be determined from the frame data\n source (or a default/fallback value, if undeterminable), if\n :py:attr:`render_data[Renderable].duration\n ` is\n :py:attr:`~term_image.renderable.FrameDuration.DYNAMIC`.\n Otherwise, it should be equal to\n :py:attr:`render_data[Renderable].duration\n `.\n * **non-animated**; the value range is unspecified i.e it may be given\n any value.\n\n Raises:\n StopIteration: End of iteration for an animated renderable with\n :py:attr:`~term_image.renderable.FrameCount.INDEFINITE` frame count.\n RenderError: An error occurred while rendering.\n\n NOTE:\n :py:class:`StopIteration` may be raised if and only if\n :py:attr:`render_data[Renderable].iteration\n ` is ``True``.\n Otherwise, it would be out of place.\n\n .. seealso:: :py:class:`~term_image.renderable.RenderableData`.\n \"\"\"\n raise NotImplementedError\n\n\n# Source: src/term_image/renderable/_types.py\nclass NoArgsNamespaceError(RenderArgsError):\n \"\"\"Raised when an attempt is made to get a render argument namespace for a\n :term:`render class` that has no render arguments.\n \"\"\"\n\nclass RenderArgs(RenderArgsData):\n \"\"\"RenderArgs(render_cls, /, *namespaces)\n RenderArgs(render_cls, init_render_args, /, *namespaces)\n\n Render arguments.\n\n Args:\n render_cls: A :term:`render class`.\n init_render_args (RenderArgs | None): A set of render arguments.\n If not ``None``,\n\n * it must be compatible [#ra-com]_ with *render_cls*,\n * it'll be used to initialize the render arguments.\n\n namespaces: Render argument namespaces compatible [#an-com]_ with *render_cls*.\n\n .. note:: If multiple namespaces associated with the same :term:`render\n class` are given, the last of them takes precedence.\n\n Raises:\n IncompatibleRenderArgsError: *init_render_args* is incompatible [#ra-com]_ with\n *render_cls*.\n IncompatibleArgsNamespaceError: Incompatible [#an-com]_ render argument\n namespace.\n\n A set of render arguments (an instance of this class) is basically a container of\n render argument namespaces (instances of\n :py:class:`~term_image.renderable.ArgsNamespace`); one for\n each :term:`render class`, which has render arguments, in the Method Resolution\n Order of its associated [#ra-ass]_ render class.\n\n The namespace for each render class is derived from the following sources, in\n [descending] order of precedence:\n\n * *namespaces*\n * *init_render_args*\n * default render argument namespaces\n\n NOTE:\n Instances are immutable but updated copies can be created via :py:meth:`update`.\n\n .. seealso::\n\n :py:attr:`~term_image.renderable.Renderable.Args`\n Render class-specific render arguments.\n\n .. Completed in /docs/source/api/renderable.rst\n \"\"\"\n\n # Class Attributes =========================================================\n\n __slots__ = ()\n\n _interned: ClassVar[dict[type[Renderable], Self]] = {}\n _namespaces: MappingProxyType[type[Renderable], ArgsNamespace]\n\n # Instance Attributes ======================================================\n\n render_cls: type[Renderable]\n \"\"\"The associated :term:`render class`\"\"\"\n\n # Special Methods ==========================================================\n\n def __new__(\n cls,\n render_cls: type[Renderable],\n init_or_namespace: RenderArgs | ArgsNamespace | None = None,\n *namespaces: ArgsNamespace,\n ) -> Self:\n if init_or_namespace is None:\n init_render_args = None\n elif isinstance(init_or_namespace, RenderArgs):\n init_render_args = init_or_namespace\n else:\n init_render_args = None\n namespaces = (init_or_namespace, *namespaces)\n\n if init_render_args and not issubclass(render_cls, init_render_args.render_cls):\n raise IncompatibleRenderArgsError(\n f\"'init_render_args' (associated with \"\n f\"{init_render_args.render_cls.__name__!r}) is incompatible with \"\n f\"{render_cls.__name__!r} \"\n )\n\n if not namespaces:\n # has default namespaces only\n if (\n not init_render_args\n or init_render_args is BASE_RENDER_ARGS\n or cls._interned.get(init_render_args.render_cls) is init_render_args\n ):\n try:\n return cls._interned[render_cls]\n except KeyError:\n pass\n\n if (\n init_render_args\n and type(init_render_args) is cls\n and init_render_args.render_cls is render_cls\n ):\n return init_render_args\n\n return super().__new__(cls)\n\n def __init__(\n self,\n render_cls: type[Renderable],\n init_or_namespace: RenderArgs | ArgsNamespace | None = None,\n *namespaces: ArgsNamespace,\n ) -> None:\n if init_or_namespace is None:\n init_render_args = None\n elif isinstance(init_or_namespace, RenderArgs):\n init_render_args = init_or_namespace\n else:\n init_render_args = None\n namespaces = (init_or_namespace, *namespaces)\n\n # has default namespaces only\n if not namespaces and (\n not init_render_args\n or init_render_args is BASE_RENDER_ARGS\n or (\n type(self)._interned.get(init_render_args.render_cls)\n is init_render_args\n )\n ):\n if render_cls in type(self)._interned: # has been initialized\n return\n intern = True\n else:\n intern = False\n\n if init_render_args is self:\n return\n\n namespaces_dict = render_cls._ALL_DEFAULT_ARGS.copy()\n\n # if `init_render_args` is non-default\n if init_render_args and BASE_RENDER_ARGS is not init_render_args is not (\n type(self)._interned.get(init_render_args.render_cls)\n ):\n namespaces_dict.update(init_render_args._namespaces)\n\n for index, namespace in enumerate(namespaces):\n if namespace._RENDER_CLS not in namespaces_dict:\n raise IncompatibleArgsNamespaceError(\n f\"'namespaces[{index}]' (associated with \"\n f\"{namespace._RENDER_CLS.__name__!r}) is incompatible with \"\n f\"{render_cls.__name__!r} \"\n )\n namespaces_dict[namespace._RENDER_CLS] = namespace\n\n super().__init__(render_cls, namespaces_dict)\n\n if intern:\n type(self)._interned[render_cls] = self\n\n def __init_subclass__(cls, **kwargs: Any) -> None:\n cls._interned = {}\n super().__init_subclass__(**kwargs)\n\n def __contains__(self, namespace: ArgsNamespace) -> bool:\n \"\"\"Checks if a render argument namespace is contained in this set of render\n arguments.\n\n Args:\n namespace: A render argument namespace.\n\n Returns:\n ``True`` if the given namespace is equal to any of the namespaces\n contained in this set of render arguments. Otherwise, ``False``.\n \"\"\"\n return None is not self._namespaces.get(namespace._RENDER_CLS) == namespace\n\n def __eq__(self, other: object) -> bool:\n \"\"\"Compares this set of render arguments with another.\n\n Args:\n other: Another set of render arguments.\n\n Returns:\n ``True`` if both are associated with the same :term:`render class`\n and have equal argument values. Otherwise, ``False``.\n \"\"\"\n if isinstance(other, RenderArgs):\n return (\n self is other\n or self.render_cls is other.render_cls\n and self._namespaces == other._namespaces\n )\n\n return NotImplemented\n\n def __getitem__(self, render_cls: type[Renderable]) -> Any:\n \"\"\"Returns a constituent namespace.\n\n Args:\n render_cls: A :term:`render class` of which :py:attr:`render_cls` is a\n subclass (which may be :py:attr:`render_cls` itself) and which has\n render arguments.\n\n Returns:\n The constituent namespace associated with *render_cls*.\n\n Raises:\n TypeError: *render_cls* is not a render class.\n ValueError: :py:attr:`render_cls` is not a subclass of *render_cls*.\n NoArgsNamespaceError: *render_cls* has no render arguments.\n\n NOTE:\n The return type hint is :py:class:`~typing.Any` only for compatibility\n with static type checking, as this aspect of the interface seems too\n dynamic to be correctly expressed with the exisiting type system.\n\n Regardless, the return value is guaranteed to always be an instance\n of a render argument namespace class associated with *render_cls*.\n For instance, the following would always be valid for\n :py:class:`~term_image.renderable.Renderable`::\n\n renderable_args: RenderableArgs = render_args[Renderable]\n\n and similar idioms are encouraged to be used for other render classes.\n \"\"\"\n try:\n return self._namespaces[render_cls]\n except TypeError:\n raise arg_type_error(\"render_cls\", render_cls) from None\n except KeyError:\n if not isinstance(render_cls, RenderableMeta):\n raise arg_type_error(\"render_cls\", render_cls) from None\n\n if issubclass(self.render_cls, render_cls):\n raise NoArgsNamespaceError(\n f\"{render_cls.__name__!r} has no render arguments\"\n ) from None\n\n raise ValueError(\n f\"{self.render_cls.__name__!r} is not a subclass of \"\n f\"{render_cls.__name__!r}\"\n ) from None\n\n def __hash__(self) -> int:\n \"\"\"Computes the hash of the render arguments.\n\n Returns:\n The computed hash.\n\n IMPORTANT:\n Like tuples, an instance is hashable if and only if the constituent\n namespaces are hashable.\n \"\"\"\n # Namespaces are always in the same order, wrt their respective associated\n # render classes, for all instances associated with the same render class.\n return hash((self.render_cls, tuple(self._namespaces.values())))\n\n def __iter__(self) -> Iterator[ArgsNamespace]:\n \"\"\"Returns an iterator that yields the constituent namespaces.\n\n Returns:\n An iterator that yields the constituent namespaces.\n\n WARNING:\n The number and order of namespaces is guaranteed to be the same across all\n instances associated [#ra-ass]_ with the same :term:`render class` but\n beyond this, should not be relied upon as the details (such as the\n specific number or order) may change without notice.\n\n The order is an implementation detail of the Renderable API and the number\n should be considered alike with respect to the associated render class.\n \"\"\"\n return iter(self._namespaces.values())\n\n def __repr__(self) -> str:\n return \"\".join(\n (\n f\"{type(self).__name__}({self.render_cls.__name__}\",\n \", \" if self._namespaces else \"\",\n \", \".join(map(repr, self._namespaces.values())),\n \")\",\n )\n )\n\n # Public Methods ===========================================================\n\n def convert(self, render_cls: type[Renderable]) -> RenderArgs:\n \"\"\"Converts the set of render arguments to one for a related render class.\n\n Args:\n render_cls: A :term:`render class` of which :py:attr:`render_cls` is a\n parent or child (which may be :py:attr:`render_cls` itself).\n\n Returns:\n A set of render arguments associated [#ra-ass]_ with *render_cls* and\n initialized with all constituent namespaces (of this set of render\n arguments, *self*) that are compatible [#an-com]_ with *render_cls*.\n\n Raises:\n ValueError: *render_cls* is not a parent or child of :py:attr:`render_cls`.\n \"\"\"\n if render_cls is self.render_cls:\n return self\n\n if issubclass(render_cls, self.render_cls):\n return RenderArgs(render_cls, self)\n\n if issubclass(self.render_cls, render_cls):\n render_cls_args_mro = render_cls._ALL_DEFAULT_ARGS\n return RenderArgs(\n render_cls,\n *[\n namespace\n for cls, namespace in self._namespaces.items()\n if cls in render_cls_args_mro\n ],\n )\n\n raise ValueError(\n f\"{render_cls.__name__!r} is not a parent or child of \"\n f\"{self.render_cls.__name__!r}\"\n )\n\n @overload\n def update(\n self,\n namespace: ArgsNamespace,\n /,\n *namespaces: ArgsNamespace,\n ) -> RenderArgs: ...\n\n @overload\n def update(\n self,\n render_cls: type[Renderable],\n /,\n **fields: Any,\n ) -> RenderArgs: ...\n\n def update(\n self,\n render_cls_or_namespace: type[Renderable] | ArgsNamespace,\n /,\n *namespaces: ArgsNamespace,\n **fields: Any,\n ) -> RenderArgs:\n \"\"\"update(namespace, /, *namespaces) -> RenderArgs\n update(render_cls, /, **fields) -> RenderArgs\n\n Replaces or updates render argument namespaces.\n\n Args:\n namespace (ArgsNamespace): Prepended to *namespaces*.\n namespaces: Render argument namespaces compatible [#an-com]_ with\n :py:attr:`render_cls`.\n\n .. note:: If multiple namespaces associated with the same :term:`render\n class` are given, the last of them takes precedence.\n\n render_cls (type[Renderable]): A :term:`render class` of which\n :py:attr:`render_cls` is a subclass (which may be :py:attr:`render_cls`\n itself) and which has render arguments.\n fields: Render argument fields.\n\n The keywords must be names of render argument fields for *render_cls*.\n\n Returns:\n For the **first** form, an instance with the namespaces for the respective\n associated :term:`render classes` of the given namespaces replaced.\n\n For the **second** form, an instance with the given render argument fields\n for *render_cls* updated, if any.\n\n Raises:\n TypeError: The arguments given do not conform to any of the expected forms.\n\n Propagates exceptions raised by:\n\n * the class constructor, for the **first** form.\n * :py:meth:`__getitem__` and :py:meth:`ArgsNamespace.update()\n `, for the **second** form.\n \"\"\"\n if isinstance(render_cls_or_namespace, RenderableMeta):\n if namespaces:\n raise TypeError(\n \"No other positional argument is expected when the first argument \"\n \"is a render class\"\n )\n render_cls = render_cls_or_namespace\n else:\n if fields:\n raise TypeError(\n \"No keyword argument is expected when the first argument is \"\n \"a render argument namespace\"\n )\n render_cls = None\n namespaces = (render_cls_or_namespace, *namespaces)\n\n return RenderArgs(\n self.render_cls,\n self,\n *((self[render_cls].update(**fields),) if render_cls else namespaces),\n )", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 56120}, "tests/test_padding.py::148": {"resolved_imports": ["src/term_image/_ctlseqs.py", "src/term_image/geometry.py", "src/term_image/padding.py"], "used_names": ["AlignedPadding", "pytest"], "enclosing_function": "test_height", "extracted_code": "# Source: src/term_image/padding.py\nclass AlignedPadding(Padding):\n \"\"\"Aligned :term:`render output` padding.\n\n Args:\n width: Minimum :term:`render width`.\n height: Minimum :term:`render height`.\n h_align: Horizontal alignment.\n v_align: Vertical alignment.\n\n If *width* or *height* is:\n\n * positive, it is **absolute** and used as-is.\n * non-positive, it is **relative** to the corresponding terminal dimension\n (**at the point of resolution**) and equivalent to the absolute dimension\n ``max(terminal_dimension + relative_dimension, 1)``.\n\n The *padded render dimension* (i.e the dimension of a :term:`render output` after\n it's padded) on each axis is given by::\n\n padded_dimension = max(render_dimension, absolute_minimum_dimension)\n\n In words... If the **absolute** *minimum render dimension* on an axis is less than\n or equal to the corresponding *render dimension*, there is no padding on that axis\n and the *padded render dimension* on that axis is equal to the *render dimension*.\n Otherwise, the render output will be padded along that axis and the *padded render\n dimension* on that axis is equal to the *minimum render dimension*.\n\n The amount of padding to each side depends on the alignment, defined by *h_align*\n and *v_align*.\n\n IMPORTANT:\n :py:class:`RelativePaddingDimensionError` is raised if any padding-related\n computation/operation (basically, calling any method other than\n :py:meth:`resolve`) is performed on an instance with **relative** *minimum\n render dimension(s)* i.e if :py:attr:`relative` is ``True``.\n\n NOTE:\n Any interface receiving an instance with **relative** dimension(s) should\n typically resolve it/them upon reception.\n\n TIP:\n * Instances are immutable and hashable.\n * Instances with equal fields compare equal.\n \"\"\"\n\n # Class Attributes =========================================================\n\n __slots__ = (\"width\", \"height\", \"h_align\", \"v_align\", \"relative\")\n\n # Instance Attributes ======================================================\n\n width: int\n \"\"\"Minimum :term:`render width`\"\"\"\n\n height: int\n \"\"\"Minimum :term:`render height`\"\"\"\n\n h_align: HAlign\n \"\"\"Horizontal alignment\"\"\"\n\n v_align: VAlign\n \"\"\"Vertical alignment\"\"\"\n\n fill: str\n\n relative: bool\n \"\"\"``True`` if either or both *minimum render dimension(s)* is/are relative i.e\n non-positive. Otherwise, ``False``.\n \"\"\"\n\n # Special Methods ==========================================================\n\n def __init__(\n self,\n width: int,\n height: int,\n h_align: HAlign = HAlign.CENTER,\n v_align: VAlign = VAlign.MIDDLE,\n fill: str = \" \",\n ):\n super().__init__(fill)\n\n _setattr = super().__setattr__\n _setattr(\"width\", width)\n _setattr(\"height\", height)\n _setattr(\"h_align\", h_align)\n _setattr(\"v_align\", v_align)\n _setattr(\"relative\", not width > 0 < height)\n\n def __repr__(self) -> str:\n return \"{}(width={}, height={}, h_align={}, v_align={}, fill={!r})\".format(\n type(self).__name__,\n self.width,\n self.height,\n self.h_align.name,\n self.v_align.name,\n self.fill,\n )\n\n # Properties ===============================================================\n\n @property\n def size(self) -> RawSize:\n \"\"\"Minimum :term:`render size`\n\n GET:\n Returns the *minimum render dimensions*.\n \"\"\"\n return _RawSize(self.width, self.height)\n\n # Public Methods ===========================================================\n\n @override\n def get_padded_size(self, render_size: Size) -> Size:\n \"\"\"Computes an expected padded :term:`render size`.\n\n See :py:meth:`Padding.get_padded_size`.\n\n Raises:\n RelativePaddingDimensionError: Relative *minimum render dimension(s)*.\n \"\"\"\n if self.relative:\n raise RelativePaddingDimensionError(\"Relative minimum render dimension(s)\")\n\n return _Size(max(self.width, render_size[0]), max(self.height, render_size[1]))\n\n def resolve(self, terminal_size: os.terminal_size) -> AlignedPadding:\n \"\"\"Resolves **relative** *minimum render dimensions*.\n\n Args:\n terminal_size: The terminal size against which to resolve relative\n dimensions.\n\n Returns:\n An instance with equivalent **absolute** dimensions.\n \"\"\"\n if not self.relative:\n return self\n\n width, height, *args, _ = astuple(self)\n terminal_width, terminal_height = terminal_size\n if width <= 0:\n width = max(terminal_width + width, 1)\n if height <= 0:\n height = max(terminal_height + height, 1)\n\n return type(self)(width, height, *args)\n\n # Extension methods ========================================================\n\n @override\n def _get_exact_dimensions_(self, render_size: Size) -> tuple[int, int, int, int]:\n if self.relative:\n raise RelativePaddingDimensionError(\"Relative minimum render dimension(s)\")\n\n width, height, h_align, v_align = astuple(self)[:4]\n render_width, render_height = render_size\n\n if width > render_width:\n padding_width = width - render_width\n numerator, denominator = _ALIGN_RATIOS[h_align]\n left = padding_width * numerator // denominator\n right = padding_width - left\n else:\n left = right = 0\n\n if height > render_height:\n padding_height = height - render_height\n numerator, denominator = _ALIGN_RATIOS[v_align]\n top = padding_height * numerator // denominator\n bottom = padding_height - top\n else:\n top = bottom = 0\n\n return left, top, right, bottom", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 5973}, "tests/test_image/test_url.py::58": {"resolved_imports": ["src/term_image/exceptions.py", "src/term_image/image/block.py", "src/term_image/image/common.py", "src/term_image/image/__init__.py"], "used_names": ["BlockImage", "from_url", "os", "pytest"], "enclosing_function": "test_close", "extracted_code": "# Source: src/term_image/image/block.py\nclass BlockImage(TextImage):\n \"\"\"A render style using unicode half blocks and direct-color colour escape\n sequences.\n\n See :py:class:`TextImage` for the description of the constructor.\n \"\"\"\n\n @classmethod\n def is_supported(cls):\n if cls._supported is None:\n COLORTERM = os.environ.get(\"COLORTERM\") or \"\"\n TERM = os.environ.get(\"TERM\") or \"\"\n cls._supported = (\n \"truecolor\" in COLORTERM or \"24bit\" in COLORTERM or \"256color\" in TERM\n )\n\n return cls._supported\n\n def _get_render_size(self) -> Tuple[int, int]:\n return tuple(map(mul, self.rendered_size, (1, 2)))\n\n @staticmethod\n def _pixels_cols(\n *, pixels: Optional[int] = None, cols: Optional[int] = None\n ) -> int:\n return pixels if pixels is not None else cols\n\n @staticmethod\n def _pixels_lines(\n *, pixels: Optional[int] = None, lines: Optional[int] = None\n ) -> int:\n return ceil(pixels / 2) if pixels is not None else lines * 2\n\n def _render_image(\n self,\n img: PIL.Image.Image,\n alpha: Union[None, float, str],\n *,\n frame: bool = False,\n split_cells: bool = False,\n ) -> str:\n # NOTE:\n # It's more efficient to write separate strings to the buffer separately\n # than concatenate and write together.\n\n def update_buffer():\n if alpha:\n no_alpha = False\n if a_cluster1 == 0 == a_cluster2:\n buf_write(SGR_DEFAULT)\n buf_write(blank * n)\n elif a_cluster1 == 0: # up is transparent\n buf_write(SGR_DEFAULT)\n buf_write(SGR_FG_DIRECT % cluster2)\n buf_write(lower_pixel * n)\n elif a_cluster2 == 0: # down is transparent\n buf_write(SGR_DEFAULT)\n buf_write(SGR_FG_DIRECT % cluster1)\n buf_write(upper_pixel * n)\n else:\n no_alpha = True\n\n if not alpha or no_alpha:\n r, g, b = cluster2\n # Kitty does not render BG colors equal to the default BG color\n if is_on_kitty and cluster2 == bg_color:\n r += r < 255 or -1\n buf_write(SGR_BG_DIRECT % (r, g, b))\n if cluster1 == cluster2:\n buf_write(blank * n)\n else:\n buf_write(SGR_FG_DIRECT % cluster1)\n buf_write(upper_pixel * n)\n\n buffer = io.StringIO()\n buf_write = buffer.write # Eliminate attribute resolution cost\n\n bg_color = get_fg_bg_colors()[1]\n is_on_kitty = self._is_on_kitty()\n if split_cells:\n blank = \" \\0\"\n lower_pixel = LOWER_PIXEL + \"\\0\"\n upper_pixel = UPPER_PIXEL + \"\\0\"\n else:\n blank = \" \"\n lower_pixel = LOWER_PIXEL\n upper_pixel = UPPER_PIXEL\n end_of_line = SGR_DEFAULT + \"\\n\"\n\n width, height = self._get_render_size()\n frame_img = img if frame else None\n img, rgb, a = self._get_render_data(img, alpha, round_alpha=True, frame=frame)\n alpha = img.mode == \"RGBA\"\n\n # clean up (ImageIterator uses one PIL image throughout)\n if frame_img is not img:\n self._close_image(img)\n\n rgb_pairs = (\n (\n zip(rgb[x : x + width], rgb[x + width : x + width * 2]),\n (rgb[x], rgb[x + width]),\n )\n for x in range(0, len(rgb), width * 2)\n )\n a_pairs = (\n (\n zip(a[x : x + width], a[x + width : x + width * 2]),\n (a[x], a[x + width]),\n )\n for x in range(0, len(a), width * 2)\n )\n\n row_no = 0\n # Two rows of pixels per line\n for (rgb_pair, (cluster1, cluster2)), (a_pair, (a_cluster1, a_cluster2)) in zip(\n rgb_pairs, a_pairs\n ):\n row_no += 2\n n = 0\n for (px1, px2), (a1, a2) in zip(rgb_pair, a_pair):\n # Color-code characters and write to buffer\n # when upper and/or lower pixel color/alpha-level changes\n if not (alpha and a1 == a_cluster1 == 0 == a_cluster2 == a2) and (\n px1 != cluster1\n or px2 != cluster2\n or alpha\n and (\n # From non-transparent to transparent\n a_cluster1 != a1 == 0\n or a_cluster2 != a2 == 0\n # From transparent to non-transparent\n or 0 == a_cluster1 != a1\n or 0 == a_cluster2 != a2\n )\n ):\n update_buffer()\n cluster1 = px1\n cluster2 = px2\n if alpha:\n a_cluster1 = a1\n a_cluster2 = a2\n n = 0\n n += 1\n\n update_buffer() # Rest of the line\n if split_cells:\n # Set the last \"\\0\" to be overwritten by the next byte\n buffer.seek(buffer.tell() - 1)\n if row_no < height: # last line not yet rendered\n buf_write(end_of_line)\n\n buf_write(SGR_DEFAULT) # Reset color after last line\n\n with buffer:\n return buffer.getvalue()\n\n\n# Source: src/term_image/image/__init__.py\ndef from_url(\n url: str,\n **kwargs: Union[None, int],\n) -> BaseImage:\n \"\"\"Creates an image instance from an image URL.\n\n Returns:\n An instance of the automatically selected image render style (as returned by\n :py:func:`auto_image_class`).\n\n Same arguments and raised exceptions as :py:meth:`BaseImage.from_url`.\n \"\"\"\n return auto_image_class().from_url(url, **kwargs)", "n_imports_parsed": 6, "n_files_resolved": 4, "n_chars_extracted": 6014}, "tests/test_color.py::38": {"resolved_imports": ["src/term_image/color.py"], "used_names": ["Color"], "enclosing_function": "test_a_default", "extracted_code": "# Source: src/term_image/color.py\nclass Color(_DummyColor):\n \"\"\"A color.\n\n Args:\n r: The red channel.\n g: The green channel.\n b: The blue channel.\n a: The alpha channel (opacity).\n\n Raises:\n ValueError: The value of a channel is not within the valid range.\n\n NOTE:\n The valid value range for all channels is 0 to 255, both inclusive.\n\n TIP:\n This class is a :py:class:`~typing.NamedTuple` of four fields.\n\n WARNING:\n In the case of multiple inheritance i.e if subclassing this class along with\n other classes, this class should appear last (i.e to the far right) in the\n base class list.\n \"\"\"\n\n __slots__ = ()\n\n # Overrides these descriptors in order to speed up attribute resolution and to\n # simplify auto documentation.\n r: int = _DummyColor.r\n r.__doc__ = \"\"\"The red channel\"\"\"\n\n g: int = _DummyColor.g\n g.__doc__ = \"\"\"The green channel\"\"\"\n\n b: int = _DummyColor.b\n b.__doc__ = \"\"\"The blue channel\"\"\"\n\n a: int = _DummyColor.a\n a.__doc__ = \"\"\"The alpha channel (opacity)\"\"\"\n\n def __new__(cls, r: int, g: int, b: int, a: int = 255) -> Self:\n # Only the 8 LSb may be set for any value within the range [0, 255].\n # `x & ~255` unsets the 8 LSb. Hence, if the result is non-zero (i.e any\n # of the bits above the lowest 8 is set), it implies `x` is out of range.\n #\n # Actually benchmarked *this* against the \"simpler\" logically-negated chained\n # comparison (i.e `0 <= x <= 255`) and *this* was significantly faster for all\n # cases i.e within, on the boundaries, and outside (on both sides).\n if (r | g | b | a) & ~255: # First test to see if *any* is out of range\n if r & ~255:\n raise arg_value_error_range(\"r\", r)\n if g & ~255:\n raise arg_value_error_range(\"g\", g)\n if b & ~255:\n raise arg_value_error_range(\"b\", b)\n # There's no point checking since at least one is out of range\n raise arg_value_error_range(\"a\", a)\n\n # Using `tuple` directly instead of `super()` for performance\n return tuple.__new__(cls, (r, g, b, a))\n\n @property\n def hex(self) -> str:\n \"\"\"Converts the color to its RGBA hexadecimal representation.\n\n Returns:\n The RGBA hex color string, starting with the ``#`` character i.e\n ``#rrggbbaa``.\n\n Each channel is represented by two **lowercase** hex digits ranging from\n ``00`` to ``ff``.\n \"\"\"\n return \"#%02x%02x%02x%02x\" % self\n\n @property\n def rgb(self) -> tuple[int, int, int]:\n \"\"\"Extracts the R, G and B channels of the color.\n\n Returns:\n A 3-tuple containing the red, green and blue channel values.\n \"\"\"\n return self[:3]\n\n @property\n def rgb_hex(self) -> str:\n \"\"\"Converts the color to its RGB hexadecimal representation.\n\n Returns:\n The RGB hex color string, starting with the ``#`` character i.e ``#rrggbb``.\n\n Each channel is represented by two **lowercase** hex digits ranging from\n ``00`` to ``ff``.\n \"\"\"\n return \"#%02x%02x%02x\" % self[:3]\n\n @classmethod\n def from_hex(cls, color: str) -> Self:\n \"\"\"Creates a new instance from a hexadecimal color string.\n\n Args:\n color: A **case-insensitive** RGB or RGBA hex color string, **optionally**\n starting with the ``#`` (pound) character i.e ``[#]rrggbb[aa]``.\n\n Returns:\n A new instance representing the given hex color string.\n\n Raises:\n ValueError: Invalid hex color string.\n\n NOTE:\n For an RGB hex color string, the value of A (the alpha channel) is\n taken to be 255.\n \"\"\"\n if not (match := _RGBA_HEX_RE.fullmatch(color)):\n raise ValueError(f\"Invalid hex color string (got: {color!r})\")\n\n return tuple.__new__(cls, [int(x, 16) for x in match.groups(\"ff\")])\n\n @classmethod\n def _new(cls, r: int, g: int, b: int, a: int = 255) -> Self:\n \"\"\"Alternate constructor for internal use only.\"\"\"\n return tuple.__new__(cls, (r, g, b, a))", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 4255}, "tests/test_top_level.py::71": {"resolved_imports": ["src/term_image/__init__.py", "src/term_image/utils.py", "src/term_image/exceptions.py", "src/term_image/geometry.py"], "used_names": ["AutoCellRatio", "Size", "get_cell_ratio", "reset_cell_size_ratio", "set_cell_ratio", "set_cell_size"], "enclosing_function": "test_dynamic", "extracted_code": "# Source: src/term_image/__init__.py\nclass AutoCellRatio(Enum):\n \"\"\":ref:`auto-cell-ratio` enumeration and support status.\n\n .. seealso:: :py:func:`set_cell_ratio`.\n \"\"\"\n\n FIXED = auto()\n \"\"\"Fixed cell ratio.\n\n :meta hide-value:\n \"\"\"\n\n DYNAMIC = auto()\n \"\"\"Dynamic cell ratio.\n\n :meta hide-value:\n \"\"\"\n\n is_supported: ClassVar[bool | None]\n \"\"\"Auto cell ratio support status. Can be\n\n :meta hide-value:\n\n - ``None`` -> support status not yet determined\n - ``True`` -> supported\n - ``False`` -> not supported\n\n Can be explicitly set when using auto cell ratio but want to avoid the support\n check in a situation where the support status is foreknown. Can help to avoid\n being wrongly detected as unsupported on a :ref:`queried `\n terminal that doesn't respond on time.\n\n For instance, when using multiprocessing, if the support status has been\n determined in the main process, this value can simply be passed on to and set\n within the child processes.\n \"\"\"\n\ndef get_cell_ratio() -> float:\n \"\"\"Returns the global :term:`cell ratio`.\n\n .. seealso:: :py:func:`set_cell_ratio`.\n \"\"\"\n # `(1, 2)` is a fallback in case the terminal doesn't respond in time\n return _cell_ratio or truediv(*(get_cell_size() or (1, 2)))\n\ndef set_cell_ratio(ratio: float | AutoCellRatio) -> None:\n \"\"\"Sets the global :term:`cell ratio`.\n\n Args:\n ratio: Can be one of the following values.\n\n * A positive :py:class:`float` value.\n * :py:attr:`AutoCellRatio.FIXED`, the ratio is immediately determined from\n the :term:`active terminal`.\n * :py:attr:`AutoCellRatio.DYNAMIC`, the ratio is determined from the\n :term:`active terminal` whenever :py:func:`get_cell_ratio` is called,\n though with some caching involved, such that the ratio is re-determined\n only if the terminal size changes.\n\n Raises:\n ValueError: *ratio* is a non-positive :py:class:`float`.\n term_image.exceptions.TermImageError: Auto cell ratio is not supported\n in the :term:`active terminal` or on the current platform.\n\n This value is taken into consideration when setting image sizes for **text-based**\n render styles, in order to preserve the aspect ratio of images drawn to the\n terminal.\n\n NOTE:\n Changing the cell ratio does not automatically affect any image that has a\n :term:`fixed size`. For a change in cell ratio to take effect, the image's\n size has to be re-set.\n\n IMPORTANT:\n See :ref:`auto-cell-ratio` for details about the auto modes.\n \"\"\"\n global _cell_ratio\n\n if isinstance(ratio, AutoCellRatio):\n if AutoCellRatio.is_supported is None:\n AutoCellRatio.is_supported = get_cell_size() is not None\n\n if not AutoCellRatio.is_supported:\n raise TermImageError(\n \"Auto cell ratio is not supported in the active terminal or on the \"\n \"current platform\"\n )\n elif ratio is AutoCellRatio.FIXED:\n # `(1, 2)` is a fallback in case the terminal doesn't respond in time\n _cell_ratio = truediv(*(get_cell_size() or (1, 2)))\n else:\n _cell_ratio = None\n else:\n if ratio <= 0.0:\n raise arg_value_error_range(\"ratio\", ratio)\n _cell_ratio = ratio\n\n\n# Source: src/term_image/geometry.py\nclass Size(RawSize):\n \"\"\"The dimensions of a rectangular region.\n\n Raises:\n ValueError: Either dimension is non-positive.\n\n Same as :py:class:`RawSize`, except that both dimensions must be **positive**.\n\n IMPORTANT:\n In the case of multiple inheritance i.e if subclassing this class along with\n other classes, this class should appear last (i.e to the far right) in the\n base class list.\n \"\"\"\n\n __slots__ = ()\n\n def __new__(cls, width: int, height: int) -> Self:\n if width < 1:\n raise arg_value_error_range(\"width\", width)\n if height < 1:\n raise arg_value_error_range(\"height\", height)\n\n # Using `tuple` directly instead of `super()` for performance\n return tuple.__new__(cls, (width, height))", "n_imports_parsed": 6, "n_files_resolved": 4, "n_chars_extracted": 4235}, "tests/widget/urwid/test_main.py::172": {"resolved_imports": ["src/term_image/__init__.py", "src/term_image/_ctlseqs.py", "src/term_image/exceptions.py", "src/term_image/image/block.py", "src/term_image/image/common.py", "src/term_image/image/iterm2.py", "src/term_image/image/kitty.py", "src/term_image/widget/_urwid.py"], "used_names": ["Size", "UrwidImage"], "enclosing_function": "test_upscale_true", "extracted_code": "# Source: src/term_image/image/common.py\nclass Size(Enum):\n \"\"\"Enumeration for :term:`automatic sizing`.\"\"\"\n\n #: Equivalent to :py:attr:`ORIGINAL` if it will fit into the\n #: :term:`frame size`, else :py:attr:`FIT`.\n #:\n #: :meta hide-value:\n AUTO = Hidden()\n\n #: The image size is set to fit optimally **within** the :term:`frame size`.\n #:\n #: :meta hide-value:\n FIT = Hidden()\n\n #: The size is set such that the width is exactly the :term:`frame width`,\n #: regardless of the :term:`cell ratio`.\n #:\n #: :meta hide-value:\n FIT_TO_WIDTH = Hidden()\n\n #: The image size is set such that the image is rendered with as many pixels as the\n #: the original image consists of.\n #:\n #: :meta hide-value:\n ORIGINAL = Hidden()\n\n\n# Source: src/term_image/widget/_urwid.py\nclass UrwidImage(urwid.Widget):\n \"\"\"Image widget (box/flow) for the urwid TUI framework.\n\n Args:\n image: The image to be rendered by the widget.\n format_spec: :ref:`Render format specifier `. Padding width and\n height are ignored.\n upscale: If ``True``, the image will be upscaled to fit maximally within the\n available size, if necessary, while still preserving the aspect ratio.\n Otherwise, the image is never upscaled.\n\n Raises:\n TypeError: An argument is of an inappropriate type.\n ValueError: An argument is of an appropriate type but has an\n unexpected/invalid value.\n term_image.exceptions.StyleError: Invalid style-specific format specifier.\n term_image.exceptions.UrwidImageError: Too many image widgets rendering images\n with the *kitty* render style.\n\n | Any ample space in the widget's render size is filled with spaces.\n | For animated images, the current frame (at render-time) is rendered.\n\n TIP:\n If *image* is of a :ref:`graphics-based ` render style and the\n widget is being used as or within a **flow** widget, with overlays or in any\n other case where the canvas will require vertical trimming, make sure to use a\n render method that splits images across lines such as the **LINES** render\n method for *kitty* and *iterm2* render styles.\n\n NOTE:\n * The `z-index` style-specific format spec field for\n :py:class:`~term_image.image.KittyImage` is ignored as this is used\n internally.\n * A **maximum** of ``2**32 - 2`` instances initialized with\n :py:class:`~term_image.image.KittyImage` instances may exist at the same time.\n\n IMPORTANT:\n This is defined if and only if the ``urwid`` package is available.\n \"\"\"\n\n _sizing = frozenset((urwid.BOX, urwid.FLOW))\n ignore_focus = True\n\n _ti_error_placeholder = None\n\n # For kitty images\n _ti_disguise_state = 0\n _ti_free_z_indexes = set()\n\n # Progresses thus: 1, -1, 2, -2, 3, ..., 2**31 - 1, -(2**31 - 1)\n # This sequence results in shorter image escape sequences compared to starting\n # from -(2**31)\n _ti_next_z_index = 1\n\n def __init__(\n self, image: BaseImage, format_spec: str = \"\", *, upscale: bool = False\n ) -> None:\n if not isinstance(image, BaseImage):\n raise arg_type_error(\"image\", image)\n\n if not isinstance(format_spec, str):\n raise arg_type_error(\"format_spec\", format_spec)\n *fmt, alpha, style_args = image._check_format_spec(format_spec)\n\n if not isinstance(upscale, bool):\n raise arg_type_error(\"upscale\", upscale)\n\n super().__init__()\n self._ti_image = image\n self._ti_h_align, _, self._ti_v_align, _ = fmt\n self._ti_alpha = alpha\n self._ti_style_args = style_args\n self._ti_sizing = Size.FIT if upscale else Size.AUTO\n\n if isinstance(image, TextImage):\n style_args[\"split_cells\"] = True\n elif isinstance(image, KittyImage):\n style_args[\"z_index\"] = self._ti_z_index = self._ti_get_z_index()\n\n # Since Konsole doesn't blend images placed at the same location and\n # z-index, unlike Kitty (and potentially others), `blend=True` is\n # better on Konsole as it reduces/eliminates flicker.\n if get_terminal_name_version()[0] != \"konsole\":\n # To clear directly overlapped images when urwid redraws a line without\n # a change in image position\n style_args[\"blend\"] = False\n\n def __del__(self) -> None:\n if hasattr(self, \"_ti_z_index\"):\n __class__._ti_free_z_indexes.add(self._ti_z_index)\n\n image = property(\n lambda self: self._ti_image,\n doc=\"\"\"\n The image rendered by the widget\n\n :type: BaseImage\n\n GET:\n Returns the image instance rendered by the widget.\n \"\"\",\n )\n\n def render(self, size: Tuple[int, int], focus: bool = False) -> urwid.Canvas:\n image = self._ti_image\n\n if len(size) == 2: # box\n image.set_size(self._ti_sizing, frame_size=size)\n elif len(size) == 1: # flow\n if self._ti_sizing is Size.FIT:\n image.set_size(size[0])\n else:\n fit_size = self._ti_image._valid_size(size[0])\n ori_size = self._ti_image._valid_size(Size.ORIGINAL)\n image._size = (\n ori_size\n if ori_size[0] <= fit_size[0] and ori_size[1] <= fit_size[1]\n else fit_size\n )\n size = (size[0], image._size[1])\n else: # fixed\n raise UrwidImageError(\"Not a fixed widget\")\n\n try:\n render = image._format_render(\n image._renderer(\n image._render_image, self._ti_alpha, **self._ti_style_args\n ),\n self._ti_h_align,\n size[0],\n self._ti_v_align,\n size[1],\n )\n except Exception:\n if type(self)._ti_error_placeholder is None:\n raise\n canv = type(self)._ti_error_placeholder.render(size, focus)\n else:\n canv = UrwidImageCanvas(render, size, image._size)\n\n return canv\n\n def rows(self, size: Tuple[int], focus: bool = False) -> int:\n fit_size = self._ti_image._valid_size(size[0])\n if self._ti_sizing is Size.FIT:\n n_rows = fit_size[1]\n else:\n ori_size = self._ti_image._valid_size(Size.ORIGINAL)\n n_rows = (\n ori_size[1]\n if ori_size[0] <= fit_size[0] and ori_size[1] <= fit_size[1]\n else fit_size[1]\n )\n\n return n_rows\n\n @classmethod\n def set_error_placeholder(cls, widget: Optional[urwid.Widget]) -> None:\n \"\"\"Sets the widget to be rendered in place of an image when rendering fails.\n\n Args:\n widget: The placeholder widget or ``None`` to remove the placeholder.\n\n Raises:\n TypeError: *widget* is not an urwid widget.\n\n If set, any exception raised during rendering is **suppressed** and the\n placeholder is rendered in place of the image.\n \"\"\"\n if not isinstance(widget, urwid.Widget):\n raise arg_type_error(\"widget\", widget)\n\n cls._ti_error_placeholder = widget\n\n @staticmethod\n def _ti_get_z_index() -> int:\n if __class__._ti_free_z_indexes:\n return __class__._ti_free_z_indexes.pop()\n\n z_index = __class__._ti_next_z_index\n if z_index == 2**31:\n raise UrwidImageError(\"Too many image widgets with the kitty render style\")\n __class__._ti_next_z_index = -z_index if z_index > 0 else -z_index + 1\n\n return z_index\n\n def _ti_change_disguise(self) -> None:\n \"\"\"See :py:meth`UrwidImageCanvas._ti_change_disguise`.\"\"\"\n self._ti_disguise_state = (self._ti_disguise_state + 1) % 3", "n_imports_parsed": 10, "n_files_resolved": 8, "n_chars_extracted": 7948}, "tests/test_image/test_base.py::498": {"resolved_imports": ["src/term_image/__init__.py", "src/term_image/_ctlseqs.py", "src/term_image/exceptions.py", "src/term_image/image/block.py", "src/term_image/image/common.py"], "used_names": ["reset_cell_size_ratio", "set_cell_ratio"], "enclosing_function": "test_frame_size_absolute", "extracted_code": "# Source: src/term_image/__init__.py\ndef set_cell_ratio(ratio: float | AutoCellRatio) -> None:\n \"\"\"Sets the global :term:`cell ratio`.\n\n Args:\n ratio: Can be one of the following values.\n\n * A positive :py:class:`float` value.\n * :py:attr:`AutoCellRatio.FIXED`, the ratio is immediately determined from\n the :term:`active terminal`.\n * :py:attr:`AutoCellRatio.DYNAMIC`, the ratio is determined from the\n :term:`active terminal` whenever :py:func:`get_cell_ratio` is called,\n though with some caching involved, such that the ratio is re-determined\n only if the terminal size changes.\n\n Raises:\n ValueError: *ratio* is a non-positive :py:class:`float`.\n term_image.exceptions.TermImageError: Auto cell ratio is not supported\n in the :term:`active terminal` or on the current platform.\n\n This value is taken into consideration when setting image sizes for **text-based**\n render styles, in order to preserve the aspect ratio of images drawn to the\n terminal.\n\n NOTE:\n Changing the cell ratio does not automatically affect any image that has a\n :term:`fixed size`. For a change in cell ratio to take effect, the image's\n size has to be re-set.\n\n IMPORTANT:\n See :ref:`auto-cell-ratio` for details about the auto modes.\n \"\"\"\n global _cell_ratio\n\n if isinstance(ratio, AutoCellRatio):\n if AutoCellRatio.is_supported is None:\n AutoCellRatio.is_supported = get_cell_size() is not None\n\n if not AutoCellRatio.is_supported:\n raise TermImageError(\n \"Auto cell ratio is not supported in the active terminal or on the \"\n \"current platform\"\n )\n elif ratio is AutoCellRatio.FIXED:\n # `(1, 2)` is a fallback in case the terminal doesn't respond in time\n _cell_ratio = truediv(*(get_cell_size() or (1, 2)))\n else:\n _cell_ratio = None\n else:\n if ratio <= 0.0:\n raise arg_value_error_range(\"ratio\", ratio)\n _cell_ratio = ratio", "n_imports_parsed": 16, "n_files_resolved": 5, "n_chars_extracted": 2121}, "tests/test_image/common.py::509": {"resolved_imports": ["src/term_image/__init__.py", "src/term_image/_ctlseqs.py", "src/term_image/exceptions.py", "src/term_image/image/common.py", "src/term_image/utils.py"], "used_names": ["SGR_DEFAULT", "_ALPHA_THRESHOLD"], "enclosing_function": "test_split_cells", "extracted_code": "# Source: src/term_image/_ctlseqs.py\nSGR_DEFAULT = SGR % \"\"\n\n\n# Source: src/term_image/image/common.py\n_ALPHA_THRESHOLD = 40 / 255", "n_imports_parsed": 11, "n_files_resolved": 5, "n_chars_extracted": 130}, "tests/test_geometry.py::23": {"resolved_imports": ["src/term_image/geometry.py"], "used_names": ["RawSize"], "enclosing_function": "test_is_tuple", "extracted_code": "# Source: src/term_image/geometry.py\nclass RawSize(NamedTuple):\n \"\"\"The dimensions of a rectangular region.\n\n Args:\n width: The horizontal dimension\n height: The vertical dimension\n\n NOTE:\n * A dimension may be non-positive but the validity and meaning would be\n determined by the receiving interface.\n * This is a subclass of :py:class:`tuple`. Hence, instances can be used anyway\n and anywhere tuples can.\n \"\"\"\n\n width: int\n height: int\n\n @classmethod\n def _new(cls, width: int, height: int) -> Self:\n \"\"\"Alternate constructor for internal use only.\"\"\"\n return tuple.__new__(cls, (width, height))", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 682}, "tests/widget/urwid/test_screen.py::174": {"resolved_imports": ["src/term_image/__init__.py", "src/term_image/_ctlseqs.py", "src/term_image/image/block.py", "src/term_image/image/iterm2.py", "src/term_image/image/kitty.py", "src/term_image/widget/_urwid.py"], "used_names": ["KittyImage", "UrwidImage"], "enclosing_function": "test_not_supported", "extracted_code": "# Source: src/term_image/image/kitty.py\nclass KittyImage(GraphicsImage):\n \"\"\"A render style using the Kitty terminal graphics protocol.\n\n See :py:class:`GraphicsImage` for the complete description of the constructor.\n\n |\n\n **Render Methods**\n\n :py:class:`KittyImage` provides two methods of :term:`rendering` images, namely:\n\n LINES (default)\n Renders an image line-by-line i.e the image is evenly split across the number\n of lines it should occupy.\n\n Pros:\n\n * Good for use cases where it might be required to trim some lines of the\n image.\n\n WHOLE\n Renders an image all at once i.e the entire image data is encoded into one\n line of the :term:`rendered` output, such that the entire image is drawn once\n by the terminal and still occupies the correct amount of lines and columns.\n\n Pros:\n\n * Render results are more compact (i.e less in character count) than with\n the **LINES** method since the entire image is encoded at once.\n\n The render method can be set with\n :py:meth:`set_render_method() ` using the names\n specified above.\n\n |\n\n **Style-Specific Render Parameters**\n\n See :py:meth:`BaseImage.draw` (particularly the *style* parameter).\n\n * **method** (*None | str*) → Render method override.\n\n * ``None`` → the current effective render method of the instance is used.\n * *default* → ``None``\n\n * **z_index** (*int*) → The stacking order of graphics and text for\n **non-animations**.\n\n * An integer in the **signed 32-bit** range (excluding ``-(2**31)``)\n * ``>= 0`` → the image will be drawn above text\n * ``< 0`` → the image will be drawn below text\n * ``< -(2**31)/2`` → the image will be drawn below cells with non-default\n background color\n * *default* → ``0``\n * Overlapping graphics on different z-indexes will be blended (by the terminal\n emulator) if they are semi-transparent.\n * To inter-mix text with graphics, see the *mix* parameter.\n\n * **mix** (*bool*) → Graphics/Text inter-mix policy.\n\n * ``False`` → text within the region covered by the drawn render output will be\n erased, though text can be inter-mixed with graphics after drawing\n * ``True`` → text within the region covered by the drawn render output will NOT\n be erased\n * *default* → ``False``\n\n * **compress** (*int*) → ZLIB compression level.\n\n * ``0`` <= *compress* <= ``9``\n * ``1`` → best speed, ``9`` → best compression, ``0`` → no compression\n * *default* → ``4``\n * Results in a trade-off between render time and data size/draw speed\n\n |\n\n **Format Specification**\n\n See :ref:`format-spec`.\n\n ::\n\n [ ] [ z ] [ m ] [ c ]\n\n * ``method`` → render method override\n\n * ``L`` → **LINES** render method (current frame only, for animated images)\n * ``W`` → **WHOLE** render method (current frame only, for animated images)\n * *default* → Current effective render method of the image\n\n * ``z`` → graphics/text stacking order\n\n * ``z-index`` → z-index\n\n * An integer in the **signed 32-bit** range (excluding ``-(2**31)``)\n * ``>= 0`` → the render output will be drawn above text\n * ``< 0`` → the render output will be drawn below text\n * ``< -(2**31)/2`` → the render output will be drawn below cells with\n non-default background color\n\n * *default* → ``z0`` (z-index zero)\n * e.g ``z0``, ``z1``, ``z-1``, ``z2147483647``, ``z-2147483648``\n * overlapping graphics on different z-indexes will be blended\n (by the terminal emulator) if they are semi-transparent\n\n * ``m`` → graphics/text inter-mix policy\n\n * ``mix`` → inter-mix policy\n\n * ``0`` → text within the region covered by the drawn render output will be\n erased, though text can be inter-mixed with graphics after drawing\n * ``1`` → text within the region covered by the drawn render output will NOT\n be erased\n\n * *default* → ``m0``\n * e.g ``m0``, ``m1``\n\n * ``c`` → ZLIB compression level\n\n * ``compress`` → compression level\n\n * An integer in the range ``0`` <= ``compress`` <= ``9``\n * ``1`` → best speed, ``9`` → best compression, ``0`` → no compression\n\n * *default* → ``c4``\n * e.g ``c0``, ``c9``\n * results in a trade-off between render time and data size/draw speed\n\n |\n\n IMPORTANT:\n Currently supported terminal emulators are:\n\n * `Kitty `_ >= 0.20.0.\n * `Konsole `_ >= 22.04.0.\n \"\"\"\n\n _FORMAT_SPEC: Tuple[re.Pattern] = tuple(\n map(re.compile, r\"[LW] z-?\\d+ m[01] c[0-9]\".split(\" \"))\n )\n _render_methods: Set[str] = {LINES, WHOLE}\n _default_render_method: str = LINES\n _render_method: str = LINES\n _style_args = {\n \"method\": (\n None,\n (\n lambda x: isinstance(x, str),\n \"Render method must be a string\",\n ),\n (\n lambda x: x.lower() in __class__._render_methods,\n \"Unknown render method for 'kitty' render style\",\n ),\n ),\n \"z_index\": (\n 0,\n (\n lambda x: isinstance(x, int),\n \"z-index must be an integer\",\n ),\n (\n # INT32_MIN is reserved for non-native animations\n lambda x: -(2**31) < x < 2**31,\n \"z-index must be within the 32-bit signed integer range \"\n \"(excluding ``-(2**31)``)\",\n ),\n ),\n \"mix\": (\n False,\n (\n lambda x: isinstance(x, bool),\n \"Inter-mix policy must be a boolean\",\n ),\n (lambda _: True, \"\"),\n ),\n \"compress\": (\n 4,\n (\n lambda x: isinstance(x, int),\n \"Compression level must be an integer\",\n ),\n (\n lambda x: 0 <= x <= 9,\n \"Compression level must be between 0 and 9, both inclusive\",\n ),\n ),\n }\n\n _TERM: str = \"\"\n _TERM_VERSION: str = \"\"\n _KITTY_VERSION: Tuple[int, int, int] = ()\n\n @classmethod\n def clear(\n cls, *, cursor: bool = False, z_index: Optional[int] = None, now: bool = False\n ) -> None:\n \"\"\"Clears images.\n\n Args:\n cursor: If ``True``, all images intersecting with the current cursor\n position are cleared.\n z_index: An integer in the **signed 32-bit range**. If given, all images\n on the given z-index are cleared.\n now: If ``True`` the images are cleared immediately, without affecting\n any standard I/O stream.\n Otherwise they're cleared when next :py:data:`sys.stdout` is flushed.\n\n Aside *now*, **only one** other argument may be given. If no argument is given\n (aside *now*) or default values are given, all images visible on the screen are\n cleared.\n\n NOTE:\n This method does nothing if the render style is not supported.\n \"\"\"\n if not (cls._forced_support or cls.is_supported()):\n return\n\n if not isinstance(cursor, bool):\n raise arg_type_error(\"cursor\", cursor)\n\n if z_index is not None:\n if not isinstance(z_index, int):\n raise arg_type_error(\"z_index\", z_index)\n if not -(1 << 31) <= z_index < (1 << 31):\n raise arg_value_error_range(\"z_index\", z_index)\n\n if not isinstance(now, bool):\n raise arg_type_error(\"now\", now)\n\n default_args = __class__.clear.__func__.__kwdefaults__\n nonlocals = locals()\n args = {name: nonlocals[name] for name in default_args}\n given_args = args.items() - (default_args.items() | {(\"now\", True)})\n\n if len(given_args) > 1:\n raise arg_value_error_msg(\n \"Only one argument (aside 'now') may be given\", len(given_args)\n )\n elif given_args:\n arg, _ = given_args.pop()\n (write_tty if now else _stdout_write)(\n (ctlseqs.KITTY_DELETE_CURSOR_b if now else ctlseqs.KITTY_DELETE_CURSOR)\n if arg == \"cursor\"\n else (\n (\n ctlseqs.KITTY_DELETE_Z_INDEX_b\n if now\n else ctlseqs.KITTY_DELETE_Z_INDEX\n )\n % z_index\n )\n )\n elif now:\n write_tty(ctlseqs.KITTY_DELETE_ALL_b)\n else:\n _stdout_write(ctlseqs.KITTY_DELETE_ALL)\n\n @classmethod\n def is_supported(cls) -> bool:\n if cls._supported is None:\n cls._supported = False\n\n # The graphics query for support detection messes up iTerm2's window title\n if get_terminal_name_version()[0] == \"iterm2\":\n return False\n\n # Kitty graphics query + terminal attribute query\n # The second query is to speed up the query since most (if not all)\n # terminals should support it and most terminals treat queries as FIFO\n response = query_terminal(\n ctlseqs.KITTY_SUPPORT_QUERY_b + ctlseqs.DA1_b,\n lambda s: not s.endswith(b\"c\"),\n )\n\n # Not supported if it doesn't respond to either query\n # or responds to the second but not the first\n if response:\n response = ctlseqs.KITTY_RESPONSE_re.match(response.decode())\n if response and response[\"id\"] == \"31\" and response[\"message\"] == \"OK\":\n name, version = get_terminal_name_version()\n # Only kitty >= 0.20.0 implement the protocol features utilized\n if name == \"kitty\" and version:\n try:\n version_tuple = tuple(map(int, version.split(\".\")))\n except ValueError: # Version string not \"understood\"\n pass\n else:\n if version_tuple >= (0, 20, 0):\n cls._TERM, cls._TERM_VERSION = name, version\n cls._KITTY_VERSION = version_tuple\n cls._supported = True\n # Konsole is good as long as it responds to the graphics query\n elif name == \"konsole\":\n cls._TERM, cls._TERM_VERSION = name, version or \"\"\n cls._supported = True\n\n return cls._supported\n\n @classmethod\n def _check_style_format_spec(cls, spec: str, original: str) -> Dict[str, Any]:\n parent, (method, z_index, mix, compress) = cls._get_style_format_spec(\n spec, original\n )\n args = {}\n if parent:\n args.update(super()._check_style_format_spec(parent, original))\n if method:\n args[\"method\"] = LINES if method == \"L\" else WHOLE\n if z_index:\n args[\"z_index\"] = int(z_index[1:])\n if mix:\n args[\"mix\"] = bool(int(mix[-1]))\n if compress:\n args[\"compress\"] = int(compress[-1])\n\n return cls._check_style_args(args)\n\n @classmethod\n def _clear_frame(cls) -> bool:\n \"\"\"Clears an animation frame on-screen.\n\n | Only used on Kitty <= 0.25.0 because ``blend=False`` is buggy on these\n versions. Does nothing on any other version or terminal.\n | Also clears any frame of any previously drawn animation, since they all use\n the same z-index.\n\n See :py:meth:`~term_image.image.BaseImage._clear_frame` for description.\n \"\"\"\n if cls._KITTY_VERSION and cls._KITTY_VERSION <= (0, 25, 0):\n cls.clear(z_index=-(1 << 31))\n return True\n return False\n\n def _display_animated(self, *args, **kwargs) -> None:\n kwargs[\"z_index\"] = -(1 << 31)\n if self._KITTY_VERSION > (0, 25, 0):\n kwargs[\"blend\"] = False\n\n super()._display_animated(*args, **kwargs)\n\n @staticmethod\n def _handle_interrupted_draw():\n \"\"\"Performs necessary actions when image drawing is interrupted.\n\n If drawing is interrupted while transmitting a command, it causes terminal to\n wait for more data (in fact, it actually consumes any output following)\n until the output reaches the expected payload size or ST (String Terminator)\n is written.\n\n Also, if the image data was chunked, it would be expecting the last chunk.\n In this case, output is not consumed but the next graphics command sent\n might not be treated as expected on some terminals e.g Konsole.\n \"\"\"\n\n # End last command (does no harm if there wasn't an unterminated command)\n # and send \"last chunk\" in case the last transmission was chunked.\n # Konsole sometimes requires ST to be written twice.\n print(ctlseqs.ST * 2 + ctlseqs.KITTY_END_CHUNKED, end=\"\", flush=True)\n\n def _render_image(\n self,\n img: PIL.Image.Image,\n alpha: Union[None, float, str],\n *,\n frame: bool = False,\n method: Optional[str] = None,\n z_index: int = 0,\n mix: bool = False,\n compress: int = 4,\n blend: bool = True,\n ) -> str:\n \"\"\"See :py:meth:`BaseImage._render_image` for the description of the method and\n :py:meth:`draw` for parameters not described here.\n\n Args:\n blend: If ``False``, the rendered image deletes overlapping/intersecting\n images when drawn. Otherwise, the behaviour is dependent on the z-index\n and/or the terminal emulator (for images with the same z-index).\n \"\"\"\n # NOTE: It's more efficient to write separate strings to the buffer separately\n # than concatenate and write together.\n\n # Using `c` and `r` ensures that an image always occupies the correct amount\n # of columns and lines even if the cell size has changed when it's drawn.\n # Since we use `c` and `r` control data keys, there's no need upscaling the\n # image on this end to reduce payload.\n # Anyways, this also implies that the image(s) have to be resized by the\n # terminal emulator, thereby leaving various details of resizing in the hands\n # of the terminal emulator such as the resampling method, etc.\n # This particularly affects the LINES render method negatively, resulting in\n # slant/curved edges not lining up across lines (amongst other artifacts\n # observed on Konsole) supposedly because the terminal emulator resizes each\n # line separately.\n # Hence, this optimization is only used for the WHOLE render method.\n\n render_method = (method or self._render_method).lower()\n r_width, r_height = self.rendered_size\n width, height = (\n self._get_minimal_render_size()\n if render_method == WHOLE\n else self._get_render_size()\n )\n\n frame_img = img if frame else None\n img = self._get_render_data(\n img, alpha, size=(width, height), pixel_data=False, frame=frame # fmt: skip\n )[0]\n format = getattr(f, img.mode)\n raw_image = img.tobytes()\n\n # clean up (ImageIterator uses one PIL image throughout)\n if frame_img is not img:\n self._close_image(img)\n\n control_data = ControlData(f=format, s=width, c=r_width, z=z_index)\n fill = (\"\" if mix else ERASE_CHARS % r_width) + (CURSOR_FORWARD % r_width)\n fill_newline = fill + \"\\n\"\n\n if render_method == LINES:\n cell_height = height // r_height\n bytes_per_line = width * cell_height * (format // 8)\n vars(control_data).update(v=cell_height, r=1)\n\n with io.StringIO() as buffer, io.BytesIO(raw_image) as raw_image:\n trans = Transmission(\n control_data, raw_image.read(bytes_per_line), compress\n )\n blend or buffer.write(KITTY_DELETE_CURSOR)\n for chunk in trans.get_chunks():\n buffer.write(chunk)\n for _ in range(r_height - 1):\n buffer.write(fill_newline)\n trans = Transmission(\n control_data, raw_image.read(bytes_per_line), compress\n )\n blend or buffer.write(KITTY_DELETE_CURSOR)\n for chunk in trans.get_chunks():\n buffer.write(chunk)\n buffer.write(fill)\n\n return buffer.getvalue()\n\n vars(control_data).update(v=height, r=r_height)\n return \"\".join(\n (\n KITTY_DELETE_CURSOR * (not blend),\n Transmission(control_data, raw_image, compress).get_chunked(),\n fill_newline * (r_height - 1),\n fill,\n )\n )\n\n\n# Source: src/term_image/widget/_urwid.py\nclass UrwidImage(urwid.Widget):\n \"\"\"Image widget (box/flow) for the urwid TUI framework.\n\n Args:\n image: The image to be rendered by the widget.\n format_spec: :ref:`Render format specifier `. Padding width and\n height are ignored.\n upscale: If ``True``, the image will be upscaled to fit maximally within the\n available size, if necessary, while still preserving the aspect ratio.\n Otherwise, the image is never upscaled.\n\n Raises:\n TypeError: An argument is of an inappropriate type.\n ValueError: An argument is of an appropriate type but has an\n unexpected/invalid value.\n term_image.exceptions.StyleError: Invalid style-specific format specifier.\n term_image.exceptions.UrwidImageError: Too many image widgets rendering images\n with the *kitty* render style.\n\n | Any ample space in the widget's render size is filled with spaces.\n | For animated images, the current frame (at render-time) is rendered.\n\n TIP:\n If *image* is of a :ref:`graphics-based ` render style and the\n widget is being used as or within a **flow** widget, with overlays or in any\n other case where the canvas will require vertical trimming, make sure to use a\n render method that splits images across lines such as the **LINES** render\n method for *kitty* and *iterm2* render styles.\n\n NOTE:\n * The `z-index` style-specific format spec field for\n :py:class:`~term_image.image.KittyImage` is ignored as this is used\n internally.\n * A **maximum** of ``2**32 - 2`` instances initialized with\n :py:class:`~term_image.image.KittyImage` instances may exist at the same time.\n\n IMPORTANT:\n This is defined if and only if the ``urwid`` package is available.\n \"\"\"\n\n _sizing = frozenset((urwid.BOX, urwid.FLOW))\n ignore_focus = True\n\n _ti_error_placeholder = None\n\n # For kitty images\n _ti_disguise_state = 0\n _ti_free_z_indexes = set()\n\n # Progresses thus: 1, -1, 2, -2, 3, ..., 2**31 - 1, -(2**31 - 1)\n # This sequence results in shorter image escape sequences compared to starting\n # from -(2**31)\n _ti_next_z_index = 1\n\n def __init__(\n self, image: BaseImage, format_spec: str = \"\", *, upscale: bool = False\n ) -> None:\n if not isinstance(image, BaseImage):\n raise arg_type_error(\"image\", image)\n\n if not isinstance(format_spec, str):\n raise arg_type_error(\"format_spec\", format_spec)\n *fmt, alpha, style_args = image._check_format_spec(format_spec)\n\n if not isinstance(upscale, bool):\n raise arg_type_error(\"upscale\", upscale)\n\n super().__init__()\n self._ti_image = image\n self._ti_h_align, _, self._ti_v_align, _ = fmt\n self._ti_alpha = alpha\n self._ti_style_args = style_args\n self._ti_sizing = Size.FIT if upscale else Size.AUTO\n\n if isinstance(image, TextImage):\n style_args[\"split_cells\"] = True\n elif isinstance(image, KittyImage):\n style_args[\"z_index\"] = self._ti_z_index = self._ti_get_z_index()\n\n # Since Konsole doesn't blend images placed at the same location and\n # z-index, unlike Kitty (and potentially others), `blend=True` is\n # better on Konsole as it reduces/eliminates flicker.\n if get_terminal_name_version()[0] != \"konsole\":\n # To clear directly overlapped images when urwid redraws a line without\n # a change in image position\n style_args[\"blend\"] = False\n\n def __del__(self) -> None:\n if hasattr(self, \"_ti_z_index\"):\n __class__._ti_free_z_indexes.add(self._ti_z_index)\n\n image = property(\n lambda self: self._ti_image,\n doc=\"\"\"\n The image rendered by the widget\n\n :type: BaseImage\n\n GET:\n Returns the image instance rendered by the widget.\n \"\"\",\n )\n\n def render(self, size: Tuple[int, int], focus: bool = False) -> urwid.Canvas:\n image = self._ti_image\n\n if len(size) == 2: # box\n image.set_size(self._ti_sizing, frame_size=size)\n elif len(size) == 1: # flow\n if self._ti_sizing is Size.FIT:\n image.set_size(size[0])\n else:\n fit_size = self._ti_image._valid_size(size[0])\n ori_size = self._ti_image._valid_size(Size.ORIGINAL)\n image._size = (\n ori_size\n if ori_size[0] <= fit_size[0] and ori_size[1] <= fit_size[1]\n else fit_size\n )\n size = (size[0], image._size[1])\n else: # fixed\n raise UrwidImageError(\"Not a fixed widget\")\n\n try:\n render = image._format_render(\n image._renderer(\n image._render_image, self._ti_alpha, **self._ti_style_args\n ),\n self._ti_h_align,\n size[0],\n self._ti_v_align,\n size[1],\n )\n except Exception:\n if type(self)._ti_error_placeholder is None:\n raise\n canv = type(self)._ti_error_placeholder.render(size, focus)\n else:\n canv = UrwidImageCanvas(render, size, image._size)\n\n return canv\n\n def rows(self, size: Tuple[int], focus: bool = False) -> int:\n fit_size = self._ti_image._valid_size(size[0])\n if self._ti_sizing is Size.FIT:\n n_rows = fit_size[1]\n else:\n ori_size = self._ti_image._valid_size(Size.ORIGINAL)\n n_rows = (\n ori_size[1]\n if ori_size[0] <= fit_size[0] and ori_size[1] <= fit_size[1]\n else fit_size[1]\n )\n\n return n_rows\n\n @classmethod\n def set_error_placeholder(cls, widget: Optional[urwid.Widget]) -> None:\n \"\"\"Sets the widget to be rendered in place of an image when rendering fails.\n\n Args:\n widget: The placeholder widget or ``None`` to remove the placeholder.\n\n Raises:\n TypeError: *widget* is not an urwid widget.\n\n If set, any exception raised during rendering is **suppressed** and the\n placeholder is rendered in place of the image.\n \"\"\"\n if not isinstance(widget, urwid.Widget):\n raise arg_type_error(\"widget\", widget)\n\n cls._ti_error_placeholder = widget\n\n @staticmethod\n def _ti_get_z_index() -> int:\n if __class__._ti_free_z_indexes:\n return __class__._ti_free_z_indexes.pop()\n\n z_index = __class__._ti_next_z_index\n if z_index == 2**31:\n raise UrwidImageError(\"Too many image widgets with the kitty render style\")\n __class__._ti_next_z_index = -z_index if z_index > 0 else -z_index + 1\n\n return z_index\n\n def _ti_change_disguise(self) -> None:\n \"\"\"See :py:meth`UrwidImageCanvas._ti_change_disguise`.\"\"\"\n self._ti_disguise_state = (self._ti_disguise_state + 1) % 3", "n_imports_parsed": 10, "n_files_resolved": 6, "n_chars_extracted": 24356}, "tests/test_image/test_block.py::80": {"resolved_imports": ["src/term_image/_ctlseqs.py", "src/term_image/image/block.py", "src/term_image/image/common.py"], "used_names": ["SGR_BG_DIRECT", "SGR_DEFAULT", "set_fg_bg_colors"], "enclosing_function": "test_background_colour", "extracted_code": "# Source: src/term_image/_ctlseqs.py\nSGR_BG_DIRECT = SGR % f\"48;2;{Pm(3)}\"\n\nSGR_DEFAULT = SGR % \"\"", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 98}, "tests/renderable/test_types.py::1069": {"resolved_imports": ["src/term_image/geometry.py", "src/term_image/renderable/_renderable.py", "src/term_image/renderable/_types.py"], "used_names": ["UnknownArgsFieldError", "pytest"], "enclosing_function": "test_getattr", "extracted_code": "# Source: src/term_image/renderable/_types.py\nclass UnknownArgsFieldError(RenderArgsError, AttributeError):\n \"\"\"Raised when an attempt is made to access or modify an unknown render argument\n field.\n \"\"\"", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 211}, "tests/test_top_level.py::59": {"resolved_imports": ["src/term_image/__init__.py", "src/term_image/utils.py", "src/term_image/exceptions.py", "src/term_image/geometry.py"], "used_names": ["AutoCellRatio", "Size", "get_cell_ratio", "reset_cell_size_ratio", "set_cell_ratio", "set_cell_size"], "enclosing_function": "test_dynamic", "extracted_code": "# Source: src/term_image/__init__.py\nclass AutoCellRatio(Enum):\n \"\"\":ref:`auto-cell-ratio` enumeration and support status.\n\n .. seealso:: :py:func:`set_cell_ratio`.\n \"\"\"\n\n FIXED = auto()\n \"\"\"Fixed cell ratio.\n\n :meta hide-value:\n \"\"\"\n\n DYNAMIC = auto()\n \"\"\"Dynamic cell ratio.\n\n :meta hide-value:\n \"\"\"\n\n is_supported: ClassVar[bool | None]\n \"\"\"Auto cell ratio support status. Can be\n\n :meta hide-value:\n\n - ``None`` -> support status not yet determined\n - ``True`` -> supported\n - ``False`` -> not supported\n\n Can be explicitly set when using auto cell ratio but want to avoid the support\n check in a situation where the support status is foreknown. Can help to avoid\n being wrongly detected as unsupported on a :ref:`queried `\n terminal that doesn't respond on time.\n\n For instance, when using multiprocessing, if the support status has been\n determined in the main process, this value can simply be passed on to and set\n within the child processes.\n \"\"\"\n\ndef get_cell_ratio() -> float:\n \"\"\"Returns the global :term:`cell ratio`.\n\n .. seealso:: :py:func:`set_cell_ratio`.\n \"\"\"\n # `(1, 2)` is a fallback in case the terminal doesn't respond in time\n return _cell_ratio or truediv(*(get_cell_size() or (1, 2)))\n\ndef set_cell_ratio(ratio: float | AutoCellRatio) -> None:\n \"\"\"Sets the global :term:`cell ratio`.\n\n Args:\n ratio: Can be one of the following values.\n\n * A positive :py:class:`float` value.\n * :py:attr:`AutoCellRatio.FIXED`, the ratio is immediately determined from\n the :term:`active terminal`.\n * :py:attr:`AutoCellRatio.DYNAMIC`, the ratio is determined from the\n :term:`active terminal` whenever :py:func:`get_cell_ratio` is called,\n though with some caching involved, such that the ratio is re-determined\n only if the terminal size changes.\n\n Raises:\n ValueError: *ratio* is a non-positive :py:class:`float`.\n term_image.exceptions.TermImageError: Auto cell ratio is not supported\n in the :term:`active terminal` or on the current platform.\n\n This value is taken into consideration when setting image sizes for **text-based**\n render styles, in order to preserve the aspect ratio of images drawn to the\n terminal.\n\n NOTE:\n Changing the cell ratio does not automatically affect any image that has a\n :term:`fixed size`. For a change in cell ratio to take effect, the image's\n size has to be re-set.\n\n IMPORTANT:\n See :ref:`auto-cell-ratio` for details about the auto modes.\n \"\"\"\n global _cell_ratio\n\n if isinstance(ratio, AutoCellRatio):\n if AutoCellRatio.is_supported is None:\n AutoCellRatio.is_supported = get_cell_size() is not None\n\n if not AutoCellRatio.is_supported:\n raise TermImageError(\n \"Auto cell ratio is not supported in the active terminal or on the \"\n \"current platform\"\n )\n elif ratio is AutoCellRatio.FIXED:\n # `(1, 2)` is a fallback in case the terminal doesn't respond in time\n _cell_ratio = truediv(*(get_cell_size() or (1, 2)))\n else:\n _cell_ratio = None\n else:\n if ratio <= 0.0:\n raise arg_value_error_range(\"ratio\", ratio)\n _cell_ratio = ratio\n\n\n# Source: src/term_image/geometry.py\nclass Size(RawSize):\n \"\"\"The dimensions of a rectangular region.\n\n Raises:\n ValueError: Either dimension is non-positive.\n\n Same as :py:class:`RawSize`, except that both dimensions must be **positive**.\n\n IMPORTANT:\n In the case of multiple inheritance i.e if subclassing this class along with\n other classes, this class should appear last (i.e to the far right) in the\n base class list.\n \"\"\"\n\n __slots__ = ()\n\n def __new__(cls, width: int, height: int) -> Self:\n if width < 1:\n raise arg_value_error_range(\"width\", width)\n if height < 1:\n raise arg_value_error_range(\"height\", height)\n\n # Using `tuple` directly instead of `super()` for performance\n return tuple.__new__(cls, (width, height))", "n_imports_parsed": 6, "n_files_resolved": 4, "n_chars_extracted": 4235}, "tests/test_iterator.py::127": {"resolved_imports": ["src/term_image/_ctlseqs.py", "src/term_image/exceptions.py", "src/term_image/image/block.py", "src/term_image/image/common.py"], "used_names": ["ImageIterator"], "enclosing_function": "test_image_seek_has_no_effect", "extracted_code": "# Source: src/term_image/image/common.py\nclass ImageIterator:\n \"\"\"Efficiently iterate over :term:`rendered` frames of an :term:`animated` image\n\n Args:\n image: Animated image.\n repeat: The number of times to go over the entire image. A negative value\n implies infinite repetition.\n format_spec: The :ref:`format specifier ` for the rendered\n frames (default: auto).\n cached: Determines if the :term:`rendered` frames will be cached (for speed up\n of subsequent renders) or not. If it is\n\n * a boolean, caching is enabled if ``True``. Otherwise, caching is disabled.\n * a positive integer, caching is enabled only if the framecount of the image\n is less than or equal to the given number.\n\n Raises:\n TypeError: An argument is of an inappropriate type.\n ValueError: An argument is of an appropriate type but has an\n unexpected/invalid value.\n term_image.exceptions.StyleError: Invalid style-specific format specifier.\n\n * If *repeat* equals ``1``, caching is disabled.\n * The iterator has immediate response to changes in the image size.\n * If the image size is :term:`dynamic `, it's computed per frame.\n * The number of the last yielded frame is set as the image's seek position.\n * Directly adjusting the seek position of the image doesn't affect iteration.\n Use :py:meth:`ImageIterator.seek` instead.\n * After the iterator is exhausted, the underlying image is set to frame ``0``.\n \"\"\"\n\n def __init__(\n self,\n image: BaseImage,\n repeat: int = -1,\n format_spec: str = \"\",\n cached: Union[bool, int] = 100,\n ) -> None:\n if not isinstance(image, BaseImage):\n raise arg_type_error(\"image\", image)\n if not image._is_animated:\n raise ValueError(\"'image' is not animated\")\n\n if not isinstance(repeat, int):\n raise arg_type_error(\"repeat\", repeat)\n if not repeat:\n raise arg_value_error(\"repeat\", repeat)\n\n if not isinstance(format_spec, str):\n raise arg_type_error(\"format_spec\", format_spec)\n *fmt, alpha, style_args = image._check_format_spec(format_spec)\n\n if not isinstance(cached, int): # `bool` is a subclass of `int`\n raise arg_type_error(\"cached\", cached)\n if False is not cached <= 0:\n raise arg_value_error_range(\"cached\", cached)\n\n self._image = image\n self._repeat = repeat\n self._format = format_spec\n self._cached = repeat != 1 and (\n cached if isinstance(cached, bool) else image.n_frames <= cached\n )\n self._loop_no = None\n self._animator = image._renderer(\n self._animate, alpha, fmt, style_args, check_size=False\n )\n\n def __del__(self) -> None:\n self.close()\n\n def __iter__(self) -> ImageIterator:\n return self\n\n def __next__(self) -> str:\n try:\n return next(self._animator)\n except StopIteration:\n self.close()\n raise StopIteration(\n \"Iteration has reached the given repeat count\"\n ) from None\n except AttributeError as e:\n if str(e).endswith(\"'_animator'\"):\n raise StopIteration(\"Iterator exhausted or closed\") from None\n else:\n self.close()\n raise\n except Exception:\n self.close()\n raise\n\n def __repr__(self) -> str:\n return (\n \"{}(image={!r}, repeat={}, format_spec={!r}, cached={}, loop_no={})\".format(\n type(self).__name__,\n *self.__dict__.values(),\n )\n )\n\n loop_no = property(\n lambda self: self._loop_no,\n doc=\"\"\"Iteration repeat countdown\n\n :type: Optional[int]\n\n GET:\n Returns:\n\n * ``None``, if iteration hasn't started.\n * Otherwise, the current iteration repeat countdown value.\n\n Changes on the first iteration of each loop, except for infinite iteration\n where it's always ``-1``. When iteration has ended, the value is zero.\n \"\"\",\n )\n\n def close(self) -> None:\n \"\"\"Closes the iterator and releases resources used.\n\n Does not reset the frame number of the underlying image.\n\n NOTE:\n This method is automatically called when the iterator is exhausted or\n garbage-collected.\n \"\"\"\n try:\n self._animator.close()\n del self._animator\n self._image._close_image(self._img)\n del self._img\n except AttributeError:\n pass\n\n def seek(self, pos: int) -> None:\n \"\"\"Sets the frame number to be yielded on the next iteration without affecting\n the repeat count.\n\n Args:\n pos: Next frame number.\n\n Raises:\n TypeError: An argument is of an inappropriate type.\n ValueError: An argument is of an appropriate type but has an\n unexpected/invalid value.\n term_image.exceptions.TermImageError: Iteration has not yet started or the\n iterator is exhausted/closed.\n\n Frame numbers start from ``0`` (zero).\n \"\"\"\n if not isinstance(pos, int):\n raise arg_type_error(\"pos\", pos)\n if not 0 <= pos < self._image.n_frames:\n raise arg_value_error_range(\"pos\", pos, f\"n_frames={self._image.n_frames}\")\n\n try:\n self._animator.send(pos)\n except TypeError:\n raise TermImageError(\"Iteration has not yet started\") from None\n except AttributeError:\n raise TermImageError(\"Iterator exhausted or closed\") from None\n\n def _animate(\n self,\n img: PIL.Image.Image,\n alpha: Union[None, float, str],\n fmt: Tuple[Union[None, str, int]],\n style_args: Dict[str, Any],\n ) -> Generator[str, int, None]:\n \"\"\"Returns a generator that yields rendered and formatted frames of the\n underlying image.\n \"\"\"\n self._img = img # For cleanup\n image = self._image\n cached = self._cached\n self._loop_no = repeat = self._repeat\n if cached:\n cache = [(None,) * 2] * image.n_frames\n\n sent = None\n n = 0\n while repeat:\n if sent is None:\n image._seek_position = n\n try:\n frame = image._format_render(\n image._render_image(img, alpha, frame=True, **style_args), *fmt\n )\n except EOFError:\n image._seek_position = n = 0\n if repeat > 0: # Avoid infinitely large negative numbers\n self._loop_no = repeat = repeat - 1\n if cached:\n break\n continue\n else:\n if cached:\n cache[n] = (frame, hash(image.rendered_size))\n\n sent = yield frame\n n = n + 1 if sent is None else sent - 1\n\n if cached:\n n_frames = len(cache)\n while repeat:\n while n < n_frames:\n if sent is None:\n image._seek_position = n\n frame, size_hash = cache[n]\n if hash(image.rendered_size) != size_hash:\n frame = image._format_render(\n image._render_image(img, alpha, frame=True, **style_args),\n *fmt,\n )\n cache[n] = (frame, hash(image.rendered_size))\n\n sent = yield frame\n n = n + 1 if sent is None else sent - 1\n\n image._seek_position = n = 0\n if repeat > 0: # Avoid infinitely large negative numbers\n self._loop_no = repeat = repeat - 1\n\n # For consistency in behaviour\n if img is image._source:\n img.seek(0)", "n_imports_parsed": 7, "n_files_resolved": 4, "n_chars_extracted": 8102}, "tests/test_image/test_others.py::12": {"resolved_imports": ["src/term_image/image/common.py", "src/term_image/image/__init__.py"], "used_names": ["AutoImage", "BaseImage", "Size", "pytest", "python_image", "python_img"], "enclosing_function": "test_auto_image", "extracted_code": "# Source: src/term_image/image/common.py\nclass Size(Enum):\n \"\"\"Enumeration for :term:`automatic sizing`.\"\"\"\n\n #: Equivalent to :py:attr:`ORIGINAL` if it will fit into the\n #: :term:`frame size`, else :py:attr:`FIT`.\n #:\n #: :meta hide-value:\n AUTO = Hidden()\n\n #: The image size is set to fit optimally **within** the :term:`frame size`.\n #:\n #: :meta hide-value:\n FIT = Hidden()\n\n #: The size is set such that the width is exactly the :term:`frame width`,\n #: regardless of the :term:`cell ratio`.\n #:\n #: :meta hide-value:\n FIT_TO_WIDTH = Hidden()\n\n #: The image size is set such that the image is rendered with as many pixels as the\n #: the original image consists of.\n #:\n #: :meta hide-value:\n ORIGINAL = Hidden()\n\nclass BaseImage(metaclass=ImageMeta):\n \"\"\"Base of all render styles.\n\n Args:\n image: Source image.\n width: Can be\n\n * a positive integer; horizontal dimension of the image, in columns.\n * a :py:class:`~term_image.image.Size` enum member.\n\n height: Can be\n\n * a positive integer; vertical dimension of the image, in lines.\n * a :py:class:`~term_image.image.Size` enum member.\n\n Raises:\n TypeError: An argument is of an inappropriate type.\n ValueError: An argument is of an appropriate type but has an\n unexpected/invalid value.\n\n Propagates exceptions raised by :py:meth:`set_size`, if *width* or *height* is\n given.\n\n NOTE:\n * If neither *width* nor *height* is given (or both are ``None``),\n :py:attr:`~term_image.image.Size.FIT` applies.\n * If both width and height are not ``None``, they must be positive integers\n and :term:`manual sizing` applies i.e the image size is set as given without\n preserving aspect ratio.\n * For animated images, the seek position is initialized to the current seek\n position of the given image.\n * It's allowed to set properties for :term:`animated` images on non-animated\n ones, the values are simply ignored.\n\n ATTENTION:\n This class cannot be directly instantiated. Image instances should be created\n from its subclasses.\n \"\"\"\n\n # Data Attributes\n\n _forced_support: bool = False\n _supported: Optional[bool] = None\n _render_method: Optional[str] = None\n _render_methods: Set[str] = set()\n _style_args: Dict[\n str, Tuple[Tuple[FunctionType, str], Tuple[FunctionType, str]]\n ] = {}\n\n # Special Methods\n\n def __init__(\n self,\n image: PIL.Image.Image,\n *,\n width: Union[int, Size, None] = None,\n height: Union[int, Size, None] = None,\n ) -> None:\n \"\"\"See the class description\"\"\"\n if not isinstance(image, Image.Image):\n raise arg_type_error(\"image\", image)\n if 0 in image.size:\n raise ValueError(\"'image' is null-sized\")\n\n self._closed = False\n self._source = image\n self._source_type = ImageSource.PIL_IMAGE\n self._original_size = image.size\n if width is None is height:\n self.size = Size.FIT\n else:\n self.set_size(width, height)\n\n self._is_animated = hasattr(image, \"is_animated\") and image.is_animated\n if self._is_animated:\n self._frame_duration = (image.info.get(\"duration\") or 100) / 1000\n self._seek_position = image.tell()\n self._n_frames = None\n\n def __del__(self) -> None:\n self.close()\n\n def __enter__(self) -> BaseImage:\n return self\n\n def __exit__(self, typ: type, val: Exception, tb: TracebackType) -> bool:\n self.close()\n return False # Currently, no particular exception is suppressed\n\n def __format__(self, spec: str) -> str:\n \"\"\"Renders the image with alignment, padding and transparency control\"\"\"\n # Only the currently set frame is rendered for animated images\n h_align, width, v_align, height, alpha, style_args = self._check_format_spec(\n spec\n )\n\n return self._format_render(\n self._renderer(self._render_image, alpha, **style_args),\n h_align,\n width,\n v_align,\n height,\n )\n\n def __iter__(self) -> ImageIterator:\n return ImageIterator(self, 1, \"1.1\", False)\n\n def __repr__(self) -> str:\n return \"<{}: source_type={} size={} is_animated={}>\".format(\n type(self).__name__,\n self._source_type.name,\n (\n self._size.name\n if isinstance(self._size, Size)\n else \"x\".join(map(str, self._size))\n ),\n self._is_animated,\n )\n\n def __str__(self) -> str:\n \"\"\"Renders the image with transparency enabled and without alignment\"\"\"\n # Only the currently set frame is rendered for animated images\n return self._renderer(self._render_image, _ALPHA_THRESHOLD)\n\n # Properties\n\n closed = property(\n lambda self: self._closed,\n doc=\"\"\"Instance finalization status\n\n :type: bool\n\n GET:\n Returns ``True`` if the instance has been finalized (:py:meth:`close` has\n been called). Otherwise, ``False``.\n \"\"\",\n )\n\n forced_support = ClassProperty(\n lambda self: type(self)._forced_support,\n doc=\"\"\"Forced render style support\n\n :type: bool\n\n GET:\n Returns the forced support status of the invoking class or class of the\n invoking instance.\n\n SET:\n Forced support is enabled or disabled for the invoking class.\n\n Can not be set on an instance.\n\n If forced support is:\n\n * **enabled**, the render style is treated as if it were supported,\n regardless of the return value of :py:meth:`is_supported`.\n * **disabled**, the return value of :py:meth:`is_supported` determines if\n the render style is supported or not.\n\n By **default**, forced support is **disabled** for all render style classes.\n\n NOTE:\n * This property is :term:`descendant`.\n * This doesn't affect the return value of :py:meth:`is_supported` but\n may affect operations that require that a render style be supported e.g\n instantiation of some render style classes.\n \"\"\",\n )\n\n frame_duration = property(\n lambda self: self._frame_duration if self._is_animated else None,\n doc=\"\"\"Duration of a single frame\n\n :type: Optional[float]\n\n GET:\n Returns:\n\n * The duration of a single frame (in seconds), if the image is animated.\n * ``None``, if otherwise.\n\n SET:\n If the image is animated, The frame duration is set.\n Otherwise, nothing is done.\n \"\"\",\n )\n\n @frame_duration.setter\n def frame_duration(self, value: float) -> None:\n if not isinstance(value, float):\n raise arg_type_error(\"frame_duration\", value)\n if value <= 0.0:\n raise arg_value_error_range(\"frame_duration\", value)\n if self._is_animated:\n self._frame_duration = value\n\n height = property(\n lambda self: self._size if isinstance(self._size, Size) else self._size[1],\n lambda self, height: self.set_size(height=height),\n doc=\"\"\"\n Image height\n\n :type: Union[Size, int]\n\n GET:\n Returns:\n\n * The image height (in lines), if the image size is\n :term:`fixed `.\n * A :py:class:`~term_image.image.Size` enum member, if the image size\n is :term:`dynamic `.\n\n SET:\n If set to:\n\n * a positive :py:class:`int`; the image height is set to the given value\n and the width is set proportionally.\n * a :py:class:`~term_image.image.Size` enum member; the image size is set\n as prescibed by the enum member.\n * ``None``; equivalent to :py:attr:`~term_image.image.Size.FIT`.\n\n This results in a :term:`fixed size`.\n \"\"\",\n )\n\n is_animated = property(\n lambda self: self._is_animated,\n doc=\"\"\"\n Animatability of the image\n\n :type: bool\n\n GET:\n Returns ``True`` if the image is :term:`animated`. Otherwise, ``False``.\n \"\"\",\n )\n\n original_size = property(\n lambda self: self._original_size,\n doc=\"\"\"Size of the source (in pixels)\n\n :type: Tuple[int, int]\n\n GET:\n Returns the source size.\n \"\"\",\n )\n\n @property\n def n_frames(self) -> int:\n \"\"\"Image frame count\n\n :type: int\n\n GET:\n Returns the number of frames the image has.\n \"\"\"\n if not self._is_animated:\n return 1\n\n if not self._n_frames:\n img = self._get_image()\n try:\n self._n_frames = img.n_frames\n finally:\n self._close_image(img)\n\n return self._n_frames\n\n rendered_height = property(\n lambda self: (\n self._valid_size(None, self._size)\n if isinstance(self._size, Size)\n else self._size\n )[1],\n doc=\"\"\"\n The height with which the image is :term:`rendered`\n\n :type: int\n\n GET:\n Returns the number of lines the image will occupy when drawn in a terminal.\n \"\"\",\n )\n\n rendered_size = property(\n lambda self: (\n self._valid_size(self._size, None)\n if isinstance(self._size, Size)\n else self._size\n ),\n doc=\"\"\"\n The size with which the image is :term:`rendered`\n\n :type: Tuple[int, int]\n\n GET:\n Returns the number of columns and lines (respectively) the image will\n occupy when drawn in a terminal.\n \"\"\",\n )\n\n rendered_width = property(\n lambda self: (\n self._valid_size(self._size, None)\n if isinstance(self._size, Size)\n else self._size\n )[0],\n doc=\"\"\"\n The width with which the image is :term:`rendered`\n\n :type: int\n\n GET:\n Returns the number of columns the image will occupy when drawn in a\n terminal.\n \"\"\",\n )\n\n size = property(\n lambda self: self._size,\n doc=\"\"\"\n Image size\n\n :type: Union[Size, Tuple[int, int]]\n\n GET:\n Returns:\n\n * The image size, ``(columns, lines)``, if the image size is\n :term:`fixed `.\n * A :py:class:`~term_image.image.Size` enum member, if the image size\n is :term:`dynamic `.\n\n SET:\n If set to a:\n\n * :py:class:`~term_image.image.Size` enum member, the image size is set\n as prescibed by the given member.\n\n This results in a :term:`dynamic size` i.e the size is computed whenever\n the image is :term:`rendered` using the default :term:`frame size`.\n\n * 2-tuple of integers, ``(width, height)``, the image size set as given.\n\n This results in a :term:`fixed size` i.e the size will not change until\n it is re-set.\n \"\"\",\n )\n\n @size.setter\n def size(self, size: Size | Tuple[int, int]) -> None:\n if isinstance(size, Size):\n self._size = size\n elif isinstance(size, tuple):\n if len(size) != 2:\n raise arg_value_error(\"size\", size)\n self.set_size(*size)\n else:\n raise arg_type_error(\"size\", size)\n\n source = property(\n _close_validated(lambda self: getattr(self, self._source_type.value)),\n doc=\"\"\"\n Image :term:`source`\n\n :type: Union[PIL.Image.Image, str]\n\n GET:\n Returns the :term:`source` from which the instance was initialized.\n \"\"\",\n )\n\n source_type = property(\n lambda self: self._source_type,\n doc=\"\"\"\n Image :term:`source` type\n\n :type: ImageSource\n\n GET:\n Returns the type of :term:`source` from which the instance was initialized.\n \"\"\",\n )\n\n width = property(\n lambda self: self._size if isinstance(self._size, Size) else self._size[0],\n lambda self, width: self.set_size(width),\n doc=\"\"\"\n Image width\n\n :type: Union[Size, int]\n\n GET:\n Returns:\n\n * The image width (in columns), if the image size is\n :term:`fixed `.\n * A :py:class:`~term_image.image.Size` enum member; if the image size\n is :term:`dynamic `.\n\n SET:\n If set to:\n\n * a positive :py:class:`int`; the image width is set to the given value\n and the height is set proportionally.\n * a :py:class:`~term_image.image.Size` enum member; the image size is set\n as prescibed by the enum member.\n * ``None``; equivalent to :py:attr:`~term_image.image.Size.FIT`.\n\n This results in a :term:`fixed size`.\n \"\"\",\n )\n\n # # Private\n\n @property\n @abstractmethod\n def _pixel_ratio(self):\n \"\"\"The width-to-height ratio of a pixel drawn in the terminal\"\"\"\n raise NotImplementedError\n\n # Public Methods\n\n def close(self) -> None:\n \"\"\"Finalizes the instance and releases external resources.\n\n * In most cases, it's not necessary to explicitly call this method, as it's\n automatically called when the instance is garbage-collected.\n * This method can be safely called multiple times.\n * If the instance was initialized with a PIL image, the PIL image is never\n finalized.\n \"\"\"\n try:\n if not self._closed:\n if self._source_type is ImageSource.URL:\n try:\n os.remove(self._source)\n except FileNotFoundError:\n pass\n del self._url\n del self._source\n except AttributeError:\n pass # Instance creation or initialization was unsuccessful\n finally:\n self._closed = True\n\n def draw(\n self,\n h_align: Optional[str] = None,\n pad_width: int = 0,\n v_align: Optional[str] = None,\n pad_height: int = -2,\n alpha: Optional[float, str] = _ALPHA_THRESHOLD,\n *,\n animate: bool = True,\n repeat: int = -1,\n cached: Union[bool, int] = 100,\n scroll: bool = False,\n check_size: bool = True,\n **style: Any,\n ) -> None:\n \"\"\"Draws the image to standard output.\n\n Args:\n h_align: Horizontal alignment (\"left\" / \"<\", \"center\" / \"|\" or\n \"right\" / \">\"). Default: center.\n pad_width: Number of columns within which to align the image.\n\n * Excess columns are filled with spaces.\n * Must not be greater than the :term:`terminal width`.\n\n v_align: Vertical alignment (\"top\"/\"^\", \"middle\"/\"-\" or \"bottom\"/\"_\").\n Default: middle.\n pad_height: Number of lines within which to align the image.\n\n * Excess lines are filled with spaces.\n * Must not be greater than the :term:`terminal height`,\n **for animations**.\n\n alpha: Transparency setting.\n\n * If ``None``, transparency is disabled (alpha channel is removed).\n * If a ``float`` (**0.0 <= x < 1.0**), specifies the alpha ratio\n **above** which pixels are taken as **opaque**. **(Applies to only\n text-based render styles)**.\n * If a string, specifies a color to replace transparent background with.\n Can be:\n\n * **\"#\"** -> The terminal's default background color (or black, if\n undetermined) is used.\n * A hex color e.g ``ffffff``, ``7faa52``.\n\n animate: If ``False``, disable animation i.e draw only the current frame of\n an animated image.\n repeat: The number of times to go over all frames of an animated image.\n A negative value implies infinite repetition.\n cached: Determines if :term:`rendered` frames of an animated image will be\n cached (for speed up of subsequent renders of the same frame) or not.\n\n * If :py:class:`bool`, it directly sets if the frames will be cached or\n not.\n * If :py:class:`int`, caching is enabled only if the framecount of the\n image is less than or equal to the given number.\n\n scroll: Only applies to non-animations. If ``True``, allows the image's\n :term:`rendered height` to be greater than the :term:`terminal height`.\n check_size: If ``False``, rendered size validation is not performed for\n non-animations. Does not affect padding size validation.\n style: Style-specific render parameters. See each subclass for it's own\n usage.\n\n Raises:\n TypeError: An argument is of an inappropriate type.\n ValueError: An argument is of an appropriate type but has an\n unexpected/invalid value.\n term_image.exceptions.InvalidSizeError: The image's :term:`rendered size`\n can not fit into the :term:`terminal size`.\n term_image.exceptions.StyleError: Unrecognized style-specific render\n parameter(s).\n term_image.exceptions.RenderError: An error occurred during\n :term:`rendering`.\n\n * If *pad_width* or *pad_height* is:\n\n * positive, it is **absolute** and used as-is.\n * non-positive, it is **relative** to the corresponding terminal dimension\n (**at the point of calling this method**) and equivalent to the absolute\n dimension ``max(terminal_dimension + frame_dimension, 1)``.\n\n * :term:`padding width` is always validated.\n * *animate*, *repeat* and *cached* apply to :term:`animated` images only.\n They are simply ignored for non-animated images.\n * For animations (i.e animated images with *animate* set to ``True``):\n\n * *scroll* is ignored.\n * Image size is always validated, if set.\n * :term:`Padding height` is always validated.\n\n * Animations, **by default**, are infinitely looped and can be terminated\n with :py:data:`~signal.SIGINT` (``CTRL + C``), **without** raising\n :py:class:`KeyboardInterrupt`.\n \"\"\"\n fmt = self._check_formatting(h_align, pad_width, v_align, pad_height)\n\n if alpha is not None:\n if isinstance(alpha, float):\n if not 0.0 <= alpha < 1.0:\n raise arg_value_error_range(\"alpha\", alpha)\n elif isinstance(alpha, str):\n if not _ALPHA_BG_FORMAT.fullmatch(alpha):\n raise arg_value_error_msg(\"Invalid hex color string\", alpha)\n else:\n raise arg_type_error(\"alpha\", alpha)\n\n if self._is_animated and not isinstance(animate, bool):\n raise arg_type_error(\"animate\", animate)\n\n terminal_width, terminal_height = get_terminal_size()\n if pad_width > terminal_width:\n raise arg_value_error_range(\n \"pad_width\", pad_width, got_extra=f\"terminal_width={terminal_width}\"\n )\n\n animation = self._is_animated and animate\n\n if animation and pad_height > terminal_height:\n raise arg_value_error_range(\n \"pad_height\",\n pad_height,\n got_extra=f\"terminal_height={terminal_height}, animation={animation}\",\n )\n\n for arg in (\"scroll\", \"check_size\"):\n arg_value = locals()[arg]\n if not isinstance(arg_value, bool):\n raise arg_type_error(arg, arg_value)\n\n # Checks for *repeat* and *cached* are delegated to `ImageIterator`.\n\n def render(image: PIL.Image.Image) -> None:\n # Hide the cursor immediately if the output is a terminal device\n sys.stdout.isatty() and print(HIDE_CURSOR, end=\"\", flush=True)\n try:\n style_args = self._check_style_args(style)\n if animation:\n self._display_animated(\n image, alpha, fmt, repeat, cached, **style_args\n )\n else:\n try:\n print(\n self._format_render(\n self._render_image(image, alpha, **style_args),\n *fmt,\n ),\n end=\"\",\n flush=True,\n )\n except (KeyboardInterrupt, Exception):\n self._handle_interrupted_draw()\n raise\n finally:\n # Reset color and show the cursor\n print(SGR_DEFAULT, SHOW_CURSOR * sys.stdout.isatty(), sep=\"\")\n\n self._renderer(\n render,\n scroll=scroll,\n check_size=check_size,\n animated=animation,\n )\n\n @classmethod\n def from_file(\n cls,\n filepath: Union[str, os.PathLike],\n **kwargs: Union[None, int],\n ) -> BaseImage:\n \"\"\"Creates an instance from an image file.\n\n Args:\n filepath: Relative/Absolute path to an image file.\n kwargs: Same keyword arguments as the class constructor.\n\n Returns:\n A new instance.\n\n Raises:\n TypeError: *filepath* is of an inappropriate type.\n FileNotFoundError: The given path does not exist.\n\n Propagates exceptions raised (or propagated) by :py:func:`PIL.Image.open` and\n the class constructor.\n \"\"\"\n if not isinstance(filepath, (str, os.PathLike)):\n raise arg_type_error(\"filepath\", filepath)\n\n if isinstance(filepath, os.PathLike):\n filepath = filepath.__fspath__()\n if isinstance(filepath, bytes):\n filepath = filepath.decode()\n\n # Intentionally propagates `IsADirectoryError` since the message is OK\n try:\n img = Image.open(filepath)\n except FileNotFoundError:\n raise FileNotFoundError(f\"No such file: {filepath!r}\") from None\n except UnidentifiedImageError as e:\n e.args = (f\"Could not identify {filepath!r} as an image\",)\n raise\n\n with img:\n new = cls(img, **kwargs)\n # Absolute paths work better with symlinks, as opposed to real paths:\n # less confusing, Filename is as expected, helps in path comparisons\n new._source = os.path.abspath(filepath)\n new._source_type = ImageSource.FILE_PATH\n return new\n\n @classmethod\n def from_url(\n cls,\n url: str,\n **kwargs: Union[None, int],\n ) -> BaseImage:\n \"\"\"Creates an instance from an image URL.\n\n Args:\n url: URL of an image file.\n kwargs: Same keyword arguments as the class constructor.\n\n Returns:\n A new instance.\n\n Raises:\n TypeError: *url* is not a string.\n ValueError: The URL is invalid.\n term_image.exceptions.URLNotFoundError: The URL does not exist.\n PIL.UnidentifiedImageError: Propagated from :py:func:`PIL.Image.open`.\n\n Also propagates connection-related exceptions from :py:func:`requests.get`\n and exceptions raised or propagated by the class constructor.\n\n NOTE:\n This method creates a temporary file, but only after successful\n initialization. The file is removed:\n\n - when :py:meth:`close` is called,\n - upon exiting a ``with`` statement block that uses the instance as a\n context manager, or\n - when the instance is garbage collected.\n \"\"\"\n if not isinstance(url, str):\n raise arg_type_error(\"url\", url)\n if not all(urlparse(url)[:3]):\n raise arg_value_error_msg(\"Invalid URL\", url)\n\n # Propagates connection-related errors.\n response = requests.get(url, stream=True)\n if response.status_code == 404:\n raise URLNotFoundError(f\"URL {url!r} does not exist.\")\n\n # Ensure initialization is successful before writing to file\n try:\n new = cls(Image.open(io.BytesIO(response.content)), **kwargs)\n except UnidentifiedImageError as e:\n e.args = (f\"The URL {url!r} doesn't link to an identifiable image\",)\n raise\n\n fd, filepath = mkstemp(\"-\" + os.path.basename(url), dir=_TEMP_DIR)\n os.write(fd, response.content)\n os.close(fd)\n\n new._source = filepath\n new._source_type = ImageSource.URL\n new._url = url\n return new\n\n @classmethod\n @abstractmethod\n def is_supported(cls) -> bool:\n \"\"\"Checks if the implemented :term:`render style` is supported by the\n :term:`active terminal`.\n\n Returns:\n ``True`` if the render style implemented by the invoking class is supported\n by the :term:`active terminal`. Otherwise, ``False``.\n\n ATTENTION:\n Support checks for most (if not all) render styles require :ref:`querying\n ` the :term:`active terminal` the **first time** they're\n executed.\n\n Hence, it's advisable to perform all necessary support checks (call\n this method on required style classes) at an early stage of a program,\n before user input is expected. If using automatic style selection,\n calling :py:func:`~term_image.image.auto_image_class` only should be\n sufficient.\n \"\"\"\n raise NotImplementedError\n\n def seek(self, pos: int) -> None:\n \"\"\"Changes current image frame.\n\n Args:\n pos: New frame number.\n\n Raises:\n TypeError: An argument is of an inappropriate type.\n ValueError: An argument is of an appropriate type but has an\n unexpected/invalid value.\n\n Frame numbers start from 0 (zero).\n \"\"\"\n if not isinstance(pos, int):\n raise arg_type_error(\"pos\", pos)\n if not 0 <= pos < self.n_frames:\n raise arg_value_error_range(\"pos\", pos, f\"n_frames={self.n_frames}\")\n if self._is_animated:\n self._seek_position = pos\n\n @ClassInstanceMethod\n def set_render_method(cls, method: Optional[str] = None) -> None:\n \"\"\"Sets the :term:`render method` used by instances of a :term:`render style`\n class that implements multiple render methods.\n\n Args:\n method: The render method to be set or ``None`` for a reset\n (case-insensitive).\n\n Raises:\n TypeError: An argument is of an inappropriate type.\n ValueError: An argument is of an appropriate type but has an\n unexpected/invalid value.\n\n See the **Render Methods** section in the description of subclasses that\n implement such for their specific usage.\n\n If *method* is not ``None`` and this method is called via:\n\n - a class, the class-wide render method is set.\n - an instance, the instance-specific render method is set.\n\n If *method* is ``None`` and this method is called via:\n\n - a class, the class-wide render method is unset, so that it uses that of\n its parent style class (if any) or the default.\n - an instance, the instance-specific render method is unset, so that it\n uses the class-wide render method thenceforth.\n\n Any instance without a render method set uses the class-wide render method.\n\n NOTE:\n *method* = ``None`` is always allowed, even if the render style doesn't\n implement multiple render methods.\n\n The **class-wide** render method is :term:`descendant`.\n \"\"\"\n if method is not None and not isinstance(method, str):\n raise arg_type_error(\"method\", method)\n if method is not None and method.lower() not in cls._render_methods:\n raise ValueError(f\"Unknown render method {method!r} for {cls.__name__}\")\n\n if not method:\n if cls._render_methods:\n cls._render_method = cls._default_render_method\n else:\n cls._render_method = method\n\n @set_render_method.instancemethod\n def set_render_method(self, method: Optional[str] = None) -> None:\n if method is not None and not isinstance(method, str):\n raise arg_type_error(\"method\", method)\n if method is not None and method.lower() not in type(self)._render_methods:\n raise ValueError(\n f\"Unknown render method {method!r} for {type(self).__name__}\"\n )\n\n if not method:\n try:\n del self._render_method\n except AttributeError:\n pass\n else:\n self._render_method = method\n\n def set_size(\n self,\n width: Union[int, Size, None] = None,\n height: Union[int, Size, None] = None,\n frame_size: Tuple[int, int] = (0, -2),\n ) -> None:\n \"\"\"Sets the image size (with extended control).\n\n Args:\n width: Can be\n\n * a positive integer; horizontal dimension of the image, in columns.\n * a :py:class:`~term_image.image.Size` enum member.\n\n height: Can be\n\n * a positive integer; vertical dimension of the image, in lines.\n * a :py:class:`~term_image.image.Size` enum member.\n\n frame_size: :term:`Frame size`, ``(columns, lines)``.\n If *columns* or *lines* is\n\n * positive, it is **absolute** and used as-is.\n * non-positive, it is **relative** to the corresponding terminal dimension\n and equivalent to the absolute dimension\n ``max(terminal_dimension + frame_dimension, 1)``.\n\n This is used only when neither *width* nor *height* is an ``int``.\n\n Raises:\n TypeError: An argument is of an inappropriate type.\n ValueError: An argument is of an appropriate type but has an\n unexpected/invalid value.\n\n * If both width and height are not ``None``, they must be positive integers\n and :term:`manual sizing` applies i.e the image size is set as given without\n preserving aspect ratio.\n * If *width* or *height* is a :py:class:`~term_image.image.Size` enum\n member, :term:`automatic sizing` applies as prescribed by the enum member.\n * If neither *width* nor *height* is given (or both are ``None``),\n :py:attr:`~term_image.image.Size.FIT` applies.\n \"\"\"\n width_height = (width, height)\n for arg_name, arg_value in zip((\"width\", \"height\"), width_height):\n if not (arg_value is None or isinstance(arg_value, (Size, int))):\n raise arg_type_error(arg_name, arg_value)\n if isinstance(arg_value, int) and arg_value <= 0:\n raise arg_value_error_range(arg_name, arg_value)\n\n if width is not None is not height:\n if not all(isinstance(x, int) for x in width_height):\n width_type = type(width).__name__\n height_type = type(height).__name__\n raise TypeError(\n \"Both 'width' and 'height' are specified but are not both integers \"\n f\"(got: ({width_type}, {height_type}))\"\n )\n\n self._size = width_height\n return\n\n if not (\n isinstance(frame_size, tuple)\n and all(isinstance(x, int) for x in frame_size)\n ):\n raise arg_type_error(\"frame_size\", frame_size)\n if not len(frame_size) == 2:\n raise arg_value_error(\"frame_size\", frame_size)\n\n self._size = self._valid_size(width, height, frame_size)\n\n def tell(self) -> int:\n \"\"\"Returns the current image frame number.\n\n :rtype: int\n \"\"\"\n return self._seek_position if self._is_animated else 0\n\n # Private Methods\n\n @classmethod\n def _check_format_spec(cls, spec: str) -> Tuple[\n str | None,\n int,\n str | None,\n int,\n Union[None, float, str],\n Dict[str, Any],\n ]:\n \"\"\"Validates a format specifier and translates it into the required values.\n\n Returns:\n A tuple ``(h_align, width, v_align, height, alpha, style_args)`` containing\n values as required by ``_format_render()`` and ``_render_image()``.\n \"\"\"\n match_ = _FORMAT_SPEC.fullmatch(spec)\n if not match_ or _NO_VERTICAL_SPEC.fullmatch(spec):\n raise arg_value_error_msg(\"Invalid format specifier\", spec)\n\n (\n _,\n h_align,\n width,\n _,\n v_align,\n height,\n alpha,\n threshold_or_bg,\n _,\n style_spec,\n ) = match_.groups()\n\n return (\n *cls._check_formatting(\n h_align,\n int(width) if width else 0,\n v_align,\n int(height) if height else -2,\n ),\n (\n threshold_or_bg\n and (\n \"#\" + threshold_or_bg.lstrip(\"#\")\n if _ALPHA_BG_FORMAT.fullmatch(\"#\" + threshold_or_bg.lstrip(\"#\"))\n else float(threshold_or_bg)\n )\n if alpha\n else _ALPHA_THRESHOLD\n ),\n style_spec and cls._check_style_format_spec(style_spec, style_spec) or {},\n )\n\n @staticmethod\n def _check_formatting(\n h_align: str | None = None,\n width: int = 0,\n v_align: str | None = None,\n height: int = -2,\n ) -> Tuple[str | None, int, str | None, int]:\n \"\"\"Validates and transforms formatting arguments.\n\n Returns:\n The respective arguments appropriate for ``_format_render()``.\n \"\"\"\n if not isinstance(h_align, (type(None), str)):\n raise arg_type_error(\"h_align\", h_align)\n if None is not h_align not in set(\"<|>\"):\n align = {\"left\": \"<\", \"center\": \"|\", \"right\": \">\"}.get(h_align)\n if not align:\n raise arg_value_error(\"h_align\", h_align)\n h_align = align\n\n if not isinstance(v_align, (type(None), str)):\n raise arg_type_error(\"v_align\", v_align)\n if None is not v_align not in set(\"^-_\"):\n align = {\"top\": \"^\", \"middle\": \"-\", \"bottom\": \"_\"}.get(v_align)\n if not align:\n raise arg_value_error(\"v_align\", v_align)\n v_align = align\n\n terminal_size = get_terminal_size()\n\n if not isinstance(width, int):\n raise arg_type_error(\"pad_width\", width)\n width = width if width > 0 else max(terminal_size.columns + width, 1)\n\n if not isinstance(height, int):\n raise arg_type_error(\"pad_height\", height)\n height = height if height > 0 else max(terminal_size.lines + height, 1)\n\n return h_align, width, v_align, height\n\n @classmethod\n def _check_style_args(cls, style_args: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"Validates style-specific arguments and translates them into the required\n values.\n\n Removes any argument having a value equal to the default.\n\n Returns:\n A mapping of keyword arguments.\n\n Raises:\n TypeError: An argument is of an inappropriate type.\n ValueError: An argument is of an appropriate type but has an\n unexpected/invalid value.\n term_image.exceptions.StyleError: An unknown style-specific parameter is\n given.\n \"\"\"\n for name, value in tuple(style_args.items()):\n try:\n (\n default,\n (check_type, type_msg),\n (check_value, value_msg),\n ) = cls._style_args[name]\n except KeyError:\n for other_cls in cls.__mro__:\n # less costly than membership tests on every class' __bases__\n if other_cls is __class__:\n raise StyleError(\n f\"Unknown style-specific render parameter {name!r} for \"\n f\"{cls.__name__!r}\"\n )\n\n if not issubclass(\n other_cls, __class__\n ) or \"_style_args\" not in vars(other_cls):\n continue\n\n try:\n (check_type, type_msg), (check_value, value_msg) = super(\n other_cls, cls\n )._style_args[name]\n break\n except KeyError:\n pass\n else:\n raise StyleError(\n f\"Unknown style-specific render parameter {name!r} for \"\n f\"{cls.__name__!r}\"\n )\n\n if not check_type(value):\n raise TypeError(f\"{type_msg} (got: {type(value).__name__})\")\n if not check_value(value):\n raise ValueError(f\"{value_msg} (got: {value!r})\")\n\n # Must not occur before type and value checks to avoid falling prey of\n # operator overloading\n if value == default:\n del style_args[name]\n\n return style_args\n\n @classmethod\n def _check_style_format_spec(cls, spec: str, original: str) -> Dict[str, Any]:\n \"\"\"Validates a style-specific format specifier and translates it into\n the required values.\n\n Returns:\n A mapping of keyword arguments.\n\n Raises:\n term_image.exceptions.StyleError: Invalid style-specific format specifier.\n\n **Every style-specific format spec should be handled as follows:**\n\n Every overriding method should call the overridden method (more on this below).\n At every step in the call chain, the specifier should be of the form::\n\n [parent] [current] [invalid]\n\n where:\n\n - *parent* is the portion to be interpreted at an higher level in the chain\n - *current* is the portion to be interpreted at the current level in the chain\n - the *invalid* portion determines the validity of the format spec\n\n Handle the portions in the order *invalid*, *parent*, *current*, so that\n validity can be determined before any further processing.\n\n At any point in the chain where the *invalid* portion exists (i.e is non-empty),\n the format spec can be correctly taken to be invalid.\n\n An overriding method must call the overridden method with the *parent* portion\n and the original format spec, **if** *parent* **is not empty**, such that every\n successful check ends up at `BaseImage._check_style_args()` or when *parent* is\n empty.\n\n :py:meth:`_get_style_format_spec` may be used to parse the format spec at each\n level of the call chain.\n \"\"\"\n if spec:\n raise StyleError(\n f\"Invalid style-specific format specifier {original!r} \"\n f\"for {cls.__name__!r}\"\n + (f\", detected at {spec!r}\" if spec != original else \"\")\n )\n return {}\n\n @classmethod\n def _clear_frame(cls) -> bool:\n \"\"\"Clears an animation frame on-screen.\n\n Called by :py:meth:`_display_animated` just before drawing a new frame.\n\n | Only required by styles wherein an image is not overwritten by another image\n e.g some graphics-based styles.\n | The base implementation does nothing and should be overridden only if\n required.\n\n Returns:\n ``True`` if the frame was cleared. Otherwise, ``False``.\n \"\"\"\n return False\n\n def _close_image(self, img: PIL.Image.Image) -> None:\n \"\"\"Closes the given PIL image instance if it isn't the instance' source.\"\"\"\n if img is not self._source:\n img.close()\n\n def _display_animated(\n self,\n img: PIL.Image.Image,\n alpha: Union[None, float, str],\n fmt: Tuple[str | None, int, str | None, int],\n repeat: int,\n cached: Union[bool, int],\n **style_args: Any,\n ) -> None:\n \"\"\"Displays an animated GIF image in the terminal.\"\"\"\n lines = max(fmt[-1], self.rendered_height)\n prev_seek_pos = self._seek_position\n duration = self._frame_duration\n image_it = ImageIterator(self, repeat, \"\", cached)\n image_it._animator = image_it._animate(img, alpha, fmt, style_args)\n cursor_up = CURSOR_UP % (lines - 1)\n cursor_down = CURSOR_DOWN % lines\n\n try:\n print(next(image_it._animator), end=\"\", flush=True) # First frame\n\n # Render next frame during current frame's duration\n start = time.time()\n for frame in image_it._animator: # Renders next frame\n # Left-over of current frame's duration\n time.sleep(max(0, duration - (time.time() - start)))\n\n # Clear the current frame, if necessary,\n # move cursor up to the beginning of the first line of the image\n # and print the new current frame.\n self._clear_frame()\n print(\"\\r\", cursor_up, frame, sep=\"\", end=\"\", flush=True)\n\n # Render next frame during current frame's duration\n start = time.time()\n except KeyboardInterrupt:\n self._handle_interrupted_draw()\n except Exception:\n self._handle_interrupted_draw()\n raise\n finally:\n image_it.close()\n self._close_image(img)\n self._seek_position = prev_seek_pos\n # Move the cursor to the last line of the image to prevent \"overlaid\"\n # output in the terminal\n print(cursor_down, end=\"\")\n\n def _format_render(\n self,\n render: str,\n h_align: str | None,\n width: int,\n v_align: str | None,\n height: int,\n ) -> str:\n \"\"\"Pads and aligns a primary :term:`render` output.\n\n NOTE:\n * All arguments should be passed through ``_check_formatting()`` first.\n * Only **absolute** padding dimensions are expected.\n \"\"\"\n cols, lines = self.rendered_size\n\n if width > cols:\n if h_align == \"<\": # left\n left = \"\"\n right = \" \" * (width - cols)\n elif h_align == \">\": # right\n left = \" \" * (width - cols)\n right = \"\"\n else: # center\n left = \" \" * ((width - cols) // 2)\n right = \" \" * (width - cols - len(left))\n render = render.replace(\"\\n\", f\"{right}\\n{left}\")\n else:\n left = right = \"\"\n\n if height > lines:\n if v_align == \"^\": # top\n top = 0\n bottom = height - lines\n elif v_align == \"_\": # bottom\n top = height - lines\n bottom = 0\n else: # middle\n top = (height - lines) // 2\n bottom = height - lines - top\n top = f\"{' ' * width}\\n\" * top\n bottom = f\"\\n{' ' * width}\" * bottom\n else:\n top = bottom = \"\"\n\n return (\n \"\".join((top, left, render, right, bottom))\n if width > cols or height > lines\n else render\n )\n\n @_close_validated\n def _get_image(self) -> PIL.Image.Image:\n \"\"\"Returns the PIL image instance corresponding to the image source as-is\"\"\"\n return (\n Image.open(self._source) if isinstance(self._source, str) else self._source\n )\n\n def _get_render_data(\n self,\n img: PIL.Image.Image,\n alpha: Union[None, float, str],\n *,\n size: Optional[Tuple[int, int]] = None,\n pixel_data: bool = True,\n round_alpha: bool = False,\n frame: bool = False,\n ) -> Tuple[\n PIL.Image.Image, Optional[List[Tuple[int, int, int]]], Optional[List[int]]\n ]:\n \"\"\"Returns the PIL image instance and pixel data required to render an image.\n\n Args:\n size: If given (in pixels), it is used instead of the pixel-equivalent of\n the image size.\n pixel_data: If ``False``, ``None`` is returned for all pixel data.\n round_alpha: Only applies when *alpha* is a ``float``.\n\n If ``True``, returned alpha values are bi-level (``0`` or ``255``), based\n on the given alpha threshold.\n Also, the image is blended with the active terminal's BG color (or black,\n if undetermined) while leaving the alpha intact.\n\n frame: If ``True``, implies *img* is being used by :py:class`ImageIterator`,\n hence, *img* is not closed.\n\n The returned image is appropriately converted, resized and composited\n (if need be).\n\n The pixel data are the last two items of the returned tuple ``(rgb, a)``, where:\n * ``rgb`` is a list of ``(r, g, b)`` tuples containing the colour channels of\n the image's pixels in a flattened row-major order where ``r``, ``g``, ``b``\n are integers in the range [0, 255].\n * ``a`` is a list of integers in the range [0, 255] representing the alpha\n channel of the image's pixels in a flattened row-major order.\n \"\"\"\n\n def convert_resize_img(mode: str):\n nonlocal img\n\n if img.mode != mode:\n prev_img = img\n try:\n img = img.convert(mode)\n # Possible for images in some modes e.g \"La\"\n except Exception as e:\n raise RenderError(\"Unable to convert image\") from e\n finally:\n if frame_img is not prev_img:\n self._close_image(prev_img)\n\n if img.size != size:\n prev_img = img\n try:\n img = img.resize(size, Image.Resampling.BOX)\n # Highly unlikely since render size can never be zero\n except Exception as e:\n raise RenderError(\"Unable to resize image\") from e\n finally:\n if frame_img is not prev_img:\n self._close_image(prev_img)\n\n frame_img = img if frame else None\n if self._is_animated:\n img.seek(self._seek_position)\n if not size:\n size = self._get_render_size()\n\n if alpha is None or img.mode in {\"1\", \"L\", \"RGB\", \"HSV\", \"CMYK\"}:\n convert_resize_img(\"RGB\")\n if pixel_data:\n rgb = list(img.getdata())\n a = [255] * mul(*size)\n else:\n convert_resize_img(\"RGBA\")\n if isinstance(alpha, str):\n if alpha == \"#\":\n alpha = get_fg_bg_colors(hex=True)[1] or \"#000000\"\n bg = Image.new(\"RGBA\", img.size, alpha)\n bg.alpha_composite(img)\n if frame_img is not img:\n self._close_image(img)\n img = bg.convert(\"RGB\")\n if pixel_data:\n a = [255] * mul(*size)\n else:\n if pixel_data:\n a = list(img.getdata(3))\n if round_alpha:\n alpha = round(alpha * 255)\n a = [0 if val < alpha else 255 for val in a]\n if round_alpha:\n bg = Image.new(\n \"RGBA\", img.size, get_fg_bg_colors(hex=True)[1] or \"#000000\"\n )\n bg.alpha_composite(img)\n bg.putalpha(img.getchannel(\"A\"))\n if frame_img is not img:\n self._close_image(img)\n img = bg\n\n if pixel_data:\n rgb = list((img if img.mode == \"RGB\" else img.convert(\"RGB\")).getdata())\n\n return (img, *(pixel_data and (rgb, a) or (None, None)))\n\n @abstractmethod\n def _get_render_size(self) -> Tuple[int, int]:\n \"\"\"Returns the size (in pixels) required to render the image.\"\"\"\n raise NotImplementedError\n\n @classmethod\n def _get_style_format_spec(\n cls, spec: str, original: str\n ) -> Tuple[str, List[Union[None, str, Tuple[Optional[str]]]]]:\n \"\"\"Parses a style-specific format specifier.\n\n See :py:meth:`_check_format_spec`.\n\n Returns:\n The *parent* portion and a list of matches for the respective fields of the\n *current* portion of the spec.\n\n * Any absent field of *current* is ``None``.\n * For a field containing groups, the match, if present, is a tuple\n containing the full match followed by the matches for each group.\n * All matches are in the same order as the fields (including their groups).\n\n Raises:\n term_image.exceptions.StyleError: The *invalid* portion exists.\n\n NOTE:\n Please avoid common fields in the format specs of parent and child classes\n (i.e fields that can match the same portion of a given string) as they\n result in ambiguities.\n \"\"\"\n patterns = iter(cls._FORMAT_SPEC)\n fields = []\n for pattern in patterns:\n match = pattern.search(spec)\n if match:\n fields.append(\n (match.group(), *match.groups())\n if pattern.groups\n else match.group()\n )\n start = match.start()\n end = match.end()\n break\n else:\n fields.append(\n (None,) * (pattern.groups + 1) if pattern.groups else None\n )\n else:\n start = end = len(spec)\n\n for pattern in patterns:\n match = pattern.match(spec, pos=end)\n if match:\n fields.append(\n (match.group(), *match.groups())\n if pattern.groups\n else match.group()\n )\n end = match.end()\n else:\n fields.append(\n (None,) * (pattern.groups + 1) if pattern.groups else None\n )\n\n parent, invalid = spec[:start], spec[end:]\n if invalid:\n raise StyleError(\n f\"Invalid style-specific format specifier {original!r} \"\n f\"for {cls.__name__!r}, detected at {invalid!r}\"\n )\n\n return parent, fields\n\n @staticmethod\n def _handle_interrupted_draw():\n \"\"\"Performs any necessary actions when image drawing is interrupted.\"\"\"\n\n @staticmethod\n @abstractmethod\n def _pixels_cols(\n *, pixels: Optional[int] = None, cols: Optional[int] = None\n ) -> int:\n \"\"\"Returns the number of pixels represented by a given number of columns\n or vice-versa.\n \"\"\"\n raise NotImplementedError\n\n @staticmethod\n @abstractmethod\n def _pixels_lines(\n *, pixels: Optional[int] = None, lines: Optional[int] = None\n ) -> int:\n \"\"\"Returns the number of pixels represented by a given number of lines\n or vice-versa.\n \"\"\"\n raise NotImplementedError\n\n @abstractmethod\n def _render_image(\n self,\n img: PIL.Image.Image,\n alpha: Union[None, float, str],\n *,\n frame: bool = False, # For `ImageIterator`\n ) -> str:\n \"\"\"Converts an image into a string which reproduces the image when printed\n to the terminal.\n\n NOTE:\n This method is not meant to be used directly, use it via `_renderer()`\n instead.\n \"\"\"\n raise NotImplementedError\n\n def _renderer(\n self,\n renderer: FunctionType,\n *args: Any,\n scroll: bool = False,\n check_size: bool = False,\n animated: bool = False,\n **kwargs,\n ) -> Any:\n \"\"\"Performs common render preparations and a rendering operation.\n\n Args:\n renderer: The function to perform the specific rendering operation for the\n caller of this method, ``_renderer()``.\n\n This function must accept at least one positional argument, the\n :py:class:`PIL.Image.Image` instance corresponding to the source.\n\n args: Positional arguments to pass on to *renderer*, after the\n :py:class:`PIL.Image.Image` instance.\n scroll: See *scroll* in :py:meth:`draw`.\n check_size: See *check_size* in :py:meth:`draw`.\n animated: If ``True``, *scroll* and *check_size* are ignored and the size\n is validated.\n kwargs: Keyword arguments to pass on to *renderer*.\n\n Returns:\n The return value of *renderer*.\n\n Raises:\n term_image.exceptions.InvalidSizeError: *check_size* or *animated* is\n ``True`` and the image's :term:`rendered size` can not fit into the\n :term:`terminal size`.\n term_image.exceptions.TermImageError: The image has been finalized.\n \"\"\"\n _size = self._size\n try:\n if isinstance(_size, Size):\n self.set_size(_size)\n elif check_size or animated:\n terminal_size = get_terminal_size()\n if any(\n map(\n gt,\n # The compared height will be 0 if *scroll* is `True`.\n # So, the height comparison will always be `False`\n # since the terminal height should never be < 0.\n map(mul, self.rendered_size, (1, not scroll)),\n terminal_size,\n )\n ):\n raise InvalidSizeError(\n \"The \"\n + (\"animation\" if animated else \"image\")\n + \" cannot fit into the terminal size\"\n )\n\n # Reaching here means it's either valid or *scroll* is `True`.\n if animated and self.rendered_height > terminal_size.lines:\n raise InvalidSizeError(\n \"The rendered height is greater than the terminal height for \"\n \"an animation\"\n )\n\n return renderer(self._get_image(), *args, **kwargs)\n\n finally:\n if isinstance(_size, Size):\n self.size = _size\n\n def _valid_size(\n self,\n width: Union[int, Size, None] = None,\n height: Union[int, Size, None] = None,\n frame_size: Tuple[int, int] = (0, -2),\n ) -> Tuple[int, int]:\n \"\"\"Returns an image size tuple.\n\n See :py:meth:`set_size` for the description of the parameters.\n \"\"\"\n ori_width, ori_height = self._original_size\n columns, lines = map(\n lambda frame_dim, terminal_dim: (\n frame_dim if frame_dim > 0 else max(terminal_dim + frame_dim, 1)\n ),\n frame_size,\n get_terminal_size(),\n )\n frame_width = self._pixels_cols(cols=columns)\n frame_height = self._pixels_lines(lines=lines)\n\n # As for cell ratio...\n #\n # Take for example, pixel ratio = 2.0\n # (i.e cell ratio = 1.0; square character cells).\n # To adjust the image to the proper scale, we either reduce the\n # width (i.e divide by 2.0) or increase the height (i.e multiply by 2.0).\n #\n # On the other hand, if the pixel ratio = 0.5\n # (i.e cell ratio = 0.25; vertically oblong character cells).\n # To adjust the image to the proper scale, we either increase the width\n # (i.e divide by the 0.5) or reduce the height (i.e multiply by the 0.5).\n #\n # Therefore, for the height, we always multiply by the pixel ratio\n # and for the width, we always divide by the pixel ratio.\n # The non-constraining axis is always the one directly adjusted.\n\n if all(not isinstance(x, int) for x in (width, height)):\n if Size.AUTO in (width, height):\n width = height = (\n Size.FIT\n if (\n ori_width > frame_width\n or round(ori_height * self._pixel_ratio) > frame_height\n )\n else Size.ORIGINAL\n )\n elif Size.FIT_TO_WIDTH in (width, height):\n return (\n self._pixels_cols(pixels=frame_width) or 1,\n self._pixels_lines(\n pixels=round(\n self._width_height_px(w=frame_width) * self._pixel_ratio\n )\n )\n or 1,\n )\n\n if Size.ORIGINAL in (width, height):\n return (\n self._pixels_cols(pixels=ori_width) or 1,\n self._pixels_lines(pixels=round(ori_height * self._pixel_ratio))\n or 1,\n )\n\n # The smaller fraction will fit on both axis.\n # Hence, the axis with the smaller ratio is the constraining axis.\n # Constraining by the axis with the larger ratio will cause the image\n # to not fit into the axis with the smaller ratio.\n width_ratio = frame_width / ori_width\n height_ratio = frame_height / ori_height\n smaller_ratio = min(width_ratio, height_ratio)\n\n # Set the dimension on the constraining axis to exactly its corresponding\n # frame dimension and the dimension on the other axis to the same ratio of\n # its corresponding original image dimension\n _width_px = ori_width * smaller_ratio\n _height_px = ori_height * smaller_ratio\n\n # The cell ratio should directly affect the non-constraining axis since the\n # constraining axis is already fully occupied at this point\n if height_ratio > width_ratio:\n _height_px = _height_px * self._pixel_ratio\n # If height becomes greater than the max, reduce it to the max\n height_px = min(_height_px, frame_height)\n # Calculate the corresponding width\n width_px = round((height_px / _height_px) * _width_px)\n # Round the height\n height_px = round(height_px)\n else:\n _width_px = _width_px / self._pixel_ratio\n # If width becomes greater than the max, reduce it to the max\n width_px = min(_width_px, frame_width)\n # Calculate the corresponding height\n height_px = round((width_px / _width_px) * _height_px)\n # Round the width\n width_px = round(width_px)\n return (\n self._pixels_cols(pixels=width_px) or 1,\n self._pixels_lines(pixels=height_px) or 1,\n )\n elif width is None:\n width_px = round(\n self._width_height_px(h=self._pixels_lines(lines=height))\n / self._pixel_ratio\n )\n width = self._pixels_cols(pixels=width_px)\n elif height is None:\n height_px = round(\n self._width_height_px(w=self._pixels_cols(cols=width))\n * self._pixel_ratio\n )\n height = self._pixels_lines(pixels=height_px)\n\n return (width or 1, height or 1)\n\n def _width_height_px(\n self, *, w: Optional[int] = None, h: Optional[int] = None\n ) -> float:\n \"\"\"Converts the given width (in pixels) to the **unrounded** proportional height\n (in pixels) OR vice-versa.\n \"\"\"\n ori_width, ori_height = self._original_size\n return (\n (w / ori_width) * ori_height\n if w is not None\n else (h / ori_height) * ori_width\n )\n\n\n# Source: src/term_image/image/__init__.py\ndef AutoImage(\n image: PIL.Image.Image,\n *,\n width: Optional[int] = None,\n height: Optional[int] = None,\n) -> BaseImage:\n \"\"\"Creates an image instance from a PIL image instance.\n\n Returns:\n An instance of the automatically selected image render style (as returned by\n :py:func:`auto_image_class`).\n\n Same arguments and raised exceptions as the :py:class:`BaseImage` class constructor.\n \"\"\"\n return auto_image_class()(image, width=width, height=height)", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 61583}, "tests/test_padding.py::236": {"resolved_imports": ["src/term_image/_ctlseqs.py", "src/term_image/geometry.py", "src/term_image/padding.py"], "used_names": ["AlignedPadding", "pytest"], "enclosing_function": "test_absolute", "extracted_code": "# Source: src/term_image/padding.py\nclass AlignedPadding(Padding):\n \"\"\"Aligned :term:`render output` padding.\n\n Args:\n width: Minimum :term:`render width`.\n height: Minimum :term:`render height`.\n h_align: Horizontal alignment.\n v_align: Vertical alignment.\n\n If *width* or *height* is:\n\n * positive, it is **absolute** and used as-is.\n * non-positive, it is **relative** to the corresponding terminal dimension\n (**at the point of resolution**) and equivalent to the absolute dimension\n ``max(terminal_dimension + relative_dimension, 1)``.\n\n The *padded render dimension* (i.e the dimension of a :term:`render output` after\n it's padded) on each axis is given by::\n\n padded_dimension = max(render_dimension, absolute_minimum_dimension)\n\n In words... If the **absolute** *minimum render dimension* on an axis is less than\n or equal to the corresponding *render dimension*, there is no padding on that axis\n and the *padded render dimension* on that axis is equal to the *render dimension*.\n Otherwise, the render output will be padded along that axis and the *padded render\n dimension* on that axis is equal to the *minimum render dimension*.\n\n The amount of padding to each side depends on the alignment, defined by *h_align*\n and *v_align*.\n\n IMPORTANT:\n :py:class:`RelativePaddingDimensionError` is raised if any padding-related\n computation/operation (basically, calling any method other than\n :py:meth:`resolve`) is performed on an instance with **relative** *minimum\n render dimension(s)* i.e if :py:attr:`relative` is ``True``.\n\n NOTE:\n Any interface receiving an instance with **relative** dimension(s) should\n typically resolve it/them upon reception.\n\n TIP:\n * Instances are immutable and hashable.\n * Instances with equal fields compare equal.\n \"\"\"\n\n # Class Attributes =========================================================\n\n __slots__ = (\"width\", \"height\", \"h_align\", \"v_align\", \"relative\")\n\n # Instance Attributes ======================================================\n\n width: int\n \"\"\"Minimum :term:`render width`\"\"\"\n\n height: int\n \"\"\"Minimum :term:`render height`\"\"\"\n\n h_align: HAlign\n \"\"\"Horizontal alignment\"\"\"\n\n v_align: VAlign\n \"\"\"Vertical alignment\"\"\"\n\n fill: str\n\n relative: bool\n \"\"\"``True`` if either or both *minimum render dimension(s)* is/are relative i.e\n non-positive. Otherwise, ``False``.\n \"\"\"\n\n # Special Methods ==========================================================\n\n def __init__(\n self,\n width: int,\n height: int,\n h_align: HAlign = HAlign.CENTER,\n v_align: VAlign = VAlign.MIDDLE,\n fill: str = \" \",\n ):\n super().__init__(fill)\n\n _setattr = super().__setattr__\n _setattr(\"width\", width)\n _setattr(\"height\", height)\n _setattr(\"h_align\", h_align)\n _setattr(\"v_align\", v_align)\n _setattr(\"relative\", not width > 0 < height)\n\n def __repr__(self) -> str:\n return \"{}(width={}, height={}, h_align={}, v_align={}, fill={!r})\".format(\n type(self).__name__,\n self.width,\n self.height,\n self.h_align.name,\n self.v_align.name,\n self.fill,\n )\n\n # Properties ===============================================================\n\n @property\n def size(self) -> RawSize:\n \"\"\"Minimum :term:`render size`\n\n GET:\n Returns the *minimum render dimensions*.\n \"\"\"\n return _RawSize(self.width, self.height)\n\n # Public Methods ===========================================================\n\n @override\n def get_padded_size(self, render_size: Size) -> Size:\n \"\"\"Computes an expected padded :term:`render size`.\n\n See :py:meth:`Padding.get_padded_size`.\n\n Raises:\n RelativePaddingDimensionError: Relative *minimum render dimension(s)*.\n \"\"\"\n if self.relative:\n raise RelativePaddingDimensionError(\"Relative minimum render dimension(s)\")\n\n return _Size(max(self.width, render_size[0]), max(self.height, render_size[1]))\n\n def resolve(self, terminal_size: os.terminal_size) -> AlignedPadding:\n \"\"\"Resolves **relative** *minimum render dimensions*.\n\n Args:\n terminal_size: The terminal size against which to resolve relative\n dimensions.\n\n Returns:\n An instance with equivalent **absolute** dimensions.\n \"\"\"\n if not self.relative:\n return self\n\n width, height, *args, _ = astuple(self)\n terminal_width, terminal_height = terminal_size\n if width <= 0:\n width = max(terminal_width + width, 1)\n if height <= 0:\n height = max(terminal_height + height, 1)\n\n return type(self)(width, height, *args)\n\n # Extension methods ========================================================\n\n @override\n def _get_exact_dimensions_(self, render_size: Size) -> tuple[int, int, int, int]:\n if self.relative:\n raise RelativePaddingDimensionError(\"Relative minimum render dimension(s)\")\n\n width, height, h_align, v_align = astuple(self)[:4]\n render_width, render_height = render_size\n\n if width > render_width:\n padding_width = width - render_width\n numerator, denominator = _ALIGN_RATIOS[h_align]\n left = padding_width * numerator // denominator\n right = padding_width - left\n else:\n left = right = 0\n\n if height > render_height:\n padding_height = height - render_height\n numerator, denominator = _ALIGN_RATIOS[v_align]\n top = padding_height * numerator // denominator\n bottom = padding_height - top\n else:\n top = bottom = 0\n\n return left, top, right, bottom", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 5973}, "tests/test_geometry.py::22": {"resolved_imports": ["src/term_image/geometry.py"], "used_names": ["RawSize"], "enclosing_function": "test_is_tuple", "extracted_code": "# Source: src/term_image/geometry.py\nclass RawSize(NamedTuple):\n \"\"\"The dimensions of a rectangular region.\n\n Args:\n width: The horizontal dimension\n height: The vertical dimension\n\n NOTE:\n * A dimension may be non-positive but the validity and meaning would be\n determined by the receiving interface.\n * This is a subclass of :py:class:`tuple`. Hence, instances can be used anyway\n and anywhere tuples can.\n \"\"\"\n\n width: int\n height: int\n\n @classmethod\n def _new(cls, width: int, height: int) -> Self:\n \"\"\"Alternate constructor for internal use only.\"\"\"\n return tuple.__new__(cls, (width, height))", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 682}, "tests/test_iterator.py::194": {"resolved_imports": ["src/term_image/_ctlseqs.py", "src/term_image/exceptions.py", "src/term_image/image/block.py", "src/term_image/image/common.py"], "used_names": ["BlockImage", "ImageIterator"], "enclosing_function": "test_caching", "extracted_code": "# Source: src/term_image/image/block.py\nclass BlockImage(TextImage):\n \"\"\"A render style using unicode half blocks and direct-color colour escape\n sequences.\n\n See :py:class:`TextImage` for the description of the constructor.\n \"\"\"\n\n @classmethod\n def is_supported(cls):\n if cls._supported is None:\n COLORTERM = os.environ.get(\"COLORTERM\") or \"\"\n TERM = os.environ.get(\"TERM\") or \"\"\n cls._supported = (\n \"truecolor\" in COLORTERM or \"24bit\" in COLORTERM or \"256color\" in TERM\n )\n\n return cls._supported\n\n def _get_render_size(self) -> Tuple[int, int]:\n return tuple(map(mul, self.rendered_size, (1, 2)))\n\n @staticmethod\n def _pixels_cols(\n *, pixels: Optional[int] = None, cols: Optional[int] = None\n ) -> int:\n return pixels if pixels is not None else cols\n\n @staticmethod\n def _pixels_lines(\n *, pixels: Optional[int] = None, lines: Optional[int] = None\n ) -> int:\n return ceil(pixels / 2) if pixels is not None else lines * 2\n\n def _render_image(\n self,\n img: PIL.Image.Image,\n alpha: Union[None, float, str],\n *,\n frame: bool = False,\n split_cells: bool = False,\n ) -> str:\n # NOTE:\n # It's more efficient to write separate strings to the buffer separately\n # than concatenate and write together.\n\n def update_buffer():\n if alpha:\n no_alpha = False\n if a_cluster1 == 0 == a_cluster2:\n buf_write(SGR_DEFAULT)\n buf_write(blank * n)\n elif a_cluster1 == 0: # up is transparent\n buf_write(SGR_DEFAULT)\n buf_write(SGR_FG_DIRECT % cluster2)\n buf_write(lower_pixel * n)\n elif a_cluster2 == 0: # down is transparent\n buf_write(SGR_DEFAULT)\n buf_write(SGR_FG_DIRECT % cluster1)\n buf_write(upper_pixel * n)\n else:\n no_alpha = True\n\n if not alpha or no_alpha:\n r, g, b = cluster2\n # Kitty does not render BG colors equal to the default BG color\n if is_on_kitty and cluster2 == bg_color:\n r += r < 255 or -1\n buf_write(SGR_BG_DIRECT % (r, g, b))\n if cluster1 == cluster2:\n buf_write(blank * n)\n else:\n buf_write(SGR_FG_DIRECT % cluster1)\n buf_write(upper_pixel * n)\n\n buffer = io.StringIO()\n buf_write = buffer.write # Eliminate attribute resolution cost\n\n bg_color = get_fg_bg_colors()[1]\n is_on_kitty = self._is_on_kitty()\n if split_cells:\n blank = \" \\0\"\n lower_pixel = LOWER_PIXEL + \"\\0\"\n upper_pixel = UPPER_PIXEL + \"\\0\"\n else:\n blank = \" \"\n lower_pixel = LOWER_PIXEL\n upper_pixel = UPPER_PIXEL\n end_of_line = SGR_DEFAULT + \"\\n\"\n\n width, height = self._get_render_size()\n frame_img = img if frame else None\n img, rgb, a = self._get_render_data(img, alpha, round_alpha=True, frame=frame)\n alpha = img.mode == \"RGBA\"\n\n # clean up (ImageIterator uses one PIL image throughout)\n if frame_img is not img:\n self._close_image(img)\n\n rgb_pairs = (\n (\n zip(rgb[x : x + width], rgb[x + width : x + width * 2]),\n (rgb[x], rgb[x + width]),\n )\n for x in range(0, len(rgb), width * 2)\n )\n a_pairs = (\n (\n zip(a[x : x + width], a[x + width : x + width * 2]),\n (a[x], a[x + width]),\n )\n for x in range(0, len(a), width * 2)\n )\n\n row_no = 0\n # Two rows of pixels per line\n for (rgb_pair, (cluster1, cluster2)), (a_pair, (a_cluster1, a_cluster2)) in zip(\n rgb_pairs, a_pairs\n ):\n row_no += 2\n n = 0\n for (px1, px2), (a1, a2) in zip(rgb_pair, a_pair):\n # Color-code characters and write to buffer\n # when upper and/or lower pixel color/alpha-level changes\n if not (alpha and a1 == a_cluster1 == 0 == a_cluster2 == a2) and (\n px1 != cluster1\n or px2 != cluster2\n or alpha\n and (\n # From non-transparent to transparent\n a_cluster1 != a1 == 0\n or a_cluster2 != a2 == 0\n # From transparent to non-transparent\n or 0 == a_cluster1 != a1\n or 0 == a_cluster2 != a2\n )\n ):\n update_buffer()\n cluster1 = px1\n cluster2 = px2\n if alpha:\n a_cluster1 = a1\n a_cluster2 = a2\n n = 0\n n += 1\n\n update_buffer() # Rest of the line\n if split_cells:\n # Set the last \"\\0\" to be overwritten by the next byte\n buffer.seek(buffer.tell() - 1)\n if row_no < height: # last line not yet rendered\n buf_write(end_of_line)\n\n buf_write(SGR_DEFAULT) # Reset color after last line\n\n with buffer:\n return buffer.getvalue()\n\n\n# Source: src/term_image/image/common.py\nclass ImageIterator:\n \"\"\"Efficiently iterate over :term:`rendered` frames of an :term:`animated` image\n\n Args:\n image: Animated image.\n repeat: The number of times to go over the entire image. A negative value\n implies infinite repetition.\n format_spec: The :ref:`format specifier ` for the rendered\n frames (default: auto).\n cached: Determines if the :term:`rendered` frames will be cached (for speed up\n of subsequent renders) or not. If it is\n\n * a boolean, caching is enabled if ``True``. Otherwise, caching is disabled.\n * a positive integer, caching is enabled only if the framecount of the image\n is less than or equal to the given number.\n\n Raises:\n TypeError: An argument is of an inappropriate type.\n ValueError: An argument is of an appropriate type but has an\n unexpected/invalid value.\n term_image.exceptions.StyleError: Invalid style-specific format specifier.\n\n * If *repeat* equals ``1``, caching is disabled.\n * The iterator has immediate response to changes in the image size.\n * If the image size is :term:`dynamic `, it's computed per frame.\n * The number of the last yielded frame is set as the image's seek position.\n * Directly adjusting the seek position of the image doesn't affect iteration.\n Use :py:meth:`ImageIterator.seek` instead.\n * After the iterator is exhausted, the underlying image is set to frame ``0``.\n \"\"\"\n\n def __init__(\n self,\n image: BaseImage,\n repeat: int = -1,\n format_spec: str = \"\",\n cached: Union[bool, int] = 100,\n ) -> None:\n if not isinstance(image, BaseImage):\n raise arg_type_error(\"image\", image)\n if not image._is_animated:\n raise ValueError(\"'image' is not animated\")\n\n if not isinstance(repeat, int):\n raise arg_type_error(\"repeat\", repeat)\n if not repeat:\n raise arg_value_error(\"repeat\", repeat)\n\n if not isinstance(format_spec, str):\n raise arg_type_error(\"format_spec\", format_spec)\n *fmt, alpha, style_args = image._check_format_spec(format_spec)\n\n if not isinstance(cached, int): # `bool` is a subclass of `int`\n raise arg_type_error(\"cached\", cached)\n if False is not cached <= 0:\n raise arg_value_error_range(\"cached\", cached)\n\n self._image = image\n self._repeat = repeat\n self._format = format_spec\n self._cached = repeat != 1 and (\n cached if isinstance(cached, bool) else image.n_frames <= cached\n )\n self._loop_no = None\n self._animator = image._renderer(\n self._animate, alpha, fmt, style_args, check_size=False\n )\n\n def __del__(self) -> None:\n self.close()\n\n def __iter__(self) -> ImageIterator:\n return self\n\n def __next__(self) -> str:\n try:\n return next(self._animator)\n except StopIteration:\n self.close()\n raise StopIteration(\n \"Iteration has reached the given repeat count\"\n ) from None\n except AttributeError as e:\n if str(e).endswith(\"'_animator'\"):\n raise StopIteration(\"Iterator exhausted or closed\") from None\n else:\n self.close()\n raise\n except Exception:\n self.close()\n raise\n\n def __repr__(self) -> str:\n return (\n \"{}(image={!r}, repeat={}, format_spec={!r}, cached={}, loop_no={})\".format(\n type(self).__name__,\n *self.__dict__.values(),\n )\n )\n\n loop_no = property(\n lambda self: self._loop_no,\n doc=\"\"\"Iteration repeat countdown\n\n :type: Optional[int]\n\n GET:\n Returns:\n\n * ``None``, if iteration hasn't started.\n * Otherwise, the current iteration repeat countdown value.\n\n Changes on the first iteration of each loop, except for infinite iteration\n where it's always ``-1``. When iteration has ended, the value is zero.\n \"\"\",\n )\n\n def close(self) -> None:\n \"\"\"Closes the iterator and releases resources used.\n\n Does not reset the frame number of the underlying image.\n\n NOTE:\n This method is automatically called when the iterator is exhausted or\n garbage-collected.\n \"\"\"\n try:\n self._animator.close()\n del self._animator\n self._image._close_image(self._img)\n del self._img\n except AttributeError:\n pass\n\n def seek(self, pos: int) -> None:\n \"\"\"Sets the frame number to be yielded on the next iteration without affecting\n the repeat count.\n\n Args:\n pos: Next frame number.\n\n Raises:\n TypeError: An argument is of an inappropriate type.\n ValueError: An argument is of an appropriate type but has an\n unexpected/invalid value.\n term_image.exceptions.TermImageError: Iteration has not yet started or the\n iterator is exhausted/closed.\n\n Frame numbers start from ``0`` (zero).\n \"\"\"\n if not isinstance(pos, int):\n raise arg_type_error(\"pos\", pos)\n if not 0 <= pos < self._image.n_frames:\n raise arg_value_error_range(\"pos\", pos, f\"n_frames={self._image.n_frames}\")\n\n try:\n self._animator.send(pos)\n except TypeError:\n raise TermImageError(\"Iteration has not yet started\") from None\n except AttributeError:\n raise TermImageError(\"Iterator exhausted or closed\") from None\n\n def _animate(\n self,\n img: PIL.Image.Image,\n alpha: Union[None, float, str],\n fmt: Tuple[Union[None, str, int]],\n style_args: Dict[str, Any],\n ) -> Generator[str, int, None]:\n \"\"\"Returns a generator that yields rendered and formatted frames of the\n underlying image.\n \"\"\"\n self._img = img # For cleanup\n image = self._image\n cached = self._cached\n self._loop_no = repeat = self._repeat\n if cached:\n cache = [(None,) * 2] * image.n_frames\n\n sent = None\n n = 0\n while repeat:\n if sent is None:\n image._seek_position = n\n try:\n frame = image._format_render(\n image._render_image(img, alpha, frame=True, **style_args), *fmt\n )\n except EOFError:\n image._seek_position = n = 0\n if repeat > 0: # Avoid infinitely large negative numbers\n self._loop_no = repeat = repeat - 1\n if cached:\n break\n continue\n else:\n if cached:\n cache[n] = (frame, hash(image.rendered_size))\n\n sent = yield frame\n n = n + 1 if sent is None else sent - 1\n\n if cached:\n n_frames = len(cache)\n while repeat:\n while n < n_frames:\n if sent is None:\n image._seek_position = n\n frame, size_hash = cache[n]\n if hash(image.rendered_size) != size_hash:\n frame = image._format_render(\n image._render_image(img, alpha, frame=True, **style_args),\n *fmt,\n )\n cache[n] = (frame, hash(image.rendered_size))\n\n sent = yield frame\n n = n + 1 if sent is None else sent - 1\n\n image._seek_position = n = 0\n if repeat > 0: # Avoid infinitely large negative numbers\n self._loop_no = repeat = repeat - 1\n\n # For consistency in behaviour\n if img is image._source:\n img.seek(0)", "n_imports_parsed": 7, "n_files_resolved": 4, "n_chars_extracted": 13671}, "tests/test_padding.py::144": {"resolved_imports": ["src/term_image/_ctlseqs.py", "src/term_image/geometry.py", "src/term_image/padding.py"], "used_names": ["AlignedPadding", "pytest"], "enclosing_function": "test_width", "extracted_code": "# Source: src/term_image/padding.py\nclass AlignedPadding(Padding):\n \"\"\"Aligned :term:`render output` padding.\n\n Args:\n width: Minimum :term:`render width`.\n height: Minimum :term:`render height`.\n h_align: Horizontal alignment.\n v_align: Vertical alignment.\n\n If *width* or *height* is:\n\n * positive, it is **absolute** and used as-is.\n * non-positive, it is **relative** to the corresponding terminal dimension\n (**at the point of resolution**) and equivalent to the absolute dimension\n ``max(terminal_dimension + relative_dimension, 1)``.\n\n The *padded render dimension* (i.e the dimension of a :term:`render output` after\n it's padded) on each axis is given by::\n\n padded_dimension = max(render_dimension, absolute_minimum_dimension)\n\n In words... If the **absolute** *minimum render dimension* on an axis is less than\n or equal to the corresponding *render dimension*, there is no padding on that axis\n and the *padded render dimension* on that axis is equal to the *render dimension*.\n Otherwise, the render output will be padded along that axis and the *padded render\n dimension* on that axis is equal to the *minimum render dimension*.\n\n The amount of padding to each side depends on the alignment, defined by *h_align*\n and *v_align*.\n\n IMPORTANT:\n :py:class:`RelativePaddingDimensionError` is raised if any padding-related\n computation/operation (basically, calling any method other than\n :py:meth:`resolve`) is performed on an instance with **relative** *minimum\n render dimension(s)* i.e if :py:attr:`relative` is ``True``.\n\n NOTE:\n Any interface receiving an instance with **relative** dimension(s) should\n typically resolve it/them upon reception.\n\n TIP:\n * Instances are immutable and hashable.\n * Instances with equal fields compare equal.\n \"\"\"\n\n # Class Attributes =========================================================\n\n __slots__ = (\"width\", \"height\", \"h_align\", \"v_align\", \"relative\")\n\n # Instance Attributes ======================================================\n\n width: int\n \"\"\"Minimum :term:`render width`\"\"\"\n\n height: int\n \"\"\"Minimum :term:`render height`\"\"\"\n\n h_align: HAlign\n \"\"\"Horizontal alignment\"\"\"\n\n v_align: VAlign\n \"\"\"Vertical alignment\"\"\"\n\n fill: str\n\n relative: bool\n \"\"\"``True`` if either or both *minimum render dimension(s)* is/are relative i.e\n non-positive. Otherwise, ``False``.\n \"\"\"\n\n # Special Methods ==========================================================\n\n def __init__(\n self,\n width: int,\n height: int,\n h_align: HAlign = HAlign.CENTER,\n v_align: VAlign = VAlign.MIDDLE,\n fill: str = \" \",\n ):\n super().__init__(fill)\n\n _setattr = super().__setattr__\n _setattr(\"width\", width)\n _setattr(\"height\", height)\n _setattr(\"h_align\", h_align)\n _setattr(\"v_align\", v_align)\n _setattr(\"relative\", not width > 0 < height)\n\n def __repr__(self) -> str:\n return \"{}(width={}, height={}, h_align={}, v_align={}, fill={!r})\".format(\n type(self).__name__,\n self.width,\n self.height,\n self.h_align.name,\n self.v_align.name,\n self.fill,\n )\n\n # Properties ===============================================================\n\n @property\n def size(self) -> RawSize:\n \"\"\"Minimum :term:`render size`\n\n GET:\n Returns the *minimum render dimensions*.\n \"\"\"\n return _RawSize(self.width, self.height)\n\n # Public Methods ===========================================================\n\n @override\n def get_padded_size(self, render_size: Size) -> Size:\n \"\"\"Computes an expected padded :term:`render size`.\n\n See :py:meth:`Padding.get_padded_size`.\n\n Raises:\n RelativePaddingDimensionError: Relative *minimum render dimension(s)*.\n \"\"\"\n if self.relative:\n raise RelativePaddingDimensionError(\"Relative minimum render dimension(s)\")\n\n return _Size(max(self.width, render_size[0]), max(self.height, render_size[1]))\n\n def resolve(self, terminal_size: os.terminal_size) -> AlignedPadding:\n \"\"\"Resolves **relative** *minimum render dimensions*.\n\n Args:\n terminal_size: The terminal size against which to resolve relative\n dimensions.\n\n Returns:\n An instance with equivalent **absolute** dimensions.\n \"\"\"\n if not self.relative:\n return self\n\n width, height, *args, _ = astuple(self)\n terminal_width, terminal_height = terminal_size\n if width <= 0:\n width = max(terminal_width + width, 1)\n if height <= 0:\n height = max(terminal_height + height, 1)\n\n return type(self)(width, height, *args)\n\n # Extension methods ========================================================\n\n @override\n def _get_exact_dimensions_(self, render_size: Size) -> tuple[int, int, int, int]:\n if self.relative:\n raise RelativePaddingDimensionError(\"Relative minimum render dimension(s)\")\n\n width, height, h_align, v_align = astuple(self)[:4]\n render_width, render_height = render_size\n\n if width > render_width:\n padding_width = width - render_width\n numerator, denominator = _ALIGN_RATIOS[h_align]\n left = padding_width * numerator // denominator\n right = padding_width - left\n else:\n left = right = 0\n\n if height > render_height:\n padding_height = height - render_height\n numerator, denominator = _ALIGN_RATIOS[v_align]\n top = padding_height * numerator // denominator\n bottom = padding_height - top\n else:\n top = bottom = 0\n\n return left, top, right, bottom", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 5973}, "tests/test_image/test_others.py::22": {"resolved_imports": ["src/term_image/image/common.py", "src/term_image/image/__init__.py"], "used_names": ["BaseImage", "BytesPath", "Path", "Size", "from_file", "pytest", "python_image", "python_img"], "enclosing_function": "test_from_file", "extracted_code": "# Source: src/term_image/image/common.py\nclass Size(Enum):\n \"\"\"Enumeration for :term:`automatic sizing`.\"\"\"\n\n #: Equivalent to :py:attr:`ORIGINAL` if it will fit into the\n #: :term:`frame size`, else :py:attr:`FIT`.\n #:\n #: :meta hide-value:\n AUTO = Hidden()\n\n #: The image size is set to fit optimally **within** the :term:`frame size`.\n #:\n #: :meta hide-value:\n FIT = Hidden()\n\n #: The size is set such that the width is exactly the :term:`frame width`,\n #: regardless of the :term:`cell ratio`.\n #:\n #: :meta hide-value:\n FIT_TO_WIDTH = Hidden()\n\n #: The image size is set such that the image is rendered with as many pixels as the\n #: the original image consists of.\n #:\n #: :meta hide-value:\n ORIGINAL = Hidden()\n\nclass BaseImage(metaclass=ImageMeta):\n \"\"\"Base of all render styles.\n\n Args:\n image: Source image.\n width: Can be\n\n * a positive integer; horizontal dimension of the image, in columns.\n * a :py:class:`~term_image.image.Size` enum member.\n\n height: Can be\n\n * a positive integer; vertical dimension of the image, in lines.\n * a :py:class:`~term_image.image.Size` enum member.\n\n Raises:\n TypeError: An argument is of an inappropriate type.\n ValueError: An argument is of an appropriate type but has an\n unexpected/invalid value.\n\n Propagates exceptions raised by :py:meth:`set_size`, if *width* or *height* is\n given.\n\n NOTE:\n * If neither *width* nor *height* is given (or both are ``None``),\n :py:attr:`~term_image.image.Size.FIT` applies.\n * If both width and height are not ``None``, they must be positive integers\n and :term:`manual sizing` applies i.e the image size is set as given without\n preserving aspect ratio.\n * For animated images, the seek position is initialized to the current seek\n position of the given image.\n * It's allowed to set properties for :term:`animated` images on non-animated\n ones, the values are simply ignored.\n\n ATTENTION:\n This class cannot be directly instantiated. Image instances should be created\n from its subclasses.\n \"\"\"\n\n # Data Attributes\n\n _forced_support: bool = False\n _supported: Optional[bool] = None\n _render_method: Optional[str] = None\n _render_methods: Set[str] = set()\n _style_args: Dict[\n str, Tuple[Tuple[FunctionType, str], Tuple[FunctionType, str]]\n ] = {}\n\n # Special Methods\n\n def __init__(\n self,\n image: PIL.Image.Image,\n *,\n width: Union[int, Size, None] = None,\n height: Union[int, Size, None] = None,\n ) -> None:\n \"\"\"See the class description\"\"\"\n if not isinstance(image, Image.Image):\n raise arg_type_error(\"image\", image)\n if 0 in image.size:\n raise ValueError(\"'image' is null-sized\")\n\n self._closed = False\n self._source = image\n self._source_type = ImageSource.PIL_IMAGE\n self._original_size = image.size\n if width is None is height:\n self.size = Size.FIT\n else:\n self.set_size(width, height)\n\n self._is_animated = hasattr(image, \"is_animated\") and image.is_animated\n if self._is_animated:\n self._frame_duration = (image.info.get(\"duration\") or 100) / 1000\n self._seek_position = image.tell()\n self._n_frames = None\n\n def __del__(self) -> None:\n self.close()\n\n def __enter__(self) -> BaseImage:\n return self\n\n def __exit__(self, typ: type, val: Exception, tb: TracebackType) -> bool:\n self.close()\n return False # Currently, no particular exception is suppressed\n\n def __format__(self, spec: str) -> str:\n \"\"\"Renders the image with alignment, padding and transparency control\"\"\"\n # Only the currently set frame is rendered for animated images\n h_align, width, v_align, height, alpha, style_args = self._check_format_spec(\n spec\n )\n\n return self._format_render(\n self._renderer(self._render_image, alpha, **style_args),\n h_align,\n width,\n v_align,\n height,\n )\n\n def __iter__(self) -> ImageIterator:\n return ImageIterator(self, 1, \"1.1\", False)\n\n def __repr__(self) -> str:\n return \"<{}: source_type={} size={} is_animated={}>\".format(\n type(self).__name__,\n self._source_type.name,\n (\n self._size.name\n if isinstance(self._size, Size)\n else \"x\".join(map(str, self._size))\n ),\n self._is_animated,\n )\n\n def __str__(self) -> str:\n \"\"\"Renders the image with transparency enabled and without alignment\"\"\"\n # Only the currently set frame is rendered for animated images\n return self._renderer(self._render_image, _ALPHA_THRESHOLD)\n\n # Properties\n\n closed = property(\n lambda self: self._closed,\n doc=\"\"\"Instance finalization status\n\n :type: bool\n\n GET:\n Returns ``True`` if the instance has been finalized (:py:meth:`close` has\n been called). Otherwise, ``False``.\n \"\"\",\n )\n\n forced_support = ClassProperty(\n lambda self: type(self)._forced_support,\n doc=\"\"\"Forced render style support\n\n :type: bool\n\n GET:\n Returns the forced support status of the invoking class or class of the\n invoking instance.\n\n SET:\n Forced support is enabled or disabled for the invoking class.\n\n Can not be set on an instance.\n\n If forced support is:\n\n * **enabled**, the render style is treated as if it were supported,\n regardless of the return value of :py:meth:`is_supported`.\n * **disabled**, the return value of :py:meth:`is_supported` determines if\n the render style is supported or not.\n\n By **default**, forced support is **disabled** for all render style classes.\n\n NOTE:\n * This property is :term:`descendant`.\n * This doesn't affect the return value of :py:meth:`is_supported` but\n may affect operations that require that a render style be supported e.g\n instantiation of some render style classes.\n \"\"\",\n )\n\n frame_duration = property(\n lambda self: self._frame_duration if self._is_animated else None,\n doc=\"\"\"Duration of a single frame\n\n :type: Optional[float]\n\n GET:\n Returns:\n\n * The duration of a single frame (in seconds), if the image is animated.\n * ``None``, if otherwise.\n\n SET:\n If the image is animated, The frame duration is set.\n Otherwise, nothing is done.\n \"\"\",\n )\n\n @frame_duration.setter\n def frame_duration(self, value: float) -> None:\n if not isinstance(value, float):\n raise arg_type_error(\"frame_duration\", value)\n if value <= 0.0:\n raise arg_value_error_range(\"frame_duration\", value)\n if self._is_animated:\n self._frame_duration = value\n\n height = property(\n lambda self: self._size if isinstance(self._size, Size) else self._size[1],\n lambda self, height: self.set_size(height=height),\n doc=\"\"\"\n Image height\n\n :type: Union[Size, int]\n\n GET:\n Returns:\n\n * The image height (in lines), if the image size is\n :term:`fixed `.\n * A :py:class:`~term_image.image.Size` enum member, if the image size\n is :term:`dynamic `.\n\n SET:\n If set to:\n\n * a positive :py:class:`int`; the image height is set to the given value\n and the width is set proportionally.\n * a :py:class:`~term_image.image.Size` enum member; the image size is set\n as prescibed by the enum member.\n * ``None``; equivalent to :py:attr:`~term_image.image.Size.FIT`.\n\n This results in a :term:`fixed size`.\n \"\"\",\n )\n\n is_animated = property(\n lambda self: self._is_animated,\n doc=\"\"\"\n Animatability of the image\n\n :type: bool\n\n GET:\n Returns ``True`` if the image is :term:`animated`. Otherwise, ``False``.\n \"\"\",\n )\n\n original_size = property(\n lambda self: self._original_size,\n doc=\"\"\"Size of the source (in pixels)\n\n :type: Tuple[int, int]\n\n GET:\n Returns the source size.\n \"\"\",\n )\n\n @property\n def n_frames(self) -> int:\n \"\"\"Image frame count\n\n :type: int\n\n GET:\n Returns the number of frames the image has.\n \"\"\"\n if not self._is_animated:\n return 1\n\n if not self._n_frames:\n img = self._get_image()\n try:\n self._n_frames = img.n_frames\n finally:\n self._close_image(img)\n\n return self._n_frames\n\n rendered_height = property(\n lambda self: (\n self._valid_size(None, self._size)\n if isinstance(self._size, Size)\n else self._size\n )[1],\n doc=\"\"\"\n The height with which the image is :term:`rendered`\n\n :type: int\n\n GET:\n Returns the number of lines the image will occupy when drawn in a terminal.\n \"\"\",\n )\n\n rendered_size = property(\n lambda self: (\n self._valid_size(self._size, None)\n if isinstance(self._size, Size)\n else self._size\n ),\n doc=\"\"\"\n The size with which the image is :term:`rendered`\n\n :type: Tuple[int, int]\n\n GET:\n Returns the number of columns and lines (respectively) the image will\n occupy when drawn in a terminal.\n \"\"\",\n )\n\n rendered_width = property(\n lambda self: (\n self._valid_size(self._size, None)\n if isinstance(self._size, Size)\n else self._size\n )[0],\n doc=\"\"\"\n The width with which the image is :term:`rendered`\n\n :type: int\n\n GET:\n Returns the number of columns the image will occupy when drawn in a\n terminal.\n \"\"\",\n )\n\n size = property(\n lambda self: self._size,\n doc=\"\"\"\n Image size\n\n :type: Union[Size, Tuple[int, int]]\n\n GET:\n Returns:\n\n * The image size, ``(columns, lines)``, if the image size is\n :term:`fixed `.\n * A :py:class:`~term_image.image.Size` enum member, if the image size\n is :term:`dynamic `.\n\n SET:\n If set to a:\n\n * :py:class:`~term_image.image.Size` enum member, the image size is set\n as prescibed by the given member.\n\n This results in a :term:`dynamic size` i.e the size is computed whenever\n the image is :term:`rendered` using the default :term:`frame size`.\n\n * 2-tuple of integers, ``(width, height)``, the image size set as given.\n\n This results in a :term:`fixed size` i.e the size will not change until\n it is re-set.\n \"\"\",\n )\n\n @size.setter\n def size(self, size: Size | Tuple[int, int]) -> None:\n if isinstance(size, Size):\n self._size = size\n elif isinstance(size, tuple):\n if len(size) != 2:\n raise arg_value_error(\"size\", size)\n self.set_size(*size)\n else:\n raise arg_type_error(\"size\", size)\n\n source = property(\n _close_validated(lambda self: getattr(self, self._source_type.value)),\n doc=\"\"\"\n Image :term:`source`\n\n :type: Union[PIL.Image.Image, str]\n\n GET:\n Returns the :term:`source` from which the instance was initialized.\n \"\"\",\n )\n\n source_type = property(\n lambda self: self._source_type,\n doc=\"\"\"\n Image :term:`source` type\n\n :type: ImageSource\n\n GET:\n Returns the type of :term:`source` from which the instance was initialized.\n \"\"\",\n )\n\n width = property(\n lambda self: self._size if isinstance(self._size, Size) else self._size[0],\n lambda self, width: self.set_size(width),\n doc=\"\"\"\n Image width\n\n :type: Union[Size, int]\n\n GET:\n Returns:\n\n * The image width (in columns), if the image size is\n :term:`fixed `.\n * A :py:class:`~term_image.image.Size` enum member; if the image size\n is :term:`dynamic `.\n\n SET:\n If set to:\n\n * a positive :py:class:`int`; the image width is set to the given value\n and the height is set proportionally.\n * a :py:class:`~term_image.image.Size` enum member; the image size is set\n as prescibed by the enum member.\n * ``None``; equivalent to :py:attr:`~term_image.image.Size.FIT`.\n\n This results in a :term:`fixed size`.\n \"\"\",\n )\n\n # # Private\n\n @property\n @abstractmethod\n def _pixel_ratio(self):\n \"\"\"The width-to-height ratio of a pixel drawn in the terminal\"\"\"\n raise NotImplementedError\n\n # Public Methods\n\n def close(self) -> None:\n \"\"\"Finalizes the instance and releases external resources.\n\n * In most cases, it's not necessary to explicitly call this method, as it's\n automatically called when the instance is garbage-collected.\n * This method can be safely called multiple times.\n * If the instance was initialized with a PIL image, the PIL image is never\n finalized.\n \"\"\"\n try:\n if not self._closed:\n if self._source_type is ImageSource.URL:\n try:\n os.remove(self._source)\n except FileNotFoundError:\n pass\n del self._url\n del self._source\n except AttributeError:\n pass # Instance creation or initialization was unsuccessful\n finally:\n self._closed = True\n\n def draw(\n self,\n h_align: Optional[str] = None,\n pad_width: int = 0,\n v_align: Optional[str] = None,\n pad_height: int = -2,\n alpha: Optional[float, str] = _ALPHA_THRESHOLD,\n *,\n animate: bool = True,\n repeat: int = -1,\n cached: Union[bool, int] = 100,\n scroll: bool = False,\n check_size: bool = True,\n **style: Any,\n ) -> None:\n \"\"\"Draws the image to standard output.\n\n Args:\n h_align: Horizontal alignment (\"left\" / \"<\", \"center\" / \"|\" or\n \"right\" / \">\"). Default: center.\n pad_width: Number of columns within which to align the image.\n\n * Excess columns are filled with spaces.\n * Must not be greater than the :term:`terminal width`.\n\n v_align: Vertical alignment (\"top\"/\"^\", \"middle\"/\"-\" or \"bottom\"/\"_\").\n Default: middle.\n pad_height: Number of lines within which to align the image.\n\n * Excess lines are filled with spaces.\n * Must not be greater than the :term:`terminal height`,\n **for animations**.\n\n alpha: Transparency setting.\n\n * If ``None``, transparency is disabled (alpha channel is removed).\n * If a ``float`` (**0.0 <= x < 1.0**), specifies the alpha ratio\n **above** which pixels are taken as **opaque**. **(Applies to only\n text-based render styles)**.\n * If a string, specifies a color to replace transparent background with.\n Can be:\n\n * **\"#\"** -> The terminal's default background color (or black, if\n undetermined) is used.\n * A hex color e.g ``ffffff``, ``7faa52``.\n\n animate: If ``False``, disable animation i.e draw only the current frame of\n an animated image.\n repeat: The number of times to go over all frames of an animated image.\n A negative value implies infinite repetition.\n cached: Determines if :term:`rendered` frames of an animated image will be\n cached (for speed up of subsequent renders of the same frame) or not.\n\n * If :py:class:`bool`, it directly sets if the frames will be cached or\n not.\n * If :py:class:`int`, caching is enabled only if the framecount of the\n image is less than or equal to the given number.\n\n scroll: Only applies to non-animations. If ``True``, allows the image's\n :term:`rendered height` to be greater than the :term:`terminal height`.\n check_size: If ``False``, rendered size validation is not performed for\n non-animations. Does not affect padding size validation.\n style: Style-specific render parameters. See each subclass for it's own\n usage.\n\n Raises:\n TypeError: An argument is of an inappropriate type.\n ValueError: An argument is of an appropriate type but has an\n unexpected/invalid value.\n term_image.exceptions.InvalidSizeError: The image's :term:`rendered size`\n can not fit into the :term:`terminal size`.\n term_image.exceptions.StyleError: Unrecognized style-specific render\n parameter(s).\n term_image.exceptions.RenderError: An error occurred during\n :term:`rendering`.\n\n * If *pad_width* or *pad_height* is:\n\n * positive, it is **absolute** and used as-is.\n * non-positive, it is **relative** to the corresponding terminal dimension\n (**at the point of calling this method**) and equivalent to the absolute\n dimension ``max(terminal_dimension + frame_dimension, 1)``.\n\n * :term:`padding width` is always validated.\n * *animate*, *repeat* and *cached* apply to :term:`animated` images only.\n They are simply ignored for non-animated images.\n * For animations (i.e animated images with *animate* set to ``True``):\n\n * *scroll* is ignored.\n * Image size is always validated, if set.\n * :term:`Padding height` is always validated.\n\n * Animations, **by default**, are infinitely looped and can be terminated\n with :py:data:`~signal.SIGINT` (``CTRL + C``), **without** raising\n :py:class:`KeyboardInterrupt`.\n \"\"\"\n fmt = self._check_formatting(h_align, pad_width, v_align, pad_height)\n\n if alpha is not None:\n if isinstance(alpha, float):\n if not 0.0 <= alpha < 1.0:\n raise arg_value_error_range(\"alpha\", alpha)\n elif isinstance(alpha, str):\n if not _ALPHA_BG_FORMAT.fullmatch(alpha):\n raise arg_value_error_msg(\"Invalid hex color string\", alpha)\n else:\n raise arg_type_error(\"alpha\", alpha)\n\n if self._is_animated and not isinstance(animate, bool):\n raise arg_type_error(\"animate\", animate)\n\n terminal_width, terminal_height = get_terminal_size()\n if pad_width > terminal_width:\n raise arg_value_error_range(\n \"pad_width\", pad_width, got_extra=f\"terminal_width={terminal_width}\"\n )\n\n animation = self._is_animated and animate\n\n if animation and pad_height > terminal_height:\n raise arg_value_error_range(\n \"pad_height\",\n pad_height,\n got_extra=f\"terminal_height={terminal_height}, animation={animation}\",\n )\n\n for arg in (\"scroll\", \"check_size\"):\n arg_value = locals()[arg]\n if not isinstance(arg_value, bool):\n raise arg_type_error(arg, arg_value)\n\n # Checks for *repeat* and *cached* are delegated to `ImageIterator`.\n\n def render(image: PIL.Image.Image) -> None:\n # Hide the cursor immediately if the output is a terminal device\n sys.stdout.isatty() and print(HIDE_CURSOR, end=\"\", flush=True)\n try:\n style_args = self._check_style_args(style)\n if animation:\n self._display_animated(\n image, alpha, fmt, repeat, cached, **style_args\n )\n else:\n try:\n print(\n self._format_render(\n self._render_image(image, alpha, **style_args),\n *fmt,\n ),\n end=\"\",\n flush=True,\n )\n except (KeyboardInterrupt, Exception):\n self._handle_interrupted_draw()\n raise\n finally:\n # Reset color and show the cursor\n print(SGR_DEFAULT, SHOW_CURSOR * sys.stdout.isatty(), sep=\"\")\n\n self._renderer(\n render,\n scroll=scroll,\n check_size=check_size,\n animated=animation,\n )\n\n @classmethod\n def from_file(\n cls,\n filepath: Union[str, os.PathLike],\n **kwargs: Union[None, int],\n ) -> BaseImage:\n \"\"\"Creates an instance from an image file.\n\n Args:\n filepath: Relative/Absolute path to an image file.\n kwargs: Same keyword arguments as the class constructor.\n\n Returns:\n A new instance.\n\n Raises:\n TypeError: *filepath* is of an inappropriate type.\n FileNotFoundError: The given path does not exist.\n\n Propagates exceptions raised (or propagated) by :py:func:`PIL.Image.open` and\n the class constructor.\n \"\"\"\n if not isinstance(filepath, (str, os.PathLike)):\n raise arg_type_error(\"filepath\", filepath)\n\n if isinstance(filepath, os.PathLike):\n filepath = filepath.__fspath__()\n if isinstance(filepath, bytes):\n filepath = filepath.decode()\n\n # Intentionally propagates `IsADirectoryError` since the message is OK\n try:\n img = Image.open(filepath)\n except FileNotFoundError:\n raise FileNotFoundError(f\"No such file: {filepath!r}\") from None\n except UnidentifiedImageError as e:\n e.args = (f\"Could not identify {filepath!r} as an image\",)\n raise\n\n with img:\n new = cls(img, **kwargs)\n # Absolute paths work better with symlinks, as opposed to real paths:\n # less confusing, Filename is as expected, helps in path comparisons\n new._source = os.path.abspath(filepath)\n new._source_type = ImageSource.FILE_PATH\n return new\n\n @classmethod\n def from_url(\n cls,\n url: str,\n **kwargs: Union[None, int],\n ) -> BaseImage:\n \"\"\"Creates an instance from an image URL.\n\n Args:\n url: URL of an image file.\n kwargs: Same keyword arguments as the class constructor.\n\n Returns:\n A new instance.\n\n Raises:\n TypeError: *url* is not a string.\n ValueError: The URL is invalid.\n term_image.exceptions.URLNotFoundError: The URL does not exist.\n PIL.UnidentifiedImageError: Propagated from :py:func:`PIL.Image.open`.\n\n Also propagates connection-related exceptions from :py:func:`requests.get`\n and exceptions raised or propagated by the class constructor.\n\n NOTE:\n This method creates a temporary file, but only after successful\n initialization. The file is removed:\n\n - when :py:meth:`close` is called,\n - upon exiting a ``with`` statement block that uses the instance as a\n context manager, or\n - when the instance is garbage collected.\n \"\"\"\n if not isinstance(url, str):\n raise arg_type_error(\"url\", url)\n if not all(urlparse(url)[:3]):\n raise arg_value_error_msg(\"Invalid URL\", url)\n\n # Propagates connection-related errors.\n response = requests.get(url, stream=True)\n if response.status_code == 404:\n raise URLNotFoundError(f\"URL {url!r} does not exist.\")\n\n # Ensure initialization is successful before writing to file\n try:\n new = cls(Image.open(io.BytesIO(response.content)), **kwargs)\n except UnidentifiedImageError as e:\n e.args = (f\"The URL {url!r} doesn't link to an identifiable image\",)\n raise\n\n fd, filepath = mkstemp(\"-\" + os.path.basename(url), dir=_TEMP_DIR)\n os.write(fd, response.content)\n os.close(fd)\n\n new._source = filepath\n new._source_type = ImageSource.URL\n new._url = url\n return new\n\n @classmethod\n @abstractmethod\n def is_supported(cls) -> bool:\n \"\"\"Checks if the implemented :term:`render style` is supported by the\n :term:`active terminal`.\n\n Returns:\n ``True`` if the render style implemented by the invoking class is supported\n by the :term:`active terminal`. Otherwise, ``False``.\n\n ATTENTION:\n Support checks for most (if not all) render styles require :ref:`querying\n ` the :term:`active terminal` the **first time** they're\n executed.\n\n Hence, it's advisable to perform all necessary support checks (call\n this method on required style classes) at an early stage of a program,\n before user input is expected. If using automatic style selection,\n calling :py:func:`~term_image.image.auto_image_class` only should be\n sufficient.\n \"\"\"\n raise NotImplementedError\n\n def seek(self, pos: int) -> None:\n \"\"\"Changes current image frame.\n\n Args:\n pos: New frame number.\n\n Raises:\n TypeError: An argument is of an inappropriate type.\n ValueError: An argument is of an appropriate type but has an\n unexpected/invalid value.\n\n Frame numbers start from 0 (zero).\n \"\"\"\n if not isinstance(pos, int):\n raise arg_type_error(\"pos\", pos)\n if not 0 <= pos < self.n_frames:\n raise arg_value_error_range(\"pos\", pos, f\"n_frames={self.n_frames}\")\n if self._is_animated:\n self._seek_position = pos\n\n @ClassInstanceMethod\n def set_render_method(cls, method: Optional[str] = None) -> None:\n \"\"\"Sets the :term:`render method` used by instances of a :term:`render style`\n class that implements multiple render methods.\n\n Args:\n method: The render method to be set or ``None`` for a reset\n (case-insensitive).\n\n Raises:\n TypeError: An argument is of an inappropriate type.\n ValueError: An argument is of an appropriate type but has an\n unexpected/invalid value.\n\n See the **Render Methods** section in the description of subclasses that\n implement such for their specific usage.\n\n If *method* is not ``None`` and this method is called via:\n\n - a class, the class-wide render method is set.\n - an instance, the instance-specific render method is set.\n\n If *method* is ``None`` and this method is called via:\n\n - a class, the class-wide render method is unset, so that it uses that of\n its parent style class (if any) or the default.\n - an instance, the instance-specific render method is unset, so that it\n uses the class-wide render method thenceforth.\n\n Any instance without a render method set uses the class-wide render method.\n\n NOTE:\n *method* = ``None`` is always allowed, even if the render style doesn't\n implement multiple render methods.\n\n The **class-wide** render method is :term:`descendant`.\n \"\"\"\n if method is not None and not isinstance(method, str):\n raise arg_type_error(\"method\", method)\n if method is not None and method.lower() not in cls._render_methods:\n raise ValueError(f\"Unknown render method {method!r} for {cls.__name__}\")\n\n if not method:\n if cls._render_methods:\n cls._render_method = cls._default_render_method\n else:\n cls._render_method = method\n\n @set_render_method.instancemethod\n def set_render_method(self, method: Optional[str] = None) -> None:\n if method is not None and not isinstance(method, str):\n raise arg_type_error(\"method\", method)\n if method is not None and method.lower() not in type(self)._render_methods:\n raise ValueError(\n f\"Unknown render method {method!r} for {type(self).__name__}\"\n )\n\n if not method:\n try:\n del self._render_method\n except AttributeError:\n pass\n else:\n self._render_method = method\n\n def set_size(\n self,\n width: Union[int, Size, None] = None,\n height: Union[int, Size, None] = None,\n frame_size: Tuple[int, int] = (0, -2),\n ) -> None:\n \"\"\"Sets the image size (with extended control).\n\n Args:\n width: Can be\n\n * a positive integer; horizontal dimension of the image, in columns.\n * a :py:class:`~term_image.image.Size` enum member.\n\n height: Can be\n\n * a positive integer; vertical dimension of the image, in lines.\n * a :py:class:`~term_image.image.Size` enum member.\n\n frame_size: :term:`Frame size`, ``(columns, lines)``.\n If *columns* or *lines* is\n\n * positive, it is **absolute** and used as-is.\n * non-positive, it is **relative** to the corresponding terminal dimension\n and equivalent to the absolute dimension\n ``max(terminal_dimension + frame_dimension, 1)``.\n\n This is used only when neither *width* nor *height* is an ``int``.\n\n Raises:\n TypeError: An argument is of an inappropriate type.\n ValueError: An argument is of an appropriate type but has an\n unexpected/invalid value.\n\n * If both width and height are not ``None``, they must be positive integers\n and :term:`manual sizing` applies i.e the image size is set as given without\n preserving aspect ratio.\n * If *width* or *height* is a :py:class:`~term_image.image.Size` enum\n member, :term:`automatic sizing` applies as prescribed by the enum member.\n * If neither *width* nor *height* is given (or both are ``None``),\n :py:attr:`~term_image.image.Size.FIT` applies.\n \"\"\"\n width_height = (width, height)\n for arg_name, arg_value in zip((\"width\", \"height\"), width_height):\n if not (arg_value is None or isinstance(arg_value, (Size, int))):\n raise arg_type_error(arg_name, arg_value)\n if isinstance(arg_value, int) and arg_value <= 0:\n raise arg_value_error_range(arg_name, arg_value)\n\n if width is not None is not height:\n if not all(isinstance(x, int) for x in width_height):\n width_type = type(width).__name__\n height_type = type(height).__name__\n raise TypeError(\n \"Both 'width' and 'height' are specified but are not both integers \"\n f\"(got: ({width_type}, {height_type}))\"\n )\n\n self._size = width_height\n return\n\n if not (\n isinstance(frame_size, tuple)\n and all(isinstance(x, int) for x in frame_size)\n ):\n raise arg_type_error(\"frame_size\", frame_size)\n if not len(frame_size) == 2:\n raise arg_value_error(\"frame_size\", frame_size)\n\n self._size = self._valid_size(width, height, frame_size)\n\n def tell(self) -> int:\n \"\"\"Returns the current image frame number.\n\n :rtype: int\n \"\"\"\n return self._seek_position if self._is_animated else 0\n\n # Private Methods\n\n @classmethod\n def _check_format_spec(cls, spec: str) -> Tuple[\n str | None,\n int,\n str | None,\n int,\n Union[None, float, str],\n Dict[str, Any],\n ]:\n \"\"\"Validates a format specifier and translates it into the required values.\n\n Returns:\n A tuple ``(h_align, width, v_align, height, alpha, style_args)`` containing\n values as required by ``_format_render()`` and ``_render_image()``.\n \"\"\"\n match_ = _FORMAT_SPEC.fullmatch(spec)\n if not match_ or _NO_VERTICAL_SPEC.fullmatch(spec):\n raise arg_value_error_msg(\"Invalid format specifier\", spec)\n\n (\n _,\n h_align,\n width,\n _,\n v_align,\n height,\n alpha,\n threshold_or_bg,\n _,\n style_spec,\n ) = match_.groups()\n\n return (\n *cls._check_formatting(\n h_align,\n int(width) if width else 0,\n v_align,\n int(height) if height else -2,\n ),\n (\n threshold_or_bg\n and (\n \"#\" + threshold_or_bg.lstrip(\"#\")\n if _ALPHA_BG_FORMAT.fullmatch(\"#\" + threshold_or_bg.lstrip(\"#\"))\n else float(threshold_or_bg)\n )\n if alpha\n else _ALPHA_THRESHOLD\n ),\n style_spec and cls._check_style_format_spec(style_spec, style_spec) or {},\n )\n\n @staticmethod\n def _check_formatting(\n h_align: str | None = None,\n width: int = 0,\n v_align: str | None = None,\n height: int = -2,\n ) -> Tuple[str | None, int, str | None, int]:\n \"\"\"Validates and transforms formatting arguments.\n\n Returns:\n The respective arguments appropriate for ``_format_render()``.\n \"\"\"\n if not isinstance(h_align, (type(None), str)):\n raise arg_type_error(\"h_align\", h_align)\n if None is not h_align not in set(\"<|>\"):\n align = {\"left\": \"<\", \"center\": \"|\", \"right\": \">\"}.get(h_align)\n if not align:\n raise arg_value_error(\"h_align\", h_align)\n h_align = align\n\n if not isinstance(v_align, (type(None), str)):\n raise arg_type_error(\"v_align\", v_align)\n if None is not v_align not in set(\"^-_\"):\n align = {\"top\": \"^\", \"middle\": \"-\", \"bottom\": \"_\"}.get(v_align)\n if not align:\n raise arg_value_error(\"v_align\", v_align)\n v_align = align\n\n terminal_size = get_terminal_size()\n\n if not isinstance(width, int):\n raise arg_type_error(\"pad_width\", width)\n width = width if width > 0 else max(terminal_size.columns + width, 1)\n\n if not isinstance(height, int):\n raise arg_type_error(\"pad_height\", height)\n height = height if height > 0 else max(terminal_size.lines + height, 1)\n\n return h_align, width, v_align, height\n\n @classmethod\n def _check_style_args(cls, style_args: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"Validates style-specific arguments and translates them into the required\n values.\n\n Removes any argument having a value equal to the default.\n\n Returns:\n A mapping of keyword arguments.\n\n Raises:\n TypeError: An argument is of an inappropriate type.\n ValueError: An argument is of an appropriate type but has an\n unexpected/invalid value.\n term_image.exceptions.StyleError: An unknown style-specific parameter is\n given.\n \"\"\"\n for name, value in tuple(style_args.items()):\n try:\n (\n default,\n (check_type, type_msg),\n (check_value, value_msg),\n ) = cls._style_args[name]\n except KeyError:\n for other_cls in cls.__mro__:\n # less costly than membership tests on every class' __bases__\n if other_cls is __class__:\n raise StyleError(\n f\"Unknown style-specific render parameter {name!r} for \"\n f\"{cls.__name__!r}\"\n )\n\n if not issubclass(\n other_cls, __class__\n ) or \"_style_args\" not in vars(other_cls):\n continue\n\n try:\n (check_type, type_msg), (check_value, value_msg) = super(\n other_cls, cls\n )._style_args[name]\n break\n except KeyError:\n pass\n else:\n raise StyleError(\n f\"Unknown style-specific render parameter {name!r} for \"\n f\"{cls.__name__!r}\"\n )\n\n if not check_type(value):\n raise TypeError(f\"{type_msg} (got: {type(value).__name__})\")\n if not check_value(value):\n raise ValueError(f\"{value_msg} (got: {value!r})\")\n\n # Must not occur before type and value checks to avoid falling prey of\n # operator overloading\n if value == default:\n del style_args[name]\n\n return style_args\n\n @classmethod\n def _check_style_format_spec(cls, spec: str, original: str) -> Dict[str, Any]:\n \"\"\"Validates a style-specific format specifier and translates it into\n the required values.\n\n Returns:\n A mapping of keyword arguments.\n\n Raises:\n term_image.exceptions.StyleError: Invalid style-specific format specifier.\n\n **Every style-specific format spec should be handled as follows:**\n\n Every overriding method should call the overridden method (more on this below).\n At every step in the call chain, the specifier should be of the form::\n\n [parent] [current] [invalid]\n\n where:\n\n - *parent* is the portion to be interpreted at an higher level in the chain\n - *current* is the portion to be interpreted at the current level in the chain\n - the *invalid* portion determines the validity of the format spec\n\n Handle the portions in the order *invalid*, *parent*, *current*, so that\n validity can be determined before any further processing.\n\n At any point in the chain where the *invalid* portion exists (i.e is non-empty),\n the format spec can be correctly taken to be invalid.\n\n An overriding method must call the overridden method with the *parent* portion\n and the original format spec, **if** *parent* **is not empty**, such that every\n successful check ends up at `BaseImage._check_style_args()` or when *parent* is\n empty.\n\n :py:meth:`_get_style_format_spec` may be used to parse the format spec at each\n level of the call chain.\n \"\"\"\n if spec:\n raise StyleError(\n f\"Invalid style-specific format specifier {original!r} \"\n f\"for {cls.__name__!r}\"\n + (f\", detected at {spec!r}\" if spec != original else \"\")\n )\n return {}\n\n @classmethod\n def _clear_frame(cls) -> bool:\n \"\"\"Clears an animation frame on-screen.\n\n Called by :py:meth:`_display_animated` just before drawing a new frame.\n\n | Only required by styles wherein an image is not overwritten by another image\n e.g some graphics-based styles.\n | The base implementation does nothing and should be overridden only if\n required.\n\n Returns:\n ``True`` if the frame was cleared. Otherwise, ``False``.\n \"\"\"\n return False\n\n def _close_image(self, img: PIL.Image.Image) -> None:\n \"\"\"Closes the given PIL image instance if it isn't the instance' source.\"\"\"\n if img is not self._source:\n img.close()\n\n def _display_animated(\n self,\n img: PIL.Image.Image,\n alpha: Union[None, float, str],\n fmt: Tuple[str | None, int, str | None, int],\n repeat: int,\n cached: Union[bool, int],\n **style_args: Any,\n ) -> None:\n \"\"\"Displays an animated GIF image in the terminal.\"\"\"\n lines = max(fmt[-1], self.rendered_height)\n prev_seek_pos = self._seek_position\n duration = self._frame_duration\n image_it = ImageIterator(self, repeat, \"\", cached)\n image_it._animator = image_it._animate(img, alpha, fmt, style_args)\n cursor_up = CURSOR_UP % (lines - 1)\n cursor_down = CURSOR_DOWN % lines\n\n try:\n print(next(image_it._animator), end=\"\", flush=True) # First frame\n\n # Render next frame during current frame's duration\n start = time.time()\n for frame in image_it._animator: # Renders next frame\n # Left-over of current frame's duration\n time.sleep(max(0, duration - (time.time() - start)))\n\n # Clear the current frame, if necessary,\n # move cursor up to the beginning of the first line of the image\n # and print the new current frame.\n self._clear_frame()\n print(\"\\r\", cursor_up, frame, sep=\"\", end=\"\", flush=True)\n\n # Render next frame during current frame's duration\n start = time.time()\n except KeyboardInterrupt:\n self._handle_interrupted_draw()\n except Exception:\n self._handle_interrupted_draw()\n raise\n finally:\n image_it.close()\n self._close_image(img)\n self._seek_position = prev_seek_pos\n # Move the cursor to the last line of the image to prevent \"overlaid\"\n # output in the terminal\n print(cursor_down, end=\"\")\n\n def _format_render(\n self,\n render: str,\n h_align: str | None,\n width: int,\n v_align: str | None,\n height: int,\n ) -> str:\n \"\"\"Pads and aligns a primary :term:`render` output.\n\n NOTE:\n * All arguments should be passed through ``_check_formatting()`` first.\n * Only **absolute** padding dimensions are expected.\n \"\"\"\n cols, lines = self.rendered_size\n\n if width > cols:\n if h_align == \"<\": # left\n left = \"\"\n right = \" \" * (width - cols)\n elif h_align == \">\": # right\n left = \" \" * (width - cols)\n right = \"\"\n else: # center\n left = \" \" * ((width - cols) // 2)\n right = \" \" * (width - cols - len(left))\n render = render.replace(\"\\n\", f\"{right}\\n{left}\")\n else:\n left = right = \"\"\n\n if height > lines:\n if v_align == \"^\": # top\n top = 0\n bottom = height - lines\n elif v_align == \"_\": # bottom\n top = height - lines\n bottom = 0\n else: # middle\n top = (height - lines) // 2\n bottom = height - lines - top\n top = f\"{' ' * width}\\n\" * top\n bottom = f\"\\n{' ' * width}\" * bottom\n else:\n top = bottom = \"\"\n\n return (\n \"\".join((top, left, render, right, bottom))\n if width > cols or height > lines\n else render\n )\n\n @_close_validated\n def _get_image(self) -> PIL.Image.Image:\n \"\"\"Returns the PIL image instance corresponding to the image source as-is\"\"\"\n return (\n Image.open(self._source) if isinstance(self._source, str) else self._source\n )\n\n def _get_render_data(\n self,\n img: PIL.Image.Image,\n alpha: Union[None, float, str],\n *,\n size: Optional[Tuple[int, int]] = None,\n pixel_data: bool = True,\n round_alpha: bool = False,\n frame: bool = False,\n ) -> Tuple[\n PIL.Image.Image, Optional[List[Tuple[int, int, int]]], Optional[List[int]]\n ]:\n \"\"\"Returns the PIL image instance and pixel data required to render an image.\n\n Args:\n size: If given (in pixels), it is used instead of the pixel-equivalent of\n the image size.\n pixel_data: If ``False``, ``None`` is returned for all pixel data.\n round_alpha: Only applies when *alpha* is a ``float``.\n\n If ``True``, returned alpha values are bi-level (``0`` or ``255``), based\n on the given alpha threshold.\n Also, the image is blended with the active terminal's BG color (or black,\n if undetermined) while leaving the alpha intact.\n\n frame: If ``True``, implies *img* is being used by :py:class`ImageIterator`,\n hence, *img* is not closed.\n\n The returned image is appropriately converted, resized and composited\n (if need be).\n\n The pixel data are the last two items of the returned tuple ``(rgb, a)``, where:\n * ``rgb`` is a list of ``(r, g, b)`` tuples containing the colour channels of\n the image's pixels in a flattened row-major order where ``r``, ``g``, ``b``\n are integers in the range [0, 255].\n * ``a`` is a list of integers in the range [0, 255] representing the alpha\n channel of the image's pixels in a flattened row-major order.\n \"\"\"\n\n def convert_resize_img(mode: str):\n nonlocal img\n\n if img.mode != mode:\n prev_img = img\n try:\n img = img.convert(mode)\n # Possible for images in some modes e.g \"La\"\n except Exception as e:\n raise RenderError(\"Unable to convert image\") from e\n finally:\n if frame_img is not prev_img:\n self._close_image(prev_img)\n\n if img.size != size:\n prev_img = img\n try:\n img = img.resize(size, Image.Resampling.BOX)\n # Highly unlikely since render size can never be zero\n except Exception as e:\n raise RenderError(\"Unable to resize image\") from e\n finally:\n if frame_img is not prev_img:\n self._close_image(prev_img)\n\n frame_img = img if frame else None\n if self._is_animated:\n img.seek(self._seek_position)\n if not size:\n size = self._get_render_size()\n\n if alpha is None or img.mode in {\"1\", \"L\", \"RGB\", \"HSV\", \"CMYK\"}:\n convert_resize_img(\"RGB\")\n if pixel_data:\n rgb = list(img.getdata())\n a = [255] * mul(*size)\n else:\n convert_resize_img(\"RGBA\")\n if isinstance(alpha, str):\n if alpha == \"#\":\n alpha = get_fg_bg_colors(hex=True)[1] or \"#000000\"\n bg = Image.new(\"RGBA\", img.size, alpha)\n bg.alpha_composite(img)\n if frame_img is not img:\n self._close_image(img)\n img = bg.convert(\"RGB\")\n if pixel_data:\n a = [255] * mul(*size)\n else:\n if pixel_data:\n a = list(img.getdata(3))\n if round_alpha:\n alpha = round(alpha * 255)\n a = [0 if val < alpha else 255 for val in a]\n if round_alpha:\n bg = Image.new(\n \"RGBA\", img.size, get_fg_bg_colors(hex=True)[1] or \"#000000\"\n )\n bg.alpha_composite(img)\n bg.putalpha(img.getchannel(\"A\"))\n if frame_img is not img:\n self._close_image(img)\n img = bg\n\n if pixel_data:\n rgb = list((img if img.mode == \"RGB\" else img.convert(\"RGB\")).getdata())\n\n return (img, *(pixel_data and (rgb, a) or (None, None)))\n\n @abstractmethod\n def _get_render_size(self) -> Tuple[int, int]:\n \"\"\"Returns the size (in pixels) required to render the image.\"\"\"\n raise NotImplementedError\n\n @classmethod\n def _get_style_format_spec(\n cls, spec: str, original: str\n ) -> Tuple[str, List[Union[None, str, Tuple[Optional[str]]]]]:\n \"\"\"Parses a style-specific format specifier.\n\n See :py:meth:`_check_format_spec`.\n\n Returns:\n The *parent* portion and a list of matches for the respective fields of the\n *current* portion of the spec.\n\n * Any absent field of *current* is ``None``.\n * For a field containing groups, the match, if present, is a tuple\n containing the full match followed by the matches for each group.\n * All matches are in the same order as the fields (including their groups).\n\n Raises:\n term_image.exceptions.StyleError: The *invalid* portion exists.\n\n NOTE:\n Please avoid common fields in the format specs of parent and child classes\n (i.e fields that can match the same portion of a given string) as they\n result in ambiguities.\n \"\"\"\n patterns = iter(cls._FORMAT_SPEC)\n fields = []\n for pattern in patterns:\n match = pattern.search(spec)\n if match:\n fields.append(\n (match.group(), *match.groups())\n if pattern.groups\n else match.group()\n )\n start = match.start()\n end = match.end()\n break\n else:\n fields.append(\n (None,) * (pattern.groups + 1) if pattern.groups else None\n )\n else:\n start = end = len(spec)\n\n for pattern in patterns:\n match = pattern.match(spec, pos=end)\n if match:\n fields.append(\n (match.group(), *match.groups())\n if pattern.groups\n else match.group()\n )\n end = match.end()\n else:\n fields.append(\n (None,) * (pattern.groups + 1) if pattern.groups else None\n )\n\n parent, invalid = spec[:start], spec[end:]\n if invalid:\n raise StyleError(\n f\"Invalid style-specific format specifier {original!r} \"\n f\"for {cls.__name__!r}, detected at {invalid!r}\"\n )\n\n return parent, fields\n\n @staticmethod\n def _handle_interrupted_draw():\n \"\"\"Performs any necessary actions when image drawing is interrupted.\"\"\"\n\n @staticmethod\n @abstractmethod\n def _pixels_cols(\n *, pixels: Optional[int] = None, cols: Optional[int] = None\n ) -> int:\n \"\"\"Returns the number of pixels represented by a given number of columns\n or vice-versa.\n \"\"\"\n raise NotImplementedError\n\n @staticmethod\n @abstractmethod\n def _pixels_lines(\n *, pixels: Optional[int] = None, lines: Optional[int] = None\n ) -> int:\n \"\"\"Returns the number of pixels represented by a given number of lines\n or vice-versa.\n \"\"\"\n raise NotImplementedError\n\n @abstractmethod\n def _render_image(\n self,\n img: PIL.Image.Image,\n alpha: Union[None, float, str],\n *,\n frame: bool = False, # For `ImageIterator`\n ) -> str:\n \"\"\"Converts an image into a string which reproduces the image when printed\n to the terminal.\n\n NOTE:\n This method is not meant to be used directly, use it via `_renderer()`\n instead.\n \"\"\"\n raise NotImplementedError\n\n def _renderer(\n self,\n renderer: FunctionType,\n *args: Any,\n scroll: bool = False,\n check_size: bool = False,\n animated: bool = False,\n **kwargs,\n ) -> Any:\n \"\"\"Performs common render preparations and a rendering operation.\n\n Args:\n renderer: The function to perform the specific rendering operation for the\n caller of this method, ``_renderer()``.\n\n This function must accept at least one positional argument, the\n :py:class:`PIL.Image.Image` instance corresponding to the source.\n\n args: Positional arguments to pass on to *renderer*, after the\n :py:class:`PIL.Image.Image` instance.\n scroll: See *scroll* in :py:meth:`draw`.\n check_size: See *check_size* in :py:meth:`draw`.\n animated: If ``True``, *scroll* and *check_size* are ignored and the size\n is validated.\n kwargs: Keyword arguments to pass on to *renderer*.\n\n Returns:\n The return value of *renderer*.\n\n Raises:\n term_image.exceptions.InvalidSizeError: *check_size* or *animated* is\n ``True`` and the image's :term:`rendered size` can not fit into the\n :term:`terminal size`.\n term_image.exceptions.TermImageError: The image has been finalized.\n \"\"\"\n _size = self._size\n try:\n if isinstance(_size, Size):\n self.set_size(_size)\n elif check_size or animated:\n terminal_size = get_terminal_size()\n if any(\n map(\n gt,\n # The compared height will be 0 if *scroll* is `True`.\n # So, the height comparison will always be `False`\n # since the terminal height should never be < 0.\n map(mul, self.rendered_size, (1, not scroll)),\n terminal_size,\n )\n ):\n raise InvalidSizeError(\n \"The \"\n + (\"animation\" if animated else \"image\")\n + \" cannot fit into the terminal size\"\n )\n\n # Reaching here means it's either valid or *scroll* is `True`.\n if animated and self.rendered_height > terminal_size.lines:\n raise InvalidSizeError(\n \"The rendered height is greater than the terminal height for \"\n \"an animation\"\n )\n\n return renderer(self._get_image(), *args, **kwargs)\n\n finally:\n if isinstance(_size, Size):\n self.size = _size\n\n def _valid_size(\n self,\n width: Union[int, Size, None] = None,\n height: Union[int, Size, None] = None,\n frame_size: Tuple[int, int] = (0, -2),\n ) -> Tuple[int, int]:\n \"\"\"Returns an image size tuple.\n\n See :py:meth:`set_size` for the description of the parameters.\n \"\"\"\n ori_width, ori_height = self._original_size\n columns, lines = map(\n lambda frame_dim, terminal_dim: (\n frame_dim if frame_dim > 0 else max(terminal_dim + frame_dim, 1)\n ),\n frame_size,\n get_terminal_size(),\n )\n frame_width = self._pixels_cols(cols=columns)\n frame_height = self._pixels_lines(lines=lines)\n\n # As for cell ratio...\n #\n # Take for example, pixel ratio = 2.0\n # (i.e cell ratio = 1.0; square character cells).\n # To adjust the image to the proper scale, we either reduce the\n # width (i.e divide by 2.0) or increase the height (i.e multiply by 2.0).\n #\n # On the other hand, if the pixel ratio = 0.5\n # (i.e cell ratio = 0.25; vertically oblong character cells).\n # To adjust the image to the proper scale, we either increase the width\n # (i.e divide by the 0.5) or reduce the height (i.e multiply by the 0.5).\n #\n # Therefore, for the height, we always multiply by the pixel ratio\n # and for the width, we always divide by the pixel ratio.\n # The non-constraining axis is always the one directly adjusted.\n\n if all(not isinstance(x, int) for x in (width, height)):\n if Size.AUTO in (width, height):\n width = height = (\n Size.FIT\n if (\n ori_width > frame_width\n or round(ori_height * self._pixel_ratio) > frame_height\n )\n else Size.ORIGINAL\n )\n elif Size.FIT_TO_WIDTH in (width, height):\n return (\n self._pixels_cols(pixels=frame_width) or 1,\n self._pixels_lines(\n pixels=round(\n self._width_height_px(w=frame_width) * self._pixel_ratio\n )\n )\n or 1,\n )\n\n if Size.ORIGINAL in (width, height):\n return (\n self._pixels_cols(pixels=ori_width) or 1,\n self._pixels_lines(pixels=round(ori_height * self._pixel_ratio))\n or 1,\n )\n\n # The smaller fraction will fit on both axis.\n # Hence, the axis with the smaller ratio is the constraining axis.\n # Constraining by the axis with the larger ratio will cause the image\n # to not fit into the axis with the smaller ratio.\n width_ratio = frame_width / ori_width\n height_ratio = frame_height / ori_height\n smaller_ratio = min(width_ratio, height_ratio)\n\n # Set the dimension on the constraining axis to exactly its corresponding\n # frame dimension and the dimension on the other axis to the same ratio of\n # its corresponding original image dimension\n _width_px = ori_width * smaller_ratio\n _height_px = ori_height * smaller_ratio\n\n # The cell ratio should directly affect the non-constraining axis since the\n # constraining axis is already fully occupied at this point\n if height_ratio > width_ratio:\n _height_px = _height_px * self._pixel_ratio\n # If height becomes greater than the max, reduce it to the max\n height_px = min(_height_px, frame_height)\n # Calculate the corresponding width\n width_px = round((height_px / _height_px) * _width_px)\n # Round the height\n height_px = round(height_px)\n else:\n _width_px = _width_px / self._pixel_ratio\n # If width becomes greater than the max, reduce it to the max\n width_px = min(_width_px, frame_width)\n # Calculate the corresponding height\n height_px = round((width_px / _width_px) * _height_px)\n # Round the width\n width_px = round(width_px)\n return (\n self._pixels_cols(pixels=width_px) or 1,\n self._pixels_lines(pixels=height_px) or 1,\n )\n elif width is None:\n width_px = round(\n self._width_height_px(h=self._pixels_lines(lines=height))\n / self._pixel_ratio\n )\n width = self._pixels_cols(pixels=width_px)\n elif height is None:\n height_px = round(\n self._width_height_px(w=self._pixels_cols(cols=width))\n * self._pixel_ratio\n )\n height = self._pixels_lines(pixels=height_px)\n\n return (width or 1, height or 1)\n\n def _width_height_px(\n self, *, w: Optional[int] = None, h: Optional[int] = None\n ) -> float:\n \"\"\"Converts the given width (in pixels) to the **unrounded** proportional height\n (in pixels) OR vice-versa.\n \"\"\"\n ori_width, ori_height = self._original_size\n return (\n (w / ori_width) * ori_height\n if w is not None\n else (h / ori_height) * ori_width\n )\n\n\n# Source: src/term_image/image/__init__.py\ndef from_file(\n filepath: Union[str, os.PathLike],\n **kwargs: Union[None, int],\n) -> BaseImage:\n \"\"\"Creates an image instance from an image file.\n\n Returns:\n An instance of the automatically selected image render style (as returned by\n :py:func:`auto_image_class`).\n\n Same arguments and raised exceptions as :py:meth:`BaseImage.from_file`.\n \"\"\"\n return auto_image_class().from_file(filepath, **kwargs)", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 61527}, "tests/widget/urwid/test_screen.py::440": {"resolved_imports": ["src/term_image/__init__.py", "src/term_image/_ctlseqs.py", "src/term_image/image/block.py", "src/term_image/image/iterm2.py", "src/term_image/image/kitty.py", "src/term_image/widget/_urwid.py"], "used_names": ["get_terminal_name_version", "set_terminal_name_version"], "enclosing_function": "test_change_top_widget", "extracted_code": "", "n_imports_parsed": 10, "n_files_resolved": 6, "n_chars_extracted": 0}, "tests/test_image/test_base.py::96": {"resolved_imports": ["src/term_image/__init__.py", "src/term_image/_ctlseqs.py", "src/term_image/exceptions.py", "src/term_image/image/block.py", "src/term_image/image/common.py"], "used_names": ["BlockImage"], "enclosing_function": "test_init_animated", "extracted_code": "# Source: src/term_image/image/block.py\nclass BlockImage(TextImage):\n \"\"\"A render style using unicode half blocks and direct-color colour escape\n sequences.\n\n See :py:class:`TextImage` for the description of the constructor.\n \"\"\"\n\n @classmethod\n def is_supported(cls):\n if cls._supported is None:\n COLORTERM = os.environ.get(\"COLORTERM\") or \"\"\n TERM = os.environ.get(\"TERM\") or \"\"\n cls._supported = (\n \"truecolor\" in COLORTERM or \"24bit\" in COLORTERM or \"256color\" in TERM\n )\n\n return cls._supported\n\n def _get_render_size(self) -> Tuple[int, int]:\n return tuple(map(mul, self.rendered_size, (1, 2)))\n\n @staticmethod\n def _pixels_cols(\n *, pixels: Optional[int] = None, cols: Optional[int] = None\n ) -> int:\n return pixels if pixels is not None else cols\n\n @staticmethod\n def _pixels_lines(\n *, pixels: Optional[int] = None, lines: Optional[int] = None\n ) -> int:\n return ceil(pixels / 2) if pixels is not None else lines * 2\n\n def _render_image(\n self,\n img: PIL.Image.Image,\n alpha: Union[None, float, str],\n *,\n frame: bool = False,\n split_cells: bool = False,\n ) -> str:\n # NOTE:\n # It's more efficient to write separate strings to the buffer separately\n # than concatenate and write together.\n\n def update_buffer():\n if alpha:\n no_alpha = False\n if a_cluster1 == 0 == a_cluster2:\n buf_write(SGR_DEFAULT)\n buf_write(blank * n)\n elif a_cluster1 == 0: # up is transparent\n buf_write(SGR_DEFAULT)\n buf_write(SGR_FG_DIRECT % cluster2)\n buf_write(lower_pixel * n)\n elif a_cluster2 == 0: # down is transparent\n buf_write(SGR_DEFAULT)\n buf_write(SGR_FG_DIRECT % cluster1)\n buf_write(upper_pixel * n)\n else:\n no_alpha = True\n\n if not alpha or no_alpha:\n r, g, b = cluster2\n # Kitty does not render BG colors equal to the default BG color\n if is_on_kitty and cluster2 == bg_color:\n r += r < 255 or -1\n buf_write(SGR_BG_DIRECT % (r, g, b))\n if cluster1 == cluster2:\n buf_write(blank * n)\n else:\n buf_write(SGR_FG_DIRECT % cluster1)\n buf_write(upper_pixel * n)\n\n buffer = io.StringIO()\n buf_write = buffer.write # Eliminate attribute resolution cost\n\n bg_color = get_fg_bg_colors()[1]\n is_on_kitty = self._is_on_kitty()\n if split_cells:\n blank = \" \\0\"\n lower_pixel = LOWER_PIXEL + \"\\0\"\n upper_pixel = UPPER_PIXEL + \"\\0\"\n else:\n blank = \" \"\n lower_pixel = LOWER_PIXEL\n upper_pixel = UPPER_PIXEL\n end_of_line = SGR_DEFAULT + \"\\n\"\n\n width, height = self._get_render_size()\n frame_img = img if frame else None\n img, rgb, a = self._get_render_data(img, alpha, round_alpha=True, frame=frame)\n alpha = img.mode == \"RGBA\"\n\n # clean up (ImageIterator uses one PIL image throughout)\n if frame_img is not img:\n self._close_image(img)\n\n rgb_pairs = (\n (\n zip(rgb[x : x + width], rgb[x + width : x + width * 2]),\n (rgb[x], rgb[x + width]),\n )\n for x in range(0, len(rgb), width * 2)\n )\n a_pairs = (\n (\n zip(a[x : x + width], a[x + width : x + width * 2]),\n (a[x], a[x + width]),\n )\n for x in range(0, len(a), width * 2)\n )\n\n row_no = 0\n # Two rows of pixels per line\n for (rgb_pair, (cluster1, cluster2)), (a_pair, (a_cluster1, a_cluster2)) in zip(\n rgb_pairs, a_pairs\n ):\n row_no += 2\n n = 0\n for (px1, px2), (a1, a2) in zip(rgb_pair, a_pair):\n # Color-code characters and write to buffer\n # when upper and/or lower pixel color/alpha-level changes\n if not (alpha and a1 == a_cluster1 == 0 == a_cluster2 == a2) and (\n px1 != cluster1\n or px2 != cluster2\n or alpha\n and (\n # From non-transparent to transparent\n a_cluster1 != a1 == 0\n or a_cluster2 != a2 == 0\n # From transparent to non-transparent\n or 0 == a_cluster1 != a1\n or 0 == a_cluster2 != a2\n )\n ):\n update_buffer()\n cluster1 = px1\n cluster2 = px2\n if alpha:\n a_cluster1 = a1\n a_cluster2 = a2\n n = 0\n n += 1\n\n update_buffer() # Rest of the line\n if split_cells:\n # Set the last \"\\0\" to be overwritten by the next byte\n buffer.seek(buffer.tell() - 1)\n if row_no < height: # last line not yet rendered\n buf_write(end_of_line)\n\n buf_write(SGR_DEFAULT) # Reset color after last line\n\n with buffer:\n return buffer.getvalue()", "n_imports_parsed": 16, "n_files_resolved": 5, "n_chars_extracted": 5566}, "tests/test_image/test_kitty.py::681": {"resolved_imports": ["src/term_image/__init__.py", "src/term_image/_ctlseqs.py", "src/term_image/exceptions.py", "src/term_image/image/__init__.py", "src/term_image/image/kitty.py"], "used_names": ["KittyImage"], "enclosing_function": "test_z_index", "extracted_code": "", "n_imports_parsed": 12, "n_files_resolved": 5, "n_chars_extracted": 0}, "tests/widget/urwid/test_main.py::347": {"resolved_imports": ["src/term_image/__init__.py", "src/term_image/_ctlseqs.py", "src/term_image/exceptions.py", "src/term_image/image/block.py", "src/term_image/image/common.py", "src/term_image/image/iterm2.py", "src/term_image/image/kitty.py", "src/term_image/widget/_urwid.py"], "used_names": ["UrwidImage", "gc"], "enclosing_function": "test_use_freed", "extracted_code": "# Source: src/term_image/widget/_urwid.py\nclass UrwidImage(urwid.Widget):\n \"\"\"Image widget (box/flow) for the urwid TUI framework.\n\n Args:\n image: The image to be rendered by the widget.\n format_spec: :ref:`Render format specifier `. Padding width and\n height are ignored.\n upscale: If ``True``, the image will be upscaled to fit maximally within the\n available size, if necessary, while still preserving the aspect ratio.\n Otherwise, the image is never upscaled.\n\n Raises:\n TypeError: An argument is of an inappropriate type.\n ValueError: An argument is of an appropriate type but has an\n unexpected/invalid value.\n term_image.exceptions.StyleError: Invalid style-specific format specifier.\n term_image.exceptions.UrwidImageError: Too many image widgets rendering images\n with the *kitty* render style.\n\n | Any ample space in the widget's render size is filled with spaces.\n | For animated images, the current frame (at render-time) is rendered.\n\n TIP:\n If *image* is of a :ref:`graphics-based ` render style and the\n widget is being used as or within a **flow** widget, with overlays or in any\n other case where the canvas will require vertical trimming, make sure to use a\n render method that splits images across lines such as the **LINES** render\n method for *kitty* and *iterm2* render styles.\n\n NOTE:\n * The `z-index` style-specific format spec field for\n :py:class:`~term_image.image.KittyImage` is ignored as this is used\n internally.\n * A **maximum** of ``2**32 - 2`` instances initialized with\n :py:class:`~term_image.image.KittyImage` instances may exist at the same time.\n\n IMPORTANT:\n This is defined if and only if the ``urwid`` package is available.\n \"\"\"\n\n _sizing = frozenset((urwid.BOX, urwid.FLOW))\n ignore_focus = True\n\n _ti_error_placeholder = None\n\n # For kitty images\n _ti_disguise_state = 0\n _ti_free_z_indexes = set()\n\n # Progresses thus: 1, -1, 2, -2, 3, ..., 2**31 - 1, -(2**31 - 1)\n # This sequence results in shorter image escape sequences compared to starting\n # from -(2**31)\n _ti_next_z_index = 1\n\n def __init__(\n self, image: BaseImage, format_spec: str = \"\", *, upscale: bool = False\n ) -> None:\n if not isinstance(image, BaseImage):\n raise arg_type_error(\"image\", image)\n\n if not isinstance(format_spec, str):\n raise arg_type_error(\"format_spec\", format_spec)\n *fmt, alpha, style_args = image._check_format_spec(format_spec)\n\n if not isinstance(upscale, bool):\n raise arg_type_error(\"upscale\", upscale)\n\n super().__init__()\n self._ti_image = image\n self._ti_h_align, _, self._ti_v_align, _ = fmt\n self._ti_alpha = alpha\n self._ti_style_args = style_args\n self._ti_sizing = Size.FIT if upscale else Size.AUTO\n\n if isinstance(image, TextImage):\n style_args[\"split_cells\"] = True\n elif isinstance(image, KittyImage):\n style_args[\"z_index\"] = self._ti_z_index = self._ti_get_z_index()\n\n # Since Konsole doesn't blend images placed at the same location and\n # z-index, unlike Kitty (and potentially others), `blend=True` is\n # better on Konsole as it reduces/eliminates flicker.\n if get_terminal_name_version()[0] != \"konsole\":\n # To clear directly overlapped images when urwid redraws a line without\n # a change in image position\n style_args[\"blend\"] = False\n\n def __del__(self) -> None:\n if hasattr(self, \"_ti_z_index\"):\n __class__._ti_free_z_indexes.add(self._ti_z_index)\n\n image = property(\n lambda self: self._ti_image,\n doc=\"\"\"\n The image rendered by the widget\n\n :type: BaseImage\n\n GET:\n Returns the image instance rendered by the widget.\n \"\"\",\n )\n\n def render(self, size: Tuple[int, int], focus: bool = False) -> urwid.Canvas:\n image = self._ti_image\n\n if len(size) == 2: # box\n image.set_size(self._ti_sizing, frame_size=size)\n elif len(size) == 1: # flow\n if self._ti_sizing is Size.FIT:\n image.set_size(size[0])\n else:\n fit_size = self._ti_image._valid_size(size[0])\n ori_size = self._ti_image._valid_size(Size.ORIGINAL)\n image._size = (\n ori_size\n if ori_size[0] <= fit_size[0] and ori_size[1] <= fit_size[1]\n else fit_size\n )\n size = (size[0], image._size[1])\n else: # fixed\n raise UrwidImageError(\"Not a fixed widget\")\n\n try:\n render = image._format_render(\n image._renderer(\n image._render_image, self._ti_alpha, **self._ti_style_args\n ),\n self._ti_h_align,\n size[0],\n self._ti_v_align,\n size[1],\n )\n except Exception:\n if type(self)._ti_error_placeholder is None:\n raise\n canv = type(self)._ti_error_placeholder.render(size, focus)\n else:\n canv = UrwidImageCanvas(render, size, image._size)\n\n return canv\n\n def rows(self, size: Tuple[int], focus: bool = False) -> int:\n fit_size = self._ti_image._valid_size(size[0])\n if self._ti_sizing is Size.FIT:\n n_rows = fit_size[1]\n else:\n ori_size = self._ti_image._valid_size(Size.ORIGINAL)\n n_rows = (\n ori_size[1]\n if ori_size[0] <= fit_size[0] and ori_size[1] <= fit_size[1]\n else fit_size[1]\n )\n\n return n_rows\n\n @classmethod\n def set_error_placeholder(cls, widget: Optional[urwid.Widget]) -> None:\n \"\"\"Sets the widget to be rendered in place of an image when rendering fails.\n\n Args:\n widget: The placeholder widget or ``None`` to remove the placeholder.\n\n Raises:\n TypeError: *widget* is not an urwid widget.\n\n If set, any exception raised during rendering is **suppressed** and the\n placeholder is rendered in place of the image.\n \"\"\"\n if not isinstance(widget, urwid.Widget):\n raise arg_type_error(\"widget\", widget)\n\n cls._ti_error_placeholder = widget\n\n @staticmethod\n def _ti_get_z_index() -> int:\n if __class__._ti_free_z_indexes:\n return __class__._ti_free_z_indexes.pop()\n\n z_index = __class__._ti_next_z_index\n if z_index == 2**31:\n raise UrwidImageError(\"Too many image widgets with the kitty render style\")\n __class__._ti_next_z_index = -z_index if z_index > 0 else -z_index + 1\n\n return z_index\n\n def _ti_change_disguise(self) -> None:\n \"\"\"See :py:meth`UrwidImageCanvas._ti_change_disguise`.\"\"\"\n self._ti_disguise_state = (self._ti_disguise_state + 1) % 3", "n_imports_parsed": 10, "n_files_resolved": 8, "n_chars_extracted": 7167}, "tests/renderable/test_types.py::519": {"resolved_imports": ["src/term_image/geometry.py", "src/term_image/renderable/_renderable.py", "src/term_image/renderable/_types.py"], "used_names": ["RenderArgs"], "enclosing_function": "test_unsupported", "extracted_code": "# Source: src/term_image/renderable/_types.py\nclass RenderArgs(RenderArgsData):\n \"\"\"RenderArgs(render_cls, /, *namespaces)\n RenderArgs(render_cls, init_render_args, /, *namespaces)\n\n Render arguments.\n\n Args:\n render_cls: A :term:`render class`.\n init_render_args (RenderArgs | None): A set of render arguments.\n If not ``None``,\n\n * it must be compatible [#ra-com]_ with *render_cls*,\n * it'll be used to initialize the render arguments.\n\n namespaces: Render argument namespaces compatible [#an-com]_ with *render_cls*.\n\n .. note:: If multiple namespaces associated with the same :term:`render\n class` are given, the last of them takes precedence.\n\n Raises:\n IncompatibleRenderArgsError: *init_render_args* is incompatible [#ra-com]_ with\n *render_cls*.\n IncompatibleArgsNamespaceError: Incompatible [#an-com]_ render argument\n namespace.\n\n A set of render arguments (an instance of this class) is basically a container of\n render argument namespaces (instances of\n :py:class:`~term_image.renderable.ArgsNamespace`); one for\n each :term:`render class`, which has render arguments, in the Method Resolution\n Order of its associated [#ra-ass]_ render class.\n\n The namespace for each render class is derived from the following sources, in\n [descending] order of precedence:\n\n * *namespaces*\n * *init_render_args*\n * default render argument namespaces\n\n NOTE:\n Instances are immutable but updated copies can be created via :py:meth:`update`.\n\n .. seealso::\n\n :py:attr:`~term_image.renderable.Renderable.Args`\n Render class-specific render arguments.\n\n .. Completed in /docs/source/api/renderable.rst\n \"\"\"\n\n # Class Attributes =========================================================\n\n __slots__ = ()\n\n _interned: ClassVar[dict[type[Renderable], Self]] = {}\n _namespaces: MappingProxyType[type[Renderable], ArgsNamespace]\n\n # Instance Attributes ======================================================\n\n render_cls: type[Renderable]\n \"\"\"The associated :term:`render class`\"\"\"\n\n # Special Methods ==========================================================\n\n def __new__(\n cls,\n render_cls: type[Renderable],\n init_or_namespace: RenderArgs | ArgsNamespace | None = None,\n *namespaces: ArgsNamespace,\n ) -> Self:\n if init_or_namespace is None:\n init_render_args = None\n elif isinstance(init_or_namespace, RenderArgs):\n init_render_args = init_or_namespace\n else:\n init_render_args = None\n namespaces = (init_or_namespace, *namespaces)\n\n if init_render_args and not issubclass(render_cls, init_render_args.render_cls):\n raise IncompatibleRenderArgsError(\n f\"'init_render_args' (associated with \"\n f\"{init_render_args.render_cls.__name__!r}) is incompatible with \"\n f\"{render_cls.__name__!r} \"\n )\n\n if not namespaces:\n # has default namespaces only\n if (\n not init_render_args\n or init_render_args is BASE_RENDER_ARGS\n or cls._interned.get(init_render_args.render_cls) is init_render_args\n ):\n try:\n return cls._interned[render_cls]\n except KeyError:\n pass\n\n if (\n init_render_args\n and type(init_render_args) is cls\n and init_render_args.render_cls is render_cls\n ):\n return init_render_args\n\n return super().__new__(cls)\n\n def __init__(\n self,\n render_cls: type[Renderable],\n init_or_namespace: RenderArgs | ArgsNamespace | None = None,\n *namespaces: ArgsNamespace,\n ) -> None:\n if init_or_namespace is None:\n init_render_args = None\n elif isinstance(init_or_namespace, RenderArgs):\n init_render_args = init_or_namespace\n else:\n init_render_args = None\n namespaces = (init_or_namespace, *namespaces)\n\n # has default namespaces only\n if not namespaces and (\n not init_render_args\n or init_render_args is BASE_RENDER_ARGS\n or (\n type(self)._interned.get(init_render_args.render_cls)\n is init_render_args\n )\n ):\n if render_cls in type(self)._interned: # has been initialized\n return\n intern = True\n else:\n intern = False\n\n if init_render_args is self:\n return\n\n namespaces_dict = render_cls._ALL_DEFAULT_ARGS.copy()\n\n # if `init_render_args` is non-default\n if init_render_args and BASE_RENDER_ARGS is not init_render_args is not (\n type(self)._interned.get(init_render_args.render_cls)\n ):\n namespaces_dict.update(init_render_args._namespaces)\n\n for index, namespace in enumerate(namespaces):\n if namespace._RENDER_CLS not in namespaces_dict:\n raise IncompatibleArgsNamespaceError(\n f\"'namespaces[{index}]' (associated with \"\n f\"{namespace._RENDER_CLS.__name__!r}) is incompatible with \"\n f\"{render_cls.__name__!r} \"\n )\n namespaces_dict[namespace._RENDER_CLS] = namespace\n\n super().__init__(render_cls, namespaces_dict)\n\n if intern:\n type(self)._interned[render_cls] = self\n\n def __init_subclass__(cls, **kwargs: Any) -> None:\n cls._interned = {}\n super().__init_subclass__(**kwargs)\n\n def __contains__(self, namespace: ArgsNamespace) -> bool:\n \"\"\"Checks if a render argument namespace is contained in this set of render\n arguments.\n\n Args:\n namespace: A render argument namespace.\n\n Returns:\n ``True`` if the given namespace is equal to any of the namespaces\n contained in this set of render arguments. Otherwise, ``False``.\n \"\"\"\n return None is not self._namespaces.get(namespace._RENDER_CLS) == namespace\n\n def __eq__(self, other: object) -> bool:\n \"\"\"Compares this set of render arguments with another.\n\n Args:\n other: Another set of render arguments.\n\n Returns:\n ``True`` if both are associated with the same :term:`render class`\n and have equal argument values. Otherwise, ``False``.\n \"\"\"\n if isinstance(other, RenderArgs):\n return (\n self is other\n or self.render_cls is other.render_cls\n and self._namespaces == other._namespaces\n )\n\n return NotImplemented\n\n def __getitem__(self, render_cls: type[Renderable]) -> Any:\n \"\"\"Returns a constituent namespace.\n\n Args:\n render_cls: A :term:`render class` of which :py:attr:`render_cls` is a\n subclass (which may be :py:attr:`render_cls` itself) and which has\n render arguments.\n\n Returns:\n The constituent namespace associated with *render_cls*.\n\n Raises:\n TypeError: *render_cls* is not a render class.\n ValueError: :py:attr:`render_cls` is not a subclass of *render_cls*.\n NoArgsNamespaceError: *render_cls* has no render arguments.\n\n NOTE:\n The return type hint is :py:class:`~typing.Any` only for compatibility\n with static type checking, as this aspect of the interface seems too\n dynamic to be correctly expressed with the exisiting type system.\n\n Regardless, the return value is guaranteed to always be an instance\n of a render argument namespace class associated with *render_cls*.\n For instance, the following would always be valid for\n :py:class:`~term_image.renderable.Renderable`::\n\n renderable_args: RenderableArgs = render_args[Renderable]\n\n and similar idioms are encouraged to be used for other render classes.\n \"\"\"\n try:\n return self._namespaces[render_cls]\n except TypeError:\n raise arg_type_error(\"render_cls\", render_cls) from None\n except KeyError:\n if not isinstance(render_cls, RenderableMeta):\n raise arg_type_error(\"render_cls\", render_cls) from None\n\n if issubclass(self.render_cls, render_cls):\n raise NoArgsNamespaceError(\n f\"{render_cls.__name__!r} has no render arguments\"\n ) from None\n\n raise ValueError(\n f\"{self.render_cls.__name__!r} is not a subclass of \"\n f\"{render_cls.__name__!r}\"\n ) from None\n\n def __hash__(self) -> int:\n \"\"\"Computes the hash of the render arguments.\n\n Returns:\n The computed hash.\n\n IMPORTANT:\n Like tuples, an instance is hashable if and only if the constituent\n namespaces are hashable.\n \"\"\"\n # Namespaces are always in the same order, wrt their respective associated\n # render classes, for all instances associated with the same render class.\n return hash((self.render_cls, tuple(self._namespaces.values())))\n\n def __iter__(self) -> Iterator[ArgsNamespace]:\n \"\"\"Returns an iterator that yields the constituent namespaces.\n\n Returns:\n An iterator that yields the constituent namespaces.\n\n WARNING:\n The number and order of namespaces is guaranteed to be the same across all\n instances associated [#ra-ass]_ with the same :term:`render class` but\n beyond this, should not be relied upon as the details (such as the\n specific number or order) may change without notice.\n\n The order is an implementation detail of the Renderable API and the number\n should be considered alike with respect to the associated render class.\n \"\"\"\n return iter(self._namespaces.values())\n\n def __repr__(self) -> str:\n return \"\".join(\n (\n f\"{type(self).__name__}({self.render_cls.__name__}\",\n \", \" if self._namespaces else \"\",\n \", \".join(map(repr, self._namespaces.values())),\n \")\",\n )\n )\n\n # Public Methods ===========================================================\n\n def convert(self, render_cls: type[Renderable]) -> RenderArgs:\n \"\"\"Converts the set of render arguments to one for a related render class.\n\n Args:\n render_cls: A :term:`render class` of which :py:attr:`render_cls` is a\n parent or child (which may be :py:attr:`render_cls` itself).\n\n Returns:\n A set of render arguments associated [#ra-ass]_ with *render_cls* and\n initialized with all constituent namespaces (of this set of render\n arguments, *self*) that are compatible [#an-com]_ with *render_cls*.\n\n Raises:\n ValueError: *render_cls* is not a parent or child of :py:attr:`render_cls`.\n \"\"\"\n if render_cls is self.render_cls:\n return self\n\n if issubclass(render_cls, self.render_cls):\n return RenderArgs(render_cls, self)\n\n if issubclass(self.render_cls, render_cls):\n render_cls_args_mro = render_cls._ALL_DEFAULT_ARGS\n return RenderArgs(\n render_cls,\n *[\n namespace\n for cls, namespace in self._namespaces.items()\n if cls in render_cls_args_mro\n ],\n )\n\n raise ValueError(\n f\"{render_cls.__name__!r} is not a parent or child of \"\n f\"{self.render_cls.__name__!r}\"\n )\n\n @overload\n def update(\n self,\n namespace: ArgsNamespace,\n /,\n *namespaces: ArgsNamespace,\n ) -> RenderArgs: ...\n\n @overload\n def update(\n self,\n render_cls: type[Renderable],\n /,\n **fields: Any,\n ) -> RenderArgs: ...\n\n def update(\n self,\n render_cls_or_namespace: type[Renderable] | ArgsNamespace,\n /,\n *namespaces: ArgsNamespace,\n **fields: Any,\n ) -> RenderArgs:\n \"\"\"update(namespace, /, *namespaces) -> RenderArgs\n update(render_cls, /, **fields) -> RenderArgs\n\n Replaces or updates render argument namespaces.\n\n Args:\n namespace (ArgsNamespace): Prepended to *namespaces*.\n namespaces: Render argument namespaces compatible [#an-com]_ with\n :py:attr:`render_cls`.\n\n .. note:: If multiple namespaces associated with the same :term:`render\n class` are given, the last of them takes precedence.\n\n render_cls (type[Renderable]): A :term:`render class` of which\n :py:attr:`render_cls` is a subclass (which may be :py:attr:`render_cls`\n itself) and which has render arguments.\n fields: Render argument fields.\n\n The keywords must be names of render argument fields for *render_cls*.\n\n Returns:\n For the **first** form, an instance with the namespaces for the respective\n associated :term:`render classes` of the given namespaces replaced.\n\n For the **second** form, an instance with the given render argument fields\n for *render_cls* updated, if any.\n\n Raises:\n TypeError: The arguments given do not conform to any of the expected forms.\n\n Propagates exceptions raised by:\n\n * the class constructor, for the **first** form.\n * :py:meth:`__getitem__` and :py:meth:`ArgsNamespace.update()\n `, for the **second** form.\n \"\"\"\n if isinstance(render_cls_or_namespace, RenderableMeta):\n if namespaces:\n raise TypeError(\n \"No other positional argument is expected when the first argument \"\n \"is a render class\"\n )\n render_cls = render_cls_or_namespace\n else:\n if fields:\n raise TypeError(\n \"No keyword argument is expected when the first argument is \"\n \"a render argument namespace\"\n )\n render_cls = None\n namespaces = (render_cls_or_namespace, *namespaces)\n\n return RenderArgs(\n self.render_cls,\n self,\n *((self[render_cls].update(**fields),) if render_cls else namespaces),\n )", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 14805}, "tests/test_image/test_block.py::46": {"resolved_imports": ["src/term_image/_ctlseqs.py", "src/term_image/image/block.py", "src/term_image/image/common.py"], "used_names": ["SGR_BG_DIRECT", "SGR_DEFAULT", "_ALPHA_THRESHOLD"], "enclosing_function": "test_transparency", "extracted_code": "# Source: src/term_image/_ctlseqs.py\nSGR_BG_DIRECT = SGR % f\"48;2;{Pm(3)}\"\n\nSGR_DEFAULT = SGR % \"\"\n\n\n# Source: src/term_image/image/common.py\n_ALPHA_THRESHOLD = 40 / 255", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 169}, "tests/test_image/common.py::345": {"resolved_imports": ["src/term_image/__init__.py", "src/term_image/_ctlseqs.py", "src/term_image/exceptions.py", "src/term_image/image/common.py", "src/term_image/utils.py"], "used_names": [], "enclosing_function": "test_int_width", "extracted_code": "", "n_imports_parsed": 11, "n_files_resolved": 5, "n_chars_extracted": 0}, "tests/test_image/test_kitty.py::136": {"resolved_imports": ["src/term_image/__init__.py", "src/term_image/_ctlseqs.py", "src/term_image/exceptions.py", "src/term_image/image/__init__.py", "src/term_image/image/kitty.py"], "used_names": ["KittyImage", "pytest"], "enclosing_function": "test_z_index", "extracted_code": "", "n_imports_parsed": 12, "n_files_resolved": 5, "n_chars_extracted": 0}, "tests/renderable/test_renderable.py::1028": {"resolved_imports": ["src/term_image/_ctlseqs.py", "src/term_image/geometry.py", "src/term_image/padding.py", "src/term_image/renderable/_enum.py", "src/term_image/renderable/_exceptions.py", "src/term_image/renderable/_renderable.py", "src/term_image/renderable/_types.py"], "used_names": ["ExactPadding", "RenderArgs", "sys"], "enclosing_function": "test_non_default", "extracted_code": "# Source: src/term_image/padding.py\nclass ExactPadding(Padding):\n \"\"\"Exact :term:`render output` padding.\n\n Args:\n left: Left padding dimension\n top: Top padding dimension.\n right: Right padding dimension\n bottom: Bottom padding dimension\n\n Raises:\n ValueError: A dimension is negative.\n\n Pads a render output on each side by the specified amount of lines or columns.\n\n TIP:\n * Instances are immutable and hashable.\n * Instances with equal fields compare equal.\n \"\"\"\n\n # Class Attributes =========================================================\n\n __slots__ = (\"left\", \"top\", \"right\", \"bottom\")\n\n # Instance Attributes ======================================================\n\n left: int\n \"\"\"Left padding dimension\"\"\"\n\n top: int\n \"\"\"Top padding dimension\"\"\"\n\n right: int\n \"\"\"Right padding dimension\"\"\"\n\n bottom: int\n \"\"\"Bottom padding dimension\"\"\"\n\n fill: str\n\n # Special Methods ==========================================================\n\n def __init__(\n self,\n left: int = 0,\n top: int = 0,\n right: int = 0,\n bottom: int = 0,\n fill: str = \" \",\n ) -> None:\n super().__init__(fill)\n\n _setattr = super().__setattr__\n for name in (\"left\", \"top\", \"right\", \"bottom\"):\n value = locals()[name]\n if value < 0:\n raise arg_value_error_range(name, value)\n _setattr(name, value)\n\n # Properties ===============================================================\n\n @property\n def dimensions(self) -> tuple[int, int, int, int]:\n \"\"\"Padding dimensions\n\n GET:\n Returns the padding dimensions, ``(left, top, right, bottom)``.\n \"\"\"\n return astuple(self)[:4]\n\n # Extension methods ========================================================\n\n @override\n def _get_exact_dimensions_(self, render_size: Size) -> tuple[int, int, int, int]:\n return astuple(self)[:4]\n\n\n# Source: src/term_image/renderable/_types.py\nclass RenderArgs(RenderArgsData):\n \"\"\"RenderArgs(render_cls, /, *namespaces)\n RenderArgs(render_cls, init_render_args, /, *namespaces)\n\n Render arguments.\n\n Args:\n render_cls: A :term:`render class`.\n init_render_args (RenderArgs | None): A set of render arguments.\n If not ``None``,\n\n * it must be compatible [#ra-com]_ with *render_cls*,\n * it'll be used to initialize the render arguments.\n\n namespaces: Render argument namespaces compatible [#an-com]_ with *render_cls*.\n\n .. note:: If multiple namespaces associated with the same :term:`render\n class` are given, the last of them takes precedence.\n\n Raises:\n IncompatibleRenderArgsError: *init_render_args* is incompatible [#ra-com]_ with\n *render_cls*.\n IncompatibleArgsNamespaceError: Incompatible [#an-com]_ render argument\n namespace.\n\n A set of render arguments (an instance of this class) is basically a container of\n render argument namespaces (instances of\n :py:class:`~term_image.renderable.ArgsNamespace`); one for\n each :term:`render class`, which has render arguments, in the Method Resolution\n Order of its associated [#ra-ass]_ render class.\n\n The namespace for each render class is derived from the following sources, in\n [descending] order of precedence:\n\n * *namespaces*\n * *init_render_args*\n * default render argument namespaces\n\n NOTE:\n Instances are immutable but updated copies can be created via :py:meth:`update`.\n\n .. seealso::\n\n :py:attr:`~term_image.renderable.Renderable.Args`\n Render class-specific render arguments.\n\n .. Completed in /docs/source/api/renderable.rst\n \"\"\"\n\n # Class Attributes =========================================================\n\n __slots__ = ()\n\n _interned: ClassVar[dict[type[Renderable], Self]] = {}\n _namespaces: MappingProxyType[type[Renderable], ArgsNamespace]\n\n # Instance Attributes ======================================================\n\n render_cls: type[Renderable]\n \"\"\"The associated :term:`render class`\"\"\"\n\n # Special Methods ==========================================================\n\n def __new__(\n cls,\n render_cls: type[Renderable],\n init_or_namespace: RenderArgs | ArgsNamespace | None = None,\n *namespaces: ArgsNamespace,\n ) -> Self:\n if init_or_namespace is None:\n init_render_args = None\n elif isinstance(init_or_namespace, RenderArgs):\n init_render_args = init_or_namespace\n else:\n init_render_args = None\n namespaces = (init_or_namespace, *namespaces)\n\n if init_render_args and not issubclass(render_cls, init_render_args.render_cls):\n raise IncompatibleRenderArgsError(\n f\"'init_render_args' (associated with \"\n f\"{init_render_args.render_cls.__name__!r}) is incompatible with \"\n f\"{render_cls.__name__!r} \"\n )\n\n if not namespaces:\n # has default namespaces only\n if (\n not init_render_args\n or init_render_args is BASE_RENDER_ARGS\n or cls._interned.get(init_render_args.render_cls) is init_render_args\n ):\n try:\n return cls._interned[render_cls]\n except KeyError:\n pass\n\n if (\n init_render_args\n and type(init_render_args) is cls\n and init_render_args.render_cls is render_cls\n ):\n return init_render_args\n\n return super().__new__(cls)\n\n def __init__(\n self,\n render_cls: type[Renderable],\n init_or_namespace: RenderArgs | ArgsNamespace | None = None,\n *namespaces: ArgsNamespace,\n ) -> None:\n if init_or_namespace is None:\n init_render_args = None\n elif isinstance(init_or_namespace, RenderArgs):\n init_render_args = init_or_namespace\n else:\n init_render_args = None\n namespaces = (init_or_namespace, *namespaces)\n\n # has default namespaces only\n if not namespaces and (\n not init_render_args\n or init_render_args is BASE_RENDER_ARGS\n or (\n type(self)._interned.get(init_render_args.render_cls)\n is init_render_args\n )\n ):\n if render_cls in type(self)._interned: # has been initialized\n return\n intern = True\n else:\n intern = False\n\n if init_render_args is self:\n return\n\n namespaces_dict = render_cls._ALL_DEFAULT_ARGS.copy()\n\n # if `init_render_args` is non-default\n if init_render_args and BASE_RENDER_ARGS is not init_render_args is not (\n type(self)._interned.get(init_render_args.render_cls)\n ):\n namespaces_dict.update(init_render_args._namespaces)\n\n for index, namespace in enumerate(namespaces):\n if namespace._RENDER_CLS not in namespaces_dict:\n raise IncompatibleArgsNamespaceError(\n f\"'namespaces[{index}]' (associated with \"\n f\"{namespace._RENDER_CLS.__name__!r}) is incompatible with \"\n f\"{render_cls.__name__!r} \"\n )\n namespaces_dict[namespace._RENDER_CLS] = namespace\n\n super().__init__(render_cls, namespaces_dict)\n\n if intern:\n type(self)._interned[render_cls] = self\n\n def __init_subclass__(cls, **kwargs: Any) -> None:\n cls._interned = {}\n super().__init_subclass__(**kwargs)\n\n def __contains__(self, namespace: ArgsNamespace) -> bool:\n \"\"\"Checks if a render argument namespace is contained in this set of render\n arguments.\n\n Args:\n namespace: A render argument namespace.\n\n Returns:\n ``True`` if the given namespace is equal to any of the namespaces\n contained in this set of render arguments. Otherwise, ``False``.\n \"\"\"\n return None is not self._namespaces.get(namespace._RENDER_CLS) == namespace\n\n def __eq__(self, other: object) -> bool:\n \"\"\"Compares this set of render arguments with another.\n\n Args:\n other: Another set of render arguments.\n\n Returns:\n ``True`` if both are associated with the same :term:`render class`\n and have equal argument values. Otherwise, ``False``.\n \"\"\"\n if isinstance(other, RenderArgs):\n return (\n self is other\n or self.render_cls is other.render_cls\n and self._namespaces == other._namespaces\n )\n\n return NotImplemented\n\n def __getitem__(self, render_cls: type[Renderable]) -> Any:\n \"\"\"Returns a constituent namespace.\n\n Args:\n render_cls: A :term:`render class` of which :py:attr:`render_cls` is a\n subclass (which may be :py:attr:`render_cls` itself) and which has\n render arguments.\n\n Returns:\n The constituent namespace associated with *render_cls*.\n\n Raises:\n TypeError: *render_cls* is not a render class.\n ValueError: :py:attr:`render_cls` is not a subclass of *render_cls*.\n NoArgsNamespaceError: *render_cls* has no render arguments.\n\n NOTE:\n The return type hint is :py:class:`~typing.Any` only for compatibility\n with static type checking, as this aspect of the interface seems too\n dynamic to be correctly expressed with the exisiting type system.\n\n Regardless, the return value is guaranteed to always be an instance\n of a render argument namespace class associated with *render_cls*.\n For instance, the following would always be valid for\n :py:class:`~term_image.renderable.Renderable`::\n\n renderable_args: RenderableArgs = render_args[Renderable]\n\n and similar idioms are encouraged to be used for other render classes.\n \"\"\"\n try:\n return self._namespaces[render_cls]\n except TypeError:\n raise arg_type_error(\"render_cls\", render_cls) from None\n except KeyError:\n if not isinstance(render_cls, RenderableMeta):\n raise arg_type_error(\"render_cls\", render_cls) from None\n\n if issubclass(self.render_cls, render_cls):\n raise NoArgsNamespaceError(\n f\"{render_cls.__name__!r} has no render arguments\"\n ) from None\n\n raise ValueError(\n f\"{self.render_cls.__name__!r} is not a subclass of \"\n f\"{render_cls.__name__!r}\"\n ) from None\n\n def __hash__(self) -> int:\n \"\"\"Computes the hash of the render arguments.\n\n Returns:\n The computed hash.\n\n IMPORTANT:\n Like tuples, an instance is hashable if and only if the constituent\n namespaces are hashable.\n \"\"\"\n # Namespaces are always in the same order, wrt their respective associated\n # render classes, for all instances associated with the same render class.\n return hash((self.render_cls, tuple(self._namespaces.values())))\n\n def __iter__(self) -> Iterator[ArgsNamespace]:\n \"\"\"Returns an iterator that yields the constituent namespaces.\n\n Returns:\n An iterator that yields the constituent namespaces.\n\n WARNING:\n The number and order of namespaces is guaranteed to be the same across all\n instances associated [#ra-ass]_ with the same :term:`render class` but\n beyond this, should not be relied upon as the details (such as the\n specific number or order) may change without notice.\n\n The order is an implementation detail of the Renderable API and the number\n should be considered alike with respect to the associated render class.\n \"\"\"\n return iter(self._namespaces.values())\n\n def __repr__(self) -> str:\n return \"\".join(\n (\n f\"{type(self).__name__}({self.render_cls.__name__}\",\n \", \" if self._namespaces else \"\",\n \", \".join(map(repr, self._namespaces.values())),\n \")\",\n )\n )\n\n # Public Methods ===========================================================\n\n def convert(self, render_cls: type[Renderable]) -> RenderArgs:\n \"\"\"Converts the set of render arguments to one for a related render class.\n\n Args:\n render_cls: A :term:`render class` of which :py:attr:`render_cls` is a\n parent or child (which may be :py:attr:`render_cls` itself).\n\n Returns:\n A set of render arguments associated [#ra-ass]_ with *render_cls* and\n initialized with all constituent namespaces (of this set of render\n arguments, *self*) that are compatible [#an-com]_ with *render_cls*.\n\n Raises:\n ValueError: *render_cls* is not a parent or child of :py:attr:`render_cls`.\n \"\"\"\n if render_cls is self.render_cls:\n return self\n\n if issubclass(render_cls, self.render_cls):\n return RenderArgs(render_cls, self)\n\n if issubclass(self.render_cls, render_cls):\n render_cls_args_mro = render_cls._ALL_DEFAULT_ARGS\n return RenderArgs(\n render_cls,\n *[\n namespace\n for cls, namespace in self._namespaces.items()\n if cls in render_cls_args_mro\n ],\n )\n\n raise ValueError(\n f\"{render_cls.__name__!r} is not a parent or child of \"\n f\"{self.render_cls.__name__!r}\"\n )\n\n @overload\n def update(\n self,\n namespace: ArgsNamespace,\n /,\n *namespaces: ArgsNamespace,\n ) -> RenderArgs: ...\n\n @overload\n def update(\n self,\n render_cls: type[Renderable],\n /,\n **fields: Any,\n ) -> RenderArgs: ...\n\n def update(\n self,\n render_cls_or_namespace: type[Renderable] | ArgsNamespace,\n /,\n *namespaces: ArgsNamespace,\n **fields: Any,\n ) -> RenderArgs:\n \"\"\"update(namespace, /, *namespaces) -> RenderArgs\n update(render_cls, /, **fields) -> RenderArgs\n\n Replaces or updates render argument namespaces.\n\n Args:\n namespace (ArgsNamespace): Prepended to *namespaces*.\n namespaces: Render argument namespaces compatible [#an-com]_ with\n :py:attr:`render_cls`.\n\n .. note:: If multiple namespaces associated with the same :term:`render\n class` are given, the last of them takes precedence.\n\n render_cls (type[Renderable]): A :term:`render class` of which\n :py:attr:`render_cls` is a subclass (which may be :py:attr:`render_cls`\n itself) and which has render arguments.\n fields: Render argument fields.\n\n The keywords must be names of render argument fields for *render_cls*.\n\n Returns:\n For the **first** form, an instance with the namespaces for the respective\n associated :term:`render classes` of the given namespaces replaced.\n\n For the **second** form, an instance with the given render argument fields\n for *render_cls* updated, if any.\n\n Raises:\n TypeError: The arguments given do not conform to any of the expected forms.\n\n Propagates exceptions raised by:\n\n * the class constructor, for the **first** form.\n * :py:meth:`__getitem__` and :py:meth:`ArgsNamespace.update()\n `, for the **second** form.\n \"\"\"\n if isinstance(render_cls_or_namespace, RenderableMeta):\n if namespaces:\n raise TypeError(\n \"No other positional argument is expected when the first argument \"\n \"is a render class\"\n )\n render_cls = render_cls_or_namespace\n else:\n if fields:\n raise TypeError(\n \"No keyword argument is expected when the first argument is \"\n \"a render argument namespace\"\n )\n render_cls = None\n namespaces = (render_cls_or_namespace, *namespaces)\n\n return RenderArgs(\n self.render_cls,\n self,\n *((self[render_cls].update(**fields),) if render_cls else namespaces),\n )", "n_imports_parsed": 14, "n_files_resolved": 7, "n_chars_extracted": 16829}, "tests/test_image/test_base.py::495": {"resolved_imports": ["src/term_image/__init__.py", "src/term_image/_ctlseqs.py", "src/term_image/exceptions.py", "src/term_image/image/block.py", "src/term_image/image/common.py"], "used_names": ["reset_cell_size_ratio", "set_cell_ratio"], "enclosing_function": "test_frame_size_absolute", "extracted_code": "# Source: src/term_image/__init__.py\ndef set_cell_ratio(ratio: float | AutoCellRatio) -> None:\n \"\"\"Sets the global :term:`cell ratio`.\n\n Args:\n ratio: Can be one of the following values.\n\n * A positive :py:class:`float` value.\n * :py:attr:`AutoCellRatio.FIXED`, the ratio is immediately determined from\n the :term:`active terminal`.\n * :py:attr:`AutoCellRatio.DYNAMIC`, the ratio is determined from the\n :term:`active terminal` whenever :py:func:`get_cell_ratio` is called,\n though with some caching involved, such that the ratio is re-determined\n only if the terminal size changes.\n\n Raises:\n ValueError: *ratio* is a non-positive :py:class:`float`.\n term_image.exceptions.TermImageError: Auto cell ratio is not supported\n in the :term:`active terminal` or on the current platform.\n\n This value is taken into consideration when setting image sizes for **text-based**\n render styles, in order to preserve the aspect ratio of images drawn to the\n terminal.\n\n NOTE:\n Changing the cell ratio does not automatically affect any image that has a\n :term:`fixed size`. For a change in cell ratio to take effect, the image's\n size has to be re-set.\n\n IMPORTANT:\n See :ref:`auto-cell-ratio` for details about the auto modes.\n \"\"\"\n global _cell_ratio\n\n if isinstance(ratio, AutoCellRatio):\n if AutoCellRatio.is_supported is None:\n AutoCellRatio.is_supported = get_cell_size() is not None\n\n if not AutoCellRatio.is_supported:\n raise TermImageError(\n \"Auto cell ratio is not supported in the active terminal or on the \"\n \"current platform\"\n )\n elif ratio is AutoCellRatio.FIXED:\n # `(1, 2)` is a fallback in case the terminal doesn't respond in time\n _cell_ratio = truediv(*(get_cell_size() or (1, 2)))\n else:\n _cell_ratio = None\n else:\n if ratio <= 0.0:\n raise arg_value_error_range(\"ratio\", ratio)\n _cell_ratio = ratio", "n_imports_parsed": 16, "n_files_resolved": 5, "n_chars_extracted": 2121}, "tests/test_padding.py::33": {"resolved_imports": ["src/term_image/_ctlseqs.py", "src/term_image/geometry.py", "src/term_image/padding.py"], "used_names": [], "enclosing_function": "test_fill", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/test_image/test_others.py::34": {"resolved_imports": ["src/term_image/image/common.py", "src/term_image/image/__init__.py"], "used_names": ["ImageSource"], "enclosing_function": "test_image_source", "extracted_code": "# Source: src/term_image/image/common.py\nclass ImageSource(Enum):\n \"\"\"Image source type.\"\"\"\n\n #: The instance was derived from a path to a local image file.\n #:\n #: :meta hide-value:\n FILE_PATH = SourceAttr(\"_source\")\n\n #: The instance was derived from a PIL image instance.\n #:\n #: :meta hide-value:\n PIL_IMAGE = SourceAttr(\"_source\")\n\n #: The instance was derived from an image URL.\n #:\n #: :meta hide-value:\n URL = SourceAttr(\"_url\")", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 475}, "tests/test_geometry.py::47": {"resolved_imports": ["src/term_image/geometry.py"], "used_names": ["Size"], "enclosing_function": "test_width", "extracted_code": "# Source: src/term_image/geometry.py\nclass Size(RawSize):\n \"\"\"The dimensions of a rectangular region.\n\n Raises:\n ValueError: Either dimension is non-positive.\n\n Same as :py:class:`RawSize`, except that both dimensions must be **positive**.\n\n IMPORTANT:\n In the case of multiple inheritance i.e if subclassing this class along with\n other classes, this class should appear last (i.e to the far right) in the\n base class list.\n \"\"\"\n\n __slots__ = ()\n\n def __new__(cls, width: int, height: int) -> Self:\n if width < 1:\n raise arg_value_error_range(\"width\", width)\n if height < 1:\n raise arg_value_error_range(\"height\", height)\n\n # Using `tuple` directly instead of `super()` for performance\n return tuple.__new__(cls, (width, height))", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 829}}}